EchoTestClientTests.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 GRPC
  19. import NIOCore
  20. import NIOPosix
  21. import XCTest
  22. /// An example model using a generated client for the 'Echo' service.
  23. ///
  24. /// This demonstrates how one might extract a generated client into a component which could be
  25. /// backed by a real or fake client.
  26. class EchoModel {
  27. private let client: Echo_EchoClientProtocol
  28. init(client: Echo_EchoClientProtocol) {
  29. self.client = client
  30. }
  31. /// Call 'get' with the given word and call the `callback` with the result.
  32. func getWord(_ text: String, _ callback: @escaping (Result<String, Error>) -> Void) {
  33. let get = self.client.get(.with { $0.text = text })
  34. get.response.whenComplete { result in
  35. switch result {
  36. case let .success(response):
  37. callback(.success(response.text))
  38. case let .failure(error):
  39. callback(.failure(error))
  40. }
  41. }
  42. }
  43. /// Call 'update' with the given words. Call `onResponse` for each response and then `onEnd` when
  44. /// the RPC has completed.
  45. func updateWords(
  46. _ words: [String],
  47. onResponse: @escaping (String) -> Void,
  48. onEnd: @escaping (GRPCStatus) -> Void
  49. ) {
  50. let update = self.client.update { response in
  51. onResponse(response.text)
  52. }
  53. update.status.whenSuccess { status in
  54. onEnd(status)
  55. }
  56. update.sendMessages(words.map { word in .with { $0.text = word } }, promise: nil)
  57. update.sendEnd(promise: nil)
  58. }
  59. }
  60. class EchoTestClientTests: GRPCTestCase {
  61. private var group: MultiThreadedEventLoopGroup?
  62. private var server: Server?
  63. private var channel: ClientConnection?
  64. private func setUpServerAndChannel() throws -> ClientConnection {
  65. let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  66. self.group = group
  67. let server = try Server.insecure(group: group)
  68. .withServiceProviders([EchoProvider()])
  69. .withLogger(self.serverLogger)
  70. .bind(host: "127.0.0.1", port: 0)
  71. .wait()
  72. self.server = server
  73. let channel = ClientConnection.insecure(group: group)
  74. .withBackgroundActivityLogger(self.clientLogger)
  75. .connect(host: "127.0.0.1", port: server.channel.localAddress!.port!)
  76. self.channel = channel
  77. return channel
  78. }
  79. override func tearDown() {
  80. if let channel = self.channel {
  81. XCTAssertNoThrow(try channel.close().wait())
  82. }
  83. if let server = self.server {
  84. XCTAssertNoThrow(try server.close().wait())
  85. }
  86. if let group = self.group {
  87. XCTAssertNoThrow(try group.syncShutdownGracefully())
  88. }
  89. super.tearDown()
  90. }
  91. @available(swift, deprecated: 5.6)
  92. func testGetWithTestClient() {
  93. let client = Echo_EchoTestClient(defaultCallOptions: self.callOptionsWithLogger)
  94. let model = EchoModel(client: client)
  95. let completed = self.expectation(description: "'Get' completed")
  96. // Enqueue a response for the next call to Get.
  97. client.enqueueGetResponse(.with { $0.text = "Expected response" })
  98. model.getWord("Hello") { result in
  99. switch result {
  100. case let .success(text):
  101. XCTAssertEqual(text, "Expected response")
  102. case let .failure(error):
  103. XCTFail("Unexpected error \(error)")
  104. }
  105. completed.fulfill()
  106. }
  107. self.wait(for: [completed], timeout: 10.0)
  108. }
  109. func testGetWithRealClientAndServer() throws {
  110. let channel = try self.setUpServerAndChannel()
  111. let client = Echo_EchoNIOClient(
  112. channel: channel,
  113. defaultCallOptions: self.callOptionsWithLogger
  114. )
  115. let model = EchoModel(client: client)
  116. let completed = self.expectation(description: "'Get' completed")
  117. model.getWord("Hello") { result in
  118. switch result {
  119. case let .success(text):
  120. XCTAssertEqual(text, "Swift echo get: Hello")
  121. case let .failure(error):
  122. XCTFail("Unexpected error \(error)")
  123. }
  124. completed.fulfill()
  125. }
  126. self.wait(for: [completed], timeout: 10.0)
  127. }
  128. @available(swift, deprecated: 5.6)
  129. func testUpdateWithTestClient() {
  130. let client = Echo_EchoTestClient(defaultCallOptions: self.callOptionsWithLogger)
  131. let model = EchoModel(client: client)
  132. let completed = self.expectation(description: "'Update' completed")
  133. let responses = self.expectation(description: "Received responses")
  134. responses.expectedFulfillmentCount = 3
  135. // Create a response stream for 'Update'.
  136. let stream = client.makeUpdateResponseStream()
  137. model.updateWords(
  138. ["foo", "bar", "baz"],
  139. onResponse: { response in
  140. XCTAssertEqual(response, "Expected response")
  141. responses.fulfill()
  142. },
  143. onEnd: { status in
  144. XCTAssertEqual(status.code, .ok)
  145. completed.fulfill()
  146. }
  147. )
  148. // Send some responses:
  149. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  150. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  151. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  152. XCTAssertNoThrow(try stream.sendEnd())
  153. self.wait(for: [responses, completed], timeout: 10.0)
  154. }
  155. func testUpdateWithRealClientAndServer() throws {
  156. let channel = try self.setUpServerAndChannel()
  157. let client = Echo_EchoNIOClient(
  158. channel: channel,
  159. defaultCallOptions: self.callOptionsWithLogger
  160. )
  161. let model = EchoModel(client: client)
  162. let completed = self.expectation(description: "'Update' completed")
  163. let responses = self.expectation(description: "Received responses")
  164. responses.expectedFulfillmentCount = 3
  165. model.updateWords(
  166. ["foo", "bar", "baz"],
  167. onResponse: { response in
  168. XCTAssertTrue(response.hasPrefix("Swift echo update"))
  169. responses.fulfill()
  170. },
  171. onEnd: { status in
  172. XCTAssertEqual(status.code, .ok)
  173. completed.fulfill()
  174. }
  175. )
  176. self.wait(for: [responses, completed], timeout: 10.0)
  177. }
  178. }