2
0

EchoTestClientTests.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 NIO
  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>) -> Void) {
  32. let get = self.client.get(.with { $0.text = text })
  33. get.response.whenComplete { result in
  34. switch result {
  35. case let .success(response):
  36. callback(.success(response.text))
  37. case let .failure(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) -> Void,
  47. onEnd: @escaping (GRPCStatus) -> Void
  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. .withLogger(self.serverLogger)
  69. .bind(host: "127.0.0.1", port: 0)
  70. .wait()
  71. self.server = server
  72. let channel = ClientConnection.insecure(group: group)
  73. .withBackgroundActivityLogger(self.clientLogger)
  74. .connect(host: "127.0.0.1", port: server.channel.localAddress!.port!)
  75. self.channel = channel
  76. return channel
  77. }
  78. override func tearDown() {
  79. if let channel = self.channel {
  80. XCTAssertNoThrow(try channel.close().wait())
  81. }
  82. if let server = self.server {
  83. XCTAssertNoThrow(try server.close().wait())
  84. }
  85. if let group = self.group {
  86. XCTAssertNoThrow(try group.syncShutdownGracefully())
  87. }
  88. super.tearDown()
  89. }
  90. func testGetWithTestClient() {
  91. let client = Echo_EchoTestClient(defaultCallOptions: self.callOptionsWithLogger)
  92. let model = EchoModel(client: client)
  93. let completed = self.expectation(description: "'Get' completed")
  94. // Enqueue a response for the next call to Get.
  95. client.enqueueGetResponse(.with { $0.text = "Expected response" })
  96. model.getWord("Hello") { result in
  97. switch result {
  98. case let .success(text):
  99. XCTAssertEqual(text, "Expected response")
  100. case let .failure(error):
  101. XCTFail("Unexpected error \(error)")
  102. }
  103. completed.fulfill()
  104. }
  105. self.wait(for: [completed], timeout: 10.0)
  106. }
  107. func testGetWithRealClientAndServer() throws {
  108. let channel = try self.setUpServerAndChannel()
  109. let client = Echo_EchoClient(channel: channel, defaultCallOptions: self.callOptionsWithLogger)
  110. let model = EchoModel(client: client)
  111. let completed = self.expectation(description: "'Get' completed")
  112. model.getWord("Hello") { result in
  113. switch result {
  114. case let .success(text):
  115. XCTAssertEqual(text, "Swift echo get: Hello")
  116. case let .failure(error):
  117. XCTFail("Unexpected error \(error)")
  118. }
  119. completed.fulfill()
  120. }
  121. self.wait(for: [completed], timeout: 10.0)
  122. }
  123. func testUpdateWithTestClient() {
  124. let client = Echo_EchoTestClient(defaultCallOptions: self.callOptionsWithLogger)
  125. let model = EchoModel(client: client)
  126. let completed = self.expectation(description: "'Update' completed")
  127. let responses = self.expectation(description: "Received responses")
  128. responses.expectedFulfillmentCount = 3
  129. // Create a response stream for 'Update'.
  130. let stream = client.makeUpdateResponseStream()
  131. model.updateWords(["foo", "bar", "baz"], onResponse: { response in
  132. XCTAssertEqual(response, "Expected response")
  133. responses.fulfill()
  134. }, onEnd: { status in
  135. XCTAssertEqual(status.code, .ok)
  136. completed.fulfill()
  137. })
  138. // Send some responses:
  139. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  140. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  141. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  142. XCTAssertNoThrow(try stream.sendEnd())
  143. self.wait(for: [responses, completed], timeout: 10.0)
  144. }
  145. func testUpdateWithRealClientAndServer() throws {
  146. let channel = try self.setUpServerAndChannel()
  147. let client = Echo_EchoClient(channel: channel, defaultCallOptions: self.callOptionsWithLogger)
  148. let model = EchoModel(client: client)
  149. let completed = self.expectation(description: "'Update' completed")
  150. let responses = self.expectation(description: "Received responses")
  151. responses.expectedFulfillmentCount = 3
  152. model.updateWords(["foo", "bar", "baz"], onResponse: { response in
  153. XCTAssertTrue(response.hasPrefix("Swift echo update"))
  154. responses.fulfill()
  155. }, onEnd: { status in
  156. XCTAssertEqual(status.code, .ok)
  157. completed.fulfill()
  158. })
  159. self.wait(for: [responses, completed], timeout: 10.0)
  160. }
  161. }