saferun_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package infra
  15. import (
  16. "errors"
  17. "fmt"
  18. "testing"
  19. "github.com/stretchr/testify/assert"
  20. )
  21. func TestDrainError(t *testing.T) {
  22. errChan := make(chan error, 1)
  23. err := errors.New("test error")
  24. go DrainError(nil, err, errChan)
  25. assert.Equal(t, err, <-errChan)
  26. }
  27. func TestSafeRun(t *testing.T) {
  28. tests := []struct {
  29. fn func() error
  30. expected error
  31. }{
  32. {
  33. func() error {
  34. return nil
  35. },
  36. nil,
  37. },
  38. {
  39. func() error {
  40. return errors.New("test error")
  41. },
  42. errors.New("test error"),
  43. },
  44. {
  45. func() error {
  46. panic(errors.New("test error"))
  47. },
  48. errors.New("test error"),
  49. },
  50. {
  51. func() error {
  52. panic("panic error")
  53. },
  54. errors.New("panic error"),
  55. },
  56. {
  57. func() error {
  58. panic(2)
  59. },
  60. fmt.Errorf("%#v", 2),
  61. },
  62. }
  63. for _, tt := range tests {
  64. assert.Equal(t, tt.expected, SafeRun(tt.fn))
  65. }
  66. }