routines_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package threading
  2. import (
  3. "bytes"
  4. "context"
  5. "io"
  6. "log"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/wuntsong-org/go-zero-plus/core/lang"
  10. "github.com/wuntsong-org/go-zero-plus/core/logx"
  11. )
  12. func TestRoutineId(t *testing.T) {
  13. assert.True(t, RoutineId() > 0)
  14. }
  15. func TestRunSafe(t *testing.T) {
  16. log.SetOutput(io.Discard)
  17. i := 0
  18. defer func() {
  19. assert.Equal(t, 1, i)
  20. }()
  21. ch := make(chan lang.PlaceholderType)
  22. go RunSafe(func() {
  23. defer func() {
  24. ch <- lang.Placeholder
  25. }()
  26. panic("panic")
  27. })
  28. <-ch
  29. i++
  30. }
  31. func TestRunSafeCtx(t *testing.T) {
  32. var buf bytes.Buffer
  33. logx.SetWriter(logx.NewWriter(&buf))
  34. ctx := context.Background()
  35. ch := make(chan lang.PlaceholderType)
  36. i := 0
  37. defer func() {
  38. assert.Equal(t, 1, i)
  39. }()
  40. go RunSafeCtx(ctx, func() {
  41. defer func() {
  42. ch <- lang.Placeholder
  43. }()
  44. panic("panic")
  45. })
  46. <-ch
  47. i++
  48. }
  49. func TestGoSafeCtx(t *testing.T) {
  50. var buf bytes.Buffer
  51. logx.SetWriter(logx.NewWriter(&buf))
  52. ctx := context.Background()
  53. ch := make(chan lang.PlaceholderType)
  54. i := 0
  55. defer func() {
  56. assert.Equal(t, 1, i)
  57. }()
  58. GoSafeCtx(ctx, func() {
  59. defer func() {
  60. ch <- lang.Placeholder
  61. }()
  62. panic("panic")
  63. })
  64. <-ch
  65. i++
  66. }