EchoTestClientTests.swift 5.9 KB

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