statinterceptor_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "net"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/zeromicro/go-zero/core/lang"
  9. "github.com/zeromicro/go-zero/core/stat"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/peer"
  12. )
  13. func TestSetSlowThreshold(t *testing.T) {
  14. assert.Equal(t, defaultSlowThreshold, slowThreshold.Load())
  15. SetSlowThreshold(time.Second)
  16. assert.Equal(t, time.Second, slowThreshold.Load())
  17. }
  18. func TestUnaryStatInterceptor(t *testing.T) {
  19. metrics := stat.NewMetrics("mock")
  20. interceptor := UnaryStatInterceptor(metrics)
  21. _, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{
  22. FullMethod: "/",
  23. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  24. return nil, nil
  25. })
  26. assert.Nil(t, err)
  27. }
  28. func TestUnaryStatInterceptor_crash(t *testing.T) {
  29. metrics := stat.NewMetrics("mock")
  30. interceptor := UnaryStatInterceptor(metrics)
  31. _, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{
  32. FullMethod: "/",
  33. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  34. panic("error")
  35. })
  36. assert.NotNil(t, err)
  37. }
  38. func TestLogDuration(t *testing.T) {
  39. addrs, err := net.InterfaceAddrs()
  40. assert.Nil(t, err)
  41. assert.True(t, len(addrs) > 0)
  42. tests := []struct {
  43. name string
  44. ctx context.Context
  45. req interface{}
  46. duration time.Duration
  47. }{
  48. {
  49. name: "normal",
  50. ctx: context.Background(),
  51. req: "foo",
  52. },
  53. {
  54. name: "bad req",
  55. ctx: context.Background(),
  56. req: make(chan lang.PlaceholderType), // not marshalable
  57. },
  58. {
  59. name: "timeout",
  60. ctx: context.Background(),
  61. req: "foo",
  62. duration: time.Second,
  63. },
  64. {
  65. name: "timeout",
  66. ctx: peer.NewContext(context.Background(), &peer.Peer{
  67. Addr: addrs[0],
  68. }),
  69. req: "foo",
  70. },
  71. {
  72. name: "timeout",
  73. ctx: context.Background(),
  74. req: "foo",
  75. duration: slowThreshold.Load() + time.Second,
  76. },
  77. }
  78. for _, test := range tests {
  79. test := test
  80. t.Run(test.name, func(t *testing.T) {
  81. t.Parallel()
  82. assert.NotPanics(t, func() {
  83. logDuration(test.ctx, "foo", test.req, test.duration)
  84. })
  85. })
  86. }
  87. }