ClientCallTests.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. import NIOCore
  19. import NIOPosix
  20. import XCTest
  21. @testable import GRPC
  22. class ClientCallTests: GRPCTestCase {
  23. private var group: MultiThreadedEventLoopGroup!
  24. private var server: Server!
  25. private var connection: ClientConnection!
  26. override func setUp() {
  27. super.setUp()
  28. self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  29. self.server = try! Server.insecure(group: self.group)
  30. .withServiceProviders([EchoProvider()])
  31. .withLogger(self.serverLogger)
  32. .bind(host: "localhost", port: 0)
  33. .wait()
  34. let port = self.server.channel.localAddress!.port!
  35. self.connection = ClientConnection.insecure(group: self.group)
  36. .withBackgroundActivityLogger(self.clientLogger)
  37. .connect(host: "localhost", port: port)
  38. }
  39. override func tearDown() {
  40. XCTAssertNoThrow(try self.connection.close().wait())
  41. XCTAssertNoThrow(try self.server.close().wait())
  42. XCTAssertNoThrow(try self.group.syncShutdownGracefully())
  43. super.tearDown()
  44. }
  45. private func makeCall(
  46. path: String,
  47. type: GRPCCallType
  48. ) -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  49. return self.connection.makeCall(path: path, type: type, callOptions: .init(), interceptors: [])
  50. }
  51. private func get() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  52. return self.makeCall(path: "/echo.Echo/Get", type: .unary)
  53. }
  54. private func collect() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  55. return self.makeCall(path: "/echo.Echo/Collect", type: .clientStreaming)
  56. }
  57. private func expand() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  58. return self.makeCall(path: "/echo.Echo/Expand", type: .serverStreaming)
  59. }
  60. private func update() -> Call<Echo_EchoRequest, Echo_EchoResponse> {
  61. return self.makeCall(path: "/echo.Echo/Update", type: .bidirectionalStreaming)
  62. }
  63. private func makeStatusPromise() -> EventLoopPromise<GRPCStatus> {
  64. return self.connection.eventLoop.makePromise()
  65. }
  66. /// Makes a response part handler which succeeds the promise when receiving the status and fails
  67. /// it if an error is received.
  68. private func makeResponsePartHandler<Response>(
  69. for: Response.Type = Response.self,
  70. completing promise: EventLoopPromise<GRPCStatus>
  71. ) -> (GRPCClientResponsePart<Response>) -> Void {
  72. return { part in
  73. switch part {
  74. case .metadata, .message:
  75. ()
  76. case let .end(status, _):
  77. promise.succeed(status)
  78. }
  79. }
  80. }
  81. // MARK: - Tests
  82. func testFullyManualUnary() throws {
  83. let get = self.get()
  84. let statusPromise = self.makeStatusPromise()
  85. get.invoke(
  86. onError: statusPromise.fail(_:),
  87. onResponsePart: self.makeResponsePartHandler(completing: statusPromise)
  88. )
  89. let f1 = get.send(.metadata(get.options.customMetadata))
  90. let f2 = get.send(.message(.with { $0.text = "get" }, .init(compress: false, flush: false)))
  91. let f3 = get.send(.end)
  92. // '.end' will flush, so we can wait on the futures now.
  93. assertThat(try f1.wait(), .doesNotThrow())
  94. assertThat(try f2.wait(), .doesNotThrow())
  95. assertThat(try f3.wait(), .doesNotThrow())
  96. // Status should be ok.
  97. assertThat(try statusPromise.futureResult.wait(), .hasCode(.ok))
  98. }
  99. func testUnaryCall() {
  100. let get = self.get()
  101. let promise = self.makeStatusPromise()
  102. get.invokeUnaryRequest(
  103. .with { $0.text = "get" },
  104. onStart: {},
  105. onError: promise.fail(_:),
  106. onResponsePart: self.makeResponsePartHandler(completing: promise)
  107. )
  108. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  109. }
  110. func testClientStreaming() {
  111. let collect = self.collect()
  112. let promise = self.makeStatusPromise()
  113. collect.invokeStreamingRequests(
  114. onStart: {},
  115. onError: promise.fail(_:),
  116. onResponsePart: self.makeResponsePartHandler(completing: promise)
  117. )
  118. collect.send(
  119. .message(.with { $0.text = "collect" }, .init(compress: false, flush: false)),
  120. promise: nil
  121. )
  122. collect.send(.end, promise: nil)
  123. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  124. }
  125. func testServerStreaming() {
  126. let expand = self.expand()
  127. let promise = self.makeStatusPromise()
  128. expand.invokeUnaryRequest(
  129. .with { $0.text = "expand" },
  130. onStart: {},
  131. onError: promise.fail(_:),
  132. onResponsePart: self.makeResponsePartHandler(completing: promise)
  133. )
  134. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  135. }
  136. func testBidirectionalStreaming() {
  137. let update = self.update()
  138. let promise = self.makeStatusPromise()
  139. update.invokeStreamingRequests(
  140. onStart: {},
  141. onError: promise.fail(_:),
  142. onResponsePart: self.makeResponsePartHandler(completing: promise)
  143. )
  144. update.send(
  145. .message(.with { $0.text = "update" }, .init(compress: false, flush: false)),
  146. promise: nil
  147. )
  148. update.send(.end, promise: nil)
  149. assertThat(try promise.futureResult.wait(), .hasCode(.ok))
  150. }
  151. func testSendBeforeInvoke() throws {
  152. let get = self.get()
  153. assertThat(try get.send(.end).wait(), .throws())
  154. }
  155. func testCancelBeforeInvoke() throws {
  156. let get = self.get()
  157. XCTAssertNoThrow(try get.cancel().wait())
  158. }
  159. func testCancelMidRPC() throws {
  160. let get = self.get()
  161. let promise = self.makeStatusPromise()
  162. get.invoke(
  163. onError: promise.fail(_:),
  164. onResponsePart: self.makeResponsePartHandler(completing: promise)
  165. )
  166. // Cancellation should succeed.
  167. assertThat(try get.cancel().wait(), .doesNotThrow())
  168. assertThat(try promise.futureResult.wait(), .hasCode(.cancelled))
  169. // Cancellation should now fail, we've already cancelled.
  170. assertThat(try get.cancel().wait(), .throws(.instanceOf(GRPCError.AlreadyComplete.self)))
  171. }
  172. func testWriteMessageOnStart() throws {
  173. // This test isn't deterministic so run a bunch of iterations.
  174. for _ in 0 ..< 100 {
  175. let call = self.update()
  176. let promise = call.eventLoop.makePromise(of: Void.self)
  177. let finished = call.eventLoop.makePromise(of: Void.self)
  178. call.invokeStreamingRequests {
  179. // Send in onStart.
  180. call.send(
  181. .message(.with { $0.text = "foo" }, .init(compress: false, flush: false)),
  182. promise: promise
  183. )
  184. } onError: { _ in // ignore errors
  185. } onResponsePart: {
  186. switch $0 {
  187. case .metadata, .message:
  188. ()
  189. case .end:
  190. finished.succeed(())
  191. }
  192. }
  193. // End the stream.
  194. promise.futureResult.whenComplete { _ in
  195. call.send(.end, promise: nil)
  196. }
  197. do {
  198. try promise.futureResult.wait()
  199. try finished.futureResult.wait()
  200. } catch {
  201. // Stop on the first error.
  202. XCTFail("Unexpected error: \(error)")
  203. return
  204. }
  205. }
  206. }
  207. }