recover_test.go 736 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package rescue
  2. import (
  3. "context"
  4. "sync/atomic"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/wuntsong-org/go-zero-plus/core/logx"
  8. )
  9. func init() {
  10. logx.Disable()
  11. }
  12. func TestRescue(t *testing.T) {
  13. var count int32
  14. assert.NotPanics(t, func() {
  15. defer Recover(func() {
  16. atomic.AddInt32(&count, 2)
  17. }, func() {
  18. atomic.AddInt32(&count, 3)
  19. })
  20. panic("hello")
  21. })
  22. assert.Equal(t, int32(5), atomic.LoadInt32(&count))
  23. }
  24. func TestRescueCtx(t *testing.T) {
  25. var count int32
  26. assert.NotPanics(t, func() {
  27. defer RecoverCtx(context.Background(), func() {
  28. atomic.AddInt32(&count, 2)
  29. }, func() {
  30. atomic.AddInt32(&count, 3)
  31. })
  32. panic("hello")
  33. })
  34. assert.Equal(t, int32(5), atomic.LoadInt32(&count))
  35. }