github.com/lingyao2333/mo-zero@v1.4.1/zrpc/internal/clientinterceptors/breakerinterceptor_test.go (about)

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