call_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "context"
  21. "fmt"
  22. "io"
  23. "math"
  24. "net"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "testing"
  29. "time"
  30. "google.golang.org/grpc/codes"
  31. "google.golang.org/grpc/internal/leakcheck"
  32. "google.golang.org/grpc/internal/transport"
  33. "google.golang.org/grpc/status"
  34. )
  35. var (
  36. expectedRequest = "ping"
  37. expectedResponse = "pong"
  38. weirdError = "format verbs: %v%s"
  39. sizeLargeErr = 1024 * 1024
  40. canceled = 0
  41. )
  42. type testCodec struct {
  43. }
  44. func (testCodec) Marshal(v interface{}) ([]byte, error) {
  45. return []byte(*(v.(*string))), nil
  46. }
  47. func (testCodec) Unmarshal(data []byte, v interface{}) error {
  48. *(v.(*string)) = string(data)
  49. return nil
  50. }
  51. func (testCodec) String() string {
  52. return "test"
  53. }
  54. type testStreamHandler struct {
  55. port string
  56. t transport.ServerTransport
  57. }
  58. func (h *testStreamHandler) handleStream(t *testing.T, s *transport.Stream) {
  59. p := &parser{r: s}
  60. for {
  61. pf, req, err := p.recvMsg(math.MaxInt32)
  62. if err == io.EOF {
  63. break
  64. }
  65. if err != nil {
  66. return
  67. }
  68. if pf != compressionNone {
  69. t.Errorf("Received the mistaken message format %d, want %d", pf, compressionNone)
  70. return
  71. }
  72. var v string
  73. codec := testCodec{}
  74. if err := codec.Unmarshal(req, &v); err != nil {
  75. t.Errorf("Failed to unmarshal the received message: %v", err)
  76. return
  77. }
  78. if v == "weird error" {
  79. h.t.WriteStatus(s, status.New(codes.Internal, weirdError))
  80. return
  81. }
  82. if v == "canceled" {
  83. canceled++
  84. h.t.WriteStatus(s, status.New(codes.Internal, ""))
  85. return
  86. }
  87. if v == "port" {
  88. h.t.WriteStatus(s, status.New(codes.Internal, h.port))
  89. return
  90. }
  91. if v != expectedRequest {
  92. h.t.WriteStatus(s, status.New(codes.Internal, strings.Repeat("A", sizeLargeErr)))
  93. return
  94. }
  95. }
  96. // send a response back to end the stream.
  97. data, err := encode(testCodec{}, &expectedResponse)
  98. if err != nil {
  99. t.Errorf("Failed to encode the response: %v", err)
  100. return
  101. }
  102. hdr, payload := msgHeader(data, nil)
  103. h.t.Write(s, hdr, payload, &transport.Options{})
  104. h.t.WriteStatus(s, status.New(codes.OK, ""))
  105. }
  106. type server struct {
  107. lis net.Listener
  108. port string
  109. addr string
  110. startedErr chan error // sent nil or an error after server starts
  111. mu sync.Mutex
  112. conns map[transport.ServerTransport]bool
  113. }
  114. func newTestServer() *server {
  115. return &server{startedErr: make(chan error, 1)}
  116. }
  117. // start starts server. Other goroutines should block on s.startedErr for further operations.
  118. func (s *server) start(t *testing.T, port int, maxStreams uint32) {
  119. var err error
  120. if port == 0 {
  121. s.lis, err = net.Listen("tcp", "localhost:0")
  122. } else {
  123. s.lis, err = net.Listen("tcp", "localhost:"+strconv.Itoa(port))
  124. }
  125. if err != nil {
  126. s.startedErr <- fmt.Errorf("failed to listen: %v", err)
  127. return
  128. }
  129. s.addr = s.lis.Addr().String()
  130. _, p, err := net.SplitHostPort(s.addr)
  131. if err != nil {
  132. s.startedErr <- fmt.Errorf("failed to parse listener address: %v", err)
  133. return
  134. }
  135. s.port = p
  136. s.conns = make(map[transport.ServerTransport]bool)
  137. s.startedErr <- nil
  138. for {
  139. conn, err := s.lis.Accept()
  140. if err != nil {
  141. return
  142. }
  143. config := &transport.ServerConfig{
  144. MaxStreams: maxStreams,
  145. }
  146. st, err := transport.NewServerTransport("http2", conn, config)
  147. if err != nil {
  148. continue
  149. }
  150. s.mu.Lock()
  151. if s.conns == nil {
  152. s.mu.Unlock()
  153. st.Close()
  154. return
  155. }
  156. s.conns[st] = true
  157. s.mu.Unlock()
  158. h := &testStreamHandler{
  159. port: s.port,
  160. t: st,
  161. }
  162. go st.HandleStreams(func(s *transport.Stream) {
  163. go h.handleStream(t, s)
  164. }, func(ctx context.Context, method string) context.Context {
  165. return ctx
  166. })
  167. }
  168. }
  169. func (s *server) wait(t *testing.T, timeout time.Duration) {
  170. select {
  171. case err := <-s.startedErr:
  172. if err != nil {
  173. t.Fatal(err)
  174. }
  175. case <-time.After(timeout):
  176. t.Fatalf("Timed out after %v waiting for server to be ready", timeout)
  177. }
  178. }
  179. func (s *server) stop() {
  180. s.lis.Close()
  181. s.mu.Lock()
  182. for c := range s.conns {
  183. c.Close()
  184. }
  185. s.conns = nil
  186. s.mu.Unlock()
  187. }
  188. func setUp(t *testing.T, port int, maxStreams uint32) (*server, *ClientConn) {
  189. server := newTestServer()
  190. go server.start(t, port, maxStreams)
  191. server.wait(t, 2*time.Second)
  192. addr := "localhost:" + server.port
  193. cc, err := Dial(addr, WithBlock(), WithInsecure(), WithCodec(testCodec{}))
  194. if err != nil {
  195. t.Fatalf("Failed to create ClientConn: %v", err)
  196. }
  197. return server, cc
  198. }
  199. func TestInvoke(t *testing.T) {
  200. defer leakcheck.Check(t)
  201. server, cc := setUp(t, 0, math.MaxUint32)
  202. var reply string
  203. if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse {
  204. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err)
  205. }
  206. cc.Close()
  207. server.stop()
  208. }
  209. func TestInvokeLargeErr(t *testing.T) {
  210. defer leakcheck.Check(t)
  211. server, cc := setUp(t, 0, math.MaxUint32)
  212. var reply string
  213. req := "hello"
  214. err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply)
  215. if _, ok := status.FromError(err); !ok {
  216. t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.")
  217. }
  218. if status.Code(err) != codes.Internal || len(errorDesc(err)) != sizeLargeErr {
  219. t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want an error of code %d and desc size %d", err, codes.Internal, sizeLargeErr)
  220. }
  221. cc.Close()
  222. server.stop()
  223. }
  224. // TestInvokeErrorSpecialChars checks that error messages don't get mangled.
  225. func TestInvokeErrorSpecialChars(t *testing.T) {
  226. defer leakcheck.Check(t)
  227. server, cc := setUp(t, 0, math.MaxUint32)
  228. var reply string
  229. req := "weird error"
  230. err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply)
  231. if _, ok := status.FromError(err); !ok {
  232. t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.")
  233. }
  234. if got, want := errorDesc(err), weirdError; got != want {
  235. t.Fatalf("grpc.Invoke(_, _, _, _, _) error = %q, want %q", got, want)
  236. }
  237. cc.Close()
  238. server.stop()
  239. }
  240. // TestInvokeCancel checks that an Invoke with a canceled context is not sent.
  241. func TestInvokeCancel(t *testing.T) {
  242. defer leakcheck.Check(t)
  243. server, cc := setUp(t, 0, math.MaxUint32)
  244. var reply string
  245. req := "canceled"
  246. for i := 0; i < 100; i++ {
  247. ctx, cancel := context.WithCancel(context.Background())
  248. cancel()
  249. cc.Invoke(ctx, "/foo/bar", &req, &reply)
  250. }
  251. if canceled != 0 {
  252. t.Fatalf("received %d of 100 canceled requests", canceled)
  253. }
  254. cc.Close()
  255. server.stop()
  256. }
  257. // TestInvokeCancelClosedNonFail checks that a canceled non-failfast RPC
  258. // on a closed client will terminate.
  259. func TestInvokeCancelClosedNonFailFast(t *testing.T) {
  260. defer leakcheck.Check(t)
  261. server, cc := setUp(t, 0, math.MaxUint32)
  262. var reply string
  263. cc.Close()
  264. req := "hello"
  265. ctx, cancel := context.WithCancel(context.Background())
  266. cancel()
  267. if err := cc.Invoke(ctx, "/foo/bar", &req, &reply, FailFast(false)); err == nil {
  268. t.Fatalf("canceled invoke on closed connection should fail")
  269. }
  270. server.stop()
  271. }