ClientCallTests.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /*
  2. * Copyright 2020, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import EchoImplementation
  17. import EchoModel
  18. @testable import GRPC
  19. import NIO
  20. import XCTest
  21. class ClientCallTests: GRPCTestCase {
  22. private var group: MultiThreadedEventLoopGroup!
  23. private var server: Server!
  24. private var connection: ClientConnection!
  25. override func setUp() {
  26. super.setUp()
  27. self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  28. self.server = try! Server.insecure(group: self.group)
  29. .withServiceProviders([EchoProvider()])
  30. .withLogger(self.serverLogger)
  31. .bind(host: "localhost", port: 0)
  32. .wait()
  33. let port = self.server.channel.localAddress!.port!
  34. self.connection = ClientConnection.insecure(group: self.group)
  35. .withBackgroundActivityLogger(self.clientLogger)
  36. .connect(host: "localhost", port: port)
  37. }
  38. override func tearDown() {
  39. XCTAssertNoThrow(try self.connection.close().wait())
  40. XCTAssertNoThrow(try self.server.close().wait())
  41. XCTAssertNoThrow(try self.group.syncShutdownGracefully())
  42. super.tearDown()
  43. }
  44. private func makeCall(
  45. path: String,
  46. type: GRPCCallType
  47. ) -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  48. return self.connection.makeCall(path: path, type: type, callOptions: .init(), interceptors: [])
  49. }
  50. private func get() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  51. return self.makeCall(path: "/echo.Echo/Get", type: .unary)
  52. }
  53. private func collect() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  54. return self.makeCall(path: "/echo.Echo/Collect", type: .clientStreaming)
  55. }
  56. private func expand() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  57. return self.makeCall(path: "/echo.Echo/Expand", type: .serverStreaming)
  58. }
  59. private func update() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  60. return self.makeCall(path: "/echo.Echo/Update", type: .bidirectionalStreaming)
  61. }
  62. private func makeStatusPromise() -> EventLoopPromise<GRPCStatus> {
  63. return self.connection.eventLoop.makePromise()
  64. }
  65. /// Makes a response part handler which succeeds the promise when receiving the status and fails
  66. /// it if an error is received.
  67. private func makeResponsePartHandler<Response>(
  68. for: Response.Type = Response.self,
  69. completing promise: EventLoopPromise<GRPCStatus>
  70. ) -> (ClientResponsePart<Response>) -> Void {
  71. return { part in
  72. switch part {
  73. case .metadata, .message:
  74. ()
  75. case let .end(status, _):
  76. promise.succeed(status)
  77. case let .error(error):
  78. promise.fail(error)
  79. }
  80. }
  81. }
  82. // MARK: - Tests
  83. func testFullyManualUnary() throws {
  84. let get = self.get()
  85. let statusPromise = self.makeStatusPromise()
  86. get.invoke(self.makeResponsePartHandler(completing: statusPromise))
  87. let f1 = get.send(.metadata(get.options.customMetadata))
  88. let f2 = get.send(.message(.with { $0.text = "get" }, .init(compress: false, flush: false)))
  89. let f3 = get.send(.end)
  90. // '.end' will flush, so we can wait on the futures now.
  91. assertThat(try f1.wait(), .doesNotThrow())
  92. assertThat(try f2.wait(), .doesNotThrow())
  93. assertThat(try f3.wait(), .doesNotThrow())
  94. // Status should be ok.
  95. assertThat(try statusPromise.futureResult.wait(), .hasCode(.ok))
  96. }
  97. func testUnaryCall() {
  98. let get = self.get()
  99. let promise = self.makeStatusPromise()
  100. get.invokeUnaryRequest(
  101. .with { $0.text = "get" },
  102. self.makeResponsePartHandler(completing: promise)
  103. )
  104. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  105. }
  106. func testClientStreaming() {
  107. let collect = self.collect()
  108. let promise = self.makeStatusPromise()
  109. collect.invokeStreamingRequests(self.makeResponsePartHandler(completing: promise))
  110. collect.send(
  111. .message(.with { $0.text = "collect" }, .init(compress: false, flush: false)),
  112. promise: nil
  113. )
  114. collect.send(.end, promise: nil)
  115. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  116. }
  117. func testServerStreaming() {
  118. let expand = self.expand()
  119. let promise = self.makeStatusPromise()
  120. expand.invokeUnaryRequest(
  121. .with { $0.text = "expand" },
  122. self.makeResponsePartHandler(completing: promise)
  123. )
  124. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  125. }
  126. func testBidirectionalStreaming() {
  127. let update = self.update()
  128. let promise = self.makeStatusPromise()
  129. update.invokeStreamingRequests(self.makeResponsePartHandler(completing: promise))
  130. update.send(
  131. .message(.with { $0.text = "update" }, .init(compress: false, flush: false)),
  132. promise: nil
  133. )
  134. update.send(.end, promise: nil)
  135. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  136. }
  137. func testSendBeforeInvoke() throws {
  138. let get = self.get()
  139. assertThat(try get.send(.end).wait(), .throws())
  140. }
  141. func testCancelBeforeInvoke() throws {
  142. let get = self.get()
  143. assertThat(try get.cancel().wait(), .throws())
  144. }
  145. func testCancelMidRPC() throws {
  146. let get = self.get()
  147. let promise = self.makeStatusPromise()
  148. get.invoke(self.makeResponsePartHandler(completing: promise))
  149. // Cancellation should succeed.
  150. assertThat(try get.cancel().wait(), .doesNotThrow())
  151. // The status promise will fail.
  152. assertThat(
  153. try promise.futureResult.wait(),
  154. .throws(.instanceOf(GRPCError.RPCCancelledByClient.self))
  155. )
  156. // Cancellation should now fail, we've already cancelled.
  157. assertThat(try get.cancel().wait(), .throws(.instanceOf(GRPCError.AlreadyComplete.self)))
  158. }
  159. }