EchoTestClientTests.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. func testGetWithTestClient() {
  92. let client = Echo_EchoTestClient(defaultCallOptions: self.callOptionsWithLogger)
  93. let model = EchoModel(client: client)
  94. let completed = self.expectation(description: "'Get' completed")
  95. // Enqueue a response for the next call to Get.
  96. client.enqueueGetResponse(.with { $0.text = "Expected response" })
  97. model.getWord("Hello") { result in
  98. switch result {
  99. case let .success(text):
  100. XCTAssertEqual(text, "Expected response")
  101. case let .failure(error):
  102. XCTFail("Unexpected error \(error)")
  103. }
  104. completed.fulfill()
  105. }
  106. self.wait(for: [completed], timeout: 10.0)
  107. }
  108. func testGetWithRealClientAndServer() throws {
  109. let channel = try self.setUpServerAndChannel()
  110. let client = Echo_EchoClient(channel: channel, defaultCallOptions: self.callOptionsWithLogger)
  111. let model = EchoModel(client: client)
  112. let completed = self.expectation(description: "'Get' completed")
  113. model.getWord("Hello") { result in
  114. switch result {
  115. case let .success(text):
  116. XCTAssertEqual(text, "Swift echo get: Hello")
  117. case let .failure(error):
  118. XCTFail("Unexpected error \(error)")
  119. }
  120. completed.fulfill()
  121. }
  122. self.wait(for: [completed], timeout: 10.0)
  123. }
  124. func testUpdateWithTestClient() {
  125. let client = Echo_EchoTestClient(defaultCallOptions: self.callOptionsWithLogger)
  126. let model = EchoModel(client: client)
  127. let completed = self.expectation(description: "'Update' completed")
  128. let responses = self.expectation(description: "Received responses")
  129. responses.expectedFulfillmentCount = 3
  130. // Create a response stream for 'Update'.
  131. let stream = client.makeUpdateResponseStream()
  132. model.updateWords(["foo", "bar", "baz"], onResponse: { response in
  133. XCTAssertEqual(response, "Expected response")
  134. responses.fulfill()
  135. }, onEnd: { status in
  136. XCTAssertEqual(status.code, .ok)
  137. completed.fulfill()
  138. })
  139. // Send some responses:
  140. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  141. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  142. XCTAssertNoThrow(try stream.sendMessage(.with { $0.text = "Expected response" }))
  143. XCTAssertNoThrow(try stream.sendEnd())
  144. self.wait(for: [responses, completed], timeout: 10.0)
  145. }
  146. func testUpdateWithRealClientAndServer() throws {
  147. let channel = try self.setUpServerAndChannel()
  148. let client = Echo_EchoClient(channel: channel, defaultCallOptions: self.callOptionsWithLogger)
  149. let model = EchoModel(client: client)
  150. let completed = self.expectation(description: "'Update' completed")
  151. let responses = self.expectation(description: "Received responses")
  152. responses.expectedFulfillmentCount = 3
  153. model.updateWords(["foo", "bar", "baz"], onResponse: { response in
  154. XCTAssertTrue(response.hasPrefix("Swift echo update"))
  155. responses.fulfill()
  156. }, onEnd: { status in
  157. XCTAssertEqual(status.code, .ok)
  158. completed.fulfill()
  159. })
  160. self.wait(for: [responses, completed], timeout: 10.0)
  161. }
  162. }