gorecover_test.go 854 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package common
  2. import (
  3. "os"
  4. "testing"
  5. "time"
  6. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  7. "github.com/op/go-logging"
  8. )
  9. func TestMain(m *testing.M) {
  10. logger.InitLogger(logging.ERROR)
  11. os.Exit(m.Run())
  12. }
  13. func TestGoRecover_RunsFn(t *testing.T) {
  14. done := make(chan struct{})
  15. GoRecover("test-run", func() { close(done) })
  16. select {
  17. case <-done:
  18. case <-time.After(2 * time.Second):
  19. t.Fatal("fn did not run")
  20. }
  21. }
  22. func TestGoRecover_RecoversPanic(t *testing.T) {
  23. done := make(chan struct{})
  24. // If GoRecover did not recover, this panic would crash the test binary.
  25. GoRecover("test-panic", func() {
  26. defer close(done)
  27. panic("boom")
  28. })
  29. select {
  30. case <-done:
  31. case <-time.After(2 * time.Second):
  32. t.Fatal("goroutine did not complete")
  33. }
  34. // Let the deferred recover+log run before the test ends.
  35. time.Sleep(50 * time.Millisecond)
  36. }