client_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package zrpc
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/tal-tech/go-zero/core/logx"
  10. "github.com/tal-tech/go-zero/zrpc/internal/mock"
  11. "google.golang.org/grpc"
  12. "google.golang.org/grpc/codes"
  13. "google.golang.org/grpc/status"
  14. "google.golang.org/grpc/test/bufconn"
  15. )
  16. func init() {
  17. logx.Disable()
  18. }
  19. func dialer() func(context.Context, string) (net.Conn, error) {
  20. listener := bufconn.Listen(1024 * 1024)
  21. server := grpc.NewServer()
  22. mock.RegisterDepositServiceServer(server, &mock.DepositServer{})
  23. go func() {
  24. if err := server.Serve(listener); err != nil {
  25. log.Fatal(err)
  26. }
  27. }()
  28. return func(context.Context, string) (net.Conn, error) {
  29. return listener.Dial()
  30. }
  31. }
  32. func TestDepositServer_Deposit(t *testing.T) {
  33. tests := []struct {
  34. name string
  35. amount float32
  36. res *mock.DepositResponse
  37. errCode codes.Code
  38. errMsg string
  39. }{
  40. {
  41. "invalid request with negative amount",
  42. -1.11,
  43. nil,
  44. codes.InvalidArgument,
  45. fmt.Sprintf("cannot deposit %v", -1.11),
  46. },
  47. {
  48. "valid request with non negative amount",
  49. 0.00,
  50. &mock.DepositResponse{Ok: true},
  51. codes.OK,
  52. "",
  53. },
  54. }
  55. directClient := MustNewClient(RpcClientConf{
  56. Endpoints: []string{"foo"},
  57. App: "foo",
  58. Token: "bar",
  59. Timeout: 1000,
  60. }, WithDialOption(grpc.WithInsecure()), WithDialOption(grpc.WithContextDialer(dialer())))
  61. targetClient, err := NewClientWithTarget("foo", WithDialOption(grpc.WithInsecure()),
  62. WithDialOption(grpc.WithContextDialer(dialer())))
  63. assert.Nil(t, err)
  64. clients := []Client{
  65. directClient,
  66. targetClient,
  67. }
  68. for _, tt := range tests {
  69. for _, client := range clients {
  70. t.Run(tt.name, func(t *testing.T) {
  71. cli := mock.NewDepositServiceClient(client.Conn())
  72. request := &mock.DepositRequest{Amount: tt.amount}
  73. response, err := cli.Deposit(context.Background(), request)
  74. if response != nil {
  75. assert.True(t, len(response.String()) > 0)
  76. if response.GetOk() != tt.res.GetOk() {
  77. t.Error("response: expected", tt.res.GetOk(), "received", response.GetOk())
  78. }
  79. }
  80. if err != nil {
  81. if e, ok := status.FromError(err); ok {
  82. if e.Code() != tt.errCode {
  83. t.Error("error code: expected", codes.InvalidArgument, "received", e.Code())
  84. }
  85. if e.Message() != tt.errMsg {
  86. t.Error("error message: expected", tt.errMsg, "received", e.Message())
  87. }
  88. }
  89. }
  90. })
  91. }
  92. }
  93. }