breakerinterceptor_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package clientinterceptors
  2. import (
  3. "context"
  4. "errors"
  5. "testing"
  6. "git.i2edu.net/i2/go-zero/core/breaker"
  7. "git.i2edu.net/i2/go-zero/core/stat"
  8. rcodes "git.i2edu.net/i2/go-zero/zrpc/internal/codes"
  9. "github.com/stretchr/testify/assert"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/codes"
  12. "google.golang.org/grpc/status"
  13. )
  14. func init() {
  15. stat.SetReporter(nil)
  16. }
  17. type mockError struct {
  18. st *status.Status
  19. }
  20. func (m mockError) GRPCStatus() *status.Status {
  21. return m.st
  22. }
  23. func (m mockError) Error() string {
  24. return "mocked error"
  25. }
  26. func TestBreakerInterceptorNotFound(t *testing.T) {
  27. err := mockError{st: status.New(codes.NotFound, "any")}
  28. for i := 0; i < 1000; i++ {
  29. assert.Equal(t, err, breaker.DoWithAcceptable("call", func() error {
  30. return err
  31. }, rcodes.Acceptable))
  32. }
  33. }
  34. func TestBreakerInterceptorDeadlineExceeded(t *testing.T) {
  35. err := mockError{st: status.New(codes.DeadlineExceeded, "any")}
  36. errs := make(map[error]int)
  37. for i := 0; i < 1000; i++ {
  38. e := breaker.DoWithAcceptable("call", func() error {
  39. return err
  40. }, rcodes.Acceptable)
  41. errs[e]++
  42. }
  43. assert.Equal(t, 2, len(errs))
  44. assert.True(t, errs[err] > 0)
  45. assert.True(t, errs[breaker.ErrServiceUnavailable] > 0)
  46. }
  47. func TestBreakerInterceptor(t *testing.T) {
  48. tests := []struct {
  49. name string
  50. err error
  51. }{
  52. {
  53. name: "nil",
  54. err: nil,
  55. },
  56. {
  57. name: "with error",
  58. err: errors.New("mock"),
  59. },
  60. }
  61. for _, test := range tests {
  62. t.Run(test.name, func(t *testing.T) {
  63. cc := new(grpc.ClientConn)
  64. err := BreakerInterceptor(context.Background(), "/foo", nil, nil, cc,
  65. func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
  66. opts ...grpc.CallOption) error {
  67. return test.err
  68. })
  69. assert.Equal(t, test.err, err)
  70. })
  71. }
  72. }