statinterceptor_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 TestLogDuration(t *testing.T) {
  29. addrs, err := net.InterfaceAddrs()
  30. assert.Nil(t, err)
  31. assert.True(t, len(addrs) > 0)
  32. tests := []struct {
  33. name string
  34. ctx context.Context
  35. req interface{}
  36. duration time.Duration
  37. }{
  38. {
  39. name: "normal",
  40. ctx: context.Background(),
  41. req: "foo",
  42. },
  43. {
  44. name: "bad req",
  45. ctx: context.Background(),
  46. req: make(chan lang.PlaceholderType), // not marshalable
  47. },
  48. {
  49. name: "timeout",
  50. ctx: context.Background(),
  51. req: "foo",
  52. duration: time.Second,
  53. },
  54. {
  55. name: "timeout",
  56. ctx: peer.NewContext(context.Background(), &peer.Peer{
  57. Addr: addrs[0],
  58. }),
  59. req: "foo",
  60. },
  61. {
  62. name: "timeout",
  63. ctx: context.Background(),
  64. req: "foo",
  65. duration: slowThreshold.Load() + time.Second,
  66. },
  67. }
  68. for _, test := range tests {
  69. test := test
  70. t.Run(test.name, func(t *testing.T) {
  71. t.Parallel()
  72. assert.NotPanics(t, func() {
  73. logDuration(test.ctx, "foo", test.req, test.duration)
  74. })
  75. })
  76. }
  77. }