client_test.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package zrpc
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/zeromicro/go-zero/core/discov"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "github.com/zeromicro/go-zero/zrpc/internal/mock"
  13. "google.golang.org/grpc"
  14. "google.golang.org/grpc/codes"
  15. "google.golang.org/grpc/credentials/insecure"
  16. "google.golang.org/grpc/status"
  17. "google.golang.org/grpc/test/bufconn"
  18. )
  19. func init() {
  20. logx.Disable()
  21. }
  22. func dialer() func(context.Context, string) (net.Conn, error) {
  23. listener := bufconn.Listen(1024 * 1024)
  24. server := grpc.NewServer()
  25. mock.RegisterDepositServiceServer(server, &mock.DepositServer{})
  26. go func() {
  27. if err := server.Serve(listener); err != nil {
  28. log.Fatal(err)
  29. }
  30. }()
  31. return func(context.Context, string) (net.Conn, error) {
  32. return listener.Dial()
  33. }
  34. }
  35. func TestDepositServer_Deposit(t *testing.T) {
  36. tests := []struct {
  37. name string
  38. amount float32
  39. res *mock.DepositResponse
  40. errCode codes.Code
  41. errMsg string
  42. }{
  43. {
  44. "invalid request with negative amount",
  45. -1.11,
  46. nil,
  47. codes.InvalidArgument,
  48. fmt.Sprintf("cannot deposit %v", -1.11),
  49. },
  50. {
  51. "valid request with non negative amount",
  52. 0.00,
  53. &mock.DepositResponse{Ok: true},
  54. codes.OK,
  55. "",
  56. },
  57. {
  58. "valid request with long handling time",
  59. 2000.00,
  60. nil,
  61. codes.DeadlineExceeded,
  62. "context deadline exceeded",
  63. },
  64. }
  65. directClient := MustNewClient(
  66. RpcClientConf{
  67. Endpoints: []string{"foo"},
  68. App: "foo",
  69. Token: "bar",
  70. Timeout: 1000,
  71. Middlewares: ClientMiddlewaresConf{
  72. Trace: true,
  73. Duration: true,
  74. Prometheus: true,
  75. Breaker: true,
  76. Timeout: true,
  77. },
  78. },
  79. WithDialOption(grpc.WithContextDialer(dialer())),
  80. WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any,
  81. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  82. return invoker(ctx, method, req, reply, cc, opts...)
  83. }),
  84. )
  85. nonBlockClient := MustNewClient(
  86. RpcClientConf{
  87. Endpoints: []string{"foo"},
  88. App: "foo",
  89. Token: "bar",
  90. Timeout: 1000,
  91. NonBlock: true,
  92. Middlewares: ClientMiddlewaresConf{
  93. Trace: true,
  94. Duration: true,
  95. Prometheus: true,
  96. Breaker: true,
  97. Timeout: true,
  98. },
  99. },
  100. WithDialOption(grpc.WithContextDialer(dialer())),
  101. WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any,
  102. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  103. return invoker(ctx, method, req, reply, cc, opts...)
  104. }),
  105. )
  106. tarConfClient := MustNewClient(
  107. RpcClientConf{
  108. Target: "foo",
  109. App: "foo",
  110. Token: "bar",
  111. Timeout: 1000,
  112. Middlewares: ClientMiddlewaresConf{
  113. Trace: true,
  114. Duration: true,
  115. Prometheus: true,
  116. Breaker: true,
  117. Timeout: true,
  118. },
  119. },
  120. WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
  121. WithDialOption(grpc.WithContextDialer(dialer())),
  122. WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any,
  123. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  124. return invoker(ctx, method, req, reply, cc, opts...)
  125. }),
  126. )
  127. targetClient, err := NewClientWithTarget("foo",
  128. WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
  129. WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(
  130. func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn,
  131. invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  132. return invoker(ctx, method, req, reply, cc, opts...)
  133. }), WithTimeout(1000*time.Millisecond))
  134. assert.Nil(t, err)
  135. clients := []Client{
  136. directClient,
  137. nonBlockClient,
  138. tarConfClient,
  139. targetClient,
  140. }
  141. DontLogClientContentForMethod("foo")
  142. SetClientSlowThreshold(time.Second)
  143. for _, tt := range tests {
  144. tt := tt
  145. for _, client := range clients {
  146. client := client
  147. t.Run(tt.name, func(t *testing.T) {
  148. t.Parallel()
  149. cli := mock.NewDepositServiceClient(client.Conn())
  150. request := &mock.DepositRequest{Amount: tt.amount}
  151. response, err := cli.Deposit(context.Background(), request)
  152. if response != nil {
  153. assert.True(t, len(response.String()) > 0)
  154. if response.GetOk() != tt.res.GetOk() {
  155. t.Error("response: expected", tt.res.GetOk(), "received", response.GetOk())
  156. }
  157. }
  158. if err != nil {
  159. if e, ok := status.FromError(err); ok {
  160. if e.Code() != tt.errCode {
  161. t.Error("error code: expected", codes.InvalidArgument, "received", e.Code())
  162. }
  163. if e.Message() != tt.errMsg {
  164. t.Error("error message: expected", tt.errMsg, "received", e.Message())
  165. }
  166. }
  167. }
  168. })
  169. }
  170. }
  171. }
  172. func TestNewClientWithError(t *testing.T) {
  173. _, err := NewClient(
  174. RpcClientConf{
  175. App: "foo",
  176. Token: "bar",
  177. Timeout: 1000,
  178. },
  179. WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
  180. WithDialOption(grpc.WithContextDialer(dialer())),
  181. WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any,
  182. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  183. return invoker(ctx, method, req, reply, cc, opts...)
  184. }),
  185. )
  186. assert.NotNil(t, err)
  187. _, err = NewClient(
  188. RpcClientConf{
  189. Etcd: discov.EtcdConf{
  190. Hosts: []string{"localhost:2379"},
  191. Key: "mock",
  192. },
  193. App: "foo",
  194. Token: "bar",
  195. Timeout: 1,
  196. },
  197. WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
  198. WithDialOption(grpc.WithContextDialer(dialer())),
  199. WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any,
  200. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  201. return invoker(ctx, method, req, reply, cc, opts...)
  202. }),
  203. )
  204. assert.NotNil(t, err)
  205. }