NIOServerTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * Copyright 2018, 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 Dispatch
  17. import Foundation
  18. import NIO
  19. import NIOHTTP1
  20. import NIOHTTP2
  21. @testable import SwiftGRPC
  22. @testable import SwiftGRPCNIO
  23. import XCTest
  24. // This class is what the SwiftGRPC user would actually implement to provide their service.
  25. final class EchoProvider_NIO: Echo_EchoProvider_NIO {
  26. func get(request: Echo_EchoRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  27. var response = Echo_EchoResponse()
  28. response.text = "Swift echo get: " + request.text
  29. return context.eventLoop.newSucceededFuture(result: response)
  30. }
  31. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  32. var parts: [String] = []
  33. return context.eventLoop.newSucceededFuture(result: { event in
  34. switch event {
  35. case .message(let message):
  36. parts.append(message.text)
  37. case .end:
  38. var response = Echo_EchoResponse()
  39. response.text = "Swift echo collect: " + parts.joined(separator: " ")
  40. context.responsePromise.succeed(result: response)
  41. }
  42. })
  43. }
  44. func expand(request: Echo_EchoRequest, context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<GRPCStatus> {
  45. var endOfSendOperationQueue = context.eventLoop.newSucceededFuture(result: ())
  46. let parts = request.text.components(separatedBy: " ")
  47. for (i, part) in parts.enumerated() {
  48. var response = Echo_EchoResponse()
  49. response.text = "Swift echo expand (\(i)): \(part)"
  50. endOfSendOperationQueue = endOfSendOperationQueue.then { context.sendResponse(response) }
  51. }
  52. return endOfSendOperationQueue.map { GRPCStatus.ok }
  53. }
  54. func update(context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  55. var endOfSendOperationQueue = context.eventLoop.newSucceededFuture(result: ())
  56. var count = 0
  57. return context.eventLoop.newSucceededFuture(result: { event in
  58. switch event {
  59. case .message(let message):
  60. var response = Echo_EchoResponse()
  61. response.text = "Swift echo update (\(count)): \(message.text)"
  62. endOfSendOperationQueue = endOfSendOperationQueue.then { context.sendResponse(response) }
  63. count += 1
  64. case .end:
  65. endOfSendOperationQueue
  66. .map { GRPCStatus.ok }
  67. .cascade(promise: context.statusPromise)
  68. }
  69. })
  70. }
  71. }
  72. class NIOServerTests: NIOServerTestCase {
  73. static var allTests: [(String, (NIOServerTests) -> () throws -> Void)] {
  74. return [
  75. ("testUnary", testUnary),
  76. ("testUnaryLotsOfRequests", testUnaryLotsOfRequests),
  77. ("testClientStreaming", testClientStreaming),
  78. ("testClientStreamingLotsOfMessages", testClientStreamingLotsOfMessages),
  79. ("testServerStreaming", testServerStreaming),
  80. ("testServerStreamingLotsOfMessages", testServerStreamingLotsOfMessages),
  81. ("testBidirectionalStreamingBatched", testBidirectionalStreamingBatched),
  82. ("testBidirectionalStreamingPingPong", testBidirectionalStreamingPingPong),
  83. ("testBidirectionalStreamingLotsOfMessagesBatched", testBidirectionalStreamingLotsOfMessagesBatched),
  84. ("testBidirectionalStreamingLotsOfMessagesPingPong", testBidirectionalStreamingLotsOfMessagesPingPong)
  85. ]
  86. }
  87. static let lotsOfStrings = (0..<1000).map { String(describing: $0) }
  88. var eventLoopGroup: MultiThreadedEventLoopGroup!
  89. var server: GRPCServer!
  90. override func setUp() {
  91. super.setUp()
  92. // This is how a GRPC server would actually be set up.
  93. eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  94. server = try! GRPCServer.start(
  95. hostname: "localhost", port: 5050, eventLoopGroup: eventLoopGroup, serviceProviders: [EchoProvider_NIO()])
  96. .wait()
  97. }
  98. override func tearDown() {
  99. XCTAssertNoThrow(try server.close().wait())
  100. XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
  101. eventLoopGroup = nil
  102. super.tearDown()
  103. }
  104. }
  105. extension NIOServerTests {
  106. func testUnary() {
  107. XCTAssertEqual("Swift echo get: foo", try! client.get(Echo_EchoRequest(text: "foo")).text)
  108. }
  109. func testUnaryLotsOfRequests() {
  110. // Sending that many requests at once can sometimes trip things up, it seems.
  111. client.timeout = 5.0
  112. let clockStart = clock()
  113. let numberOfRequests = 2_000
  114. for i in 0..<numberOfRequests {
  115. if i % 1_000 == 0 && i > 0 {
  116. print("\(i) requests sent so far, elapsed time: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  117. }
  118. XCTAssertEqual("Swift echo get: foo \(i)", try client.get(Echo_EchoRequest(text: "foo \(i)")).text)
  119. }
  120. print("total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  121. }
  122. }
  123. extension NIOServerTests {
  124. func testClientStreaming() {
  125. let completionHandlerExpectation = expectation(description: "final completion handler called")
  126. let call = try! client.collect { callResult in
  127. XCTAssertEqual(.ok, callResult.statusCode)
  128. completionHandlerExpectation.fulfill()
  129. }
  130. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "foo")))
  131. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "bar")))
  132. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "baz")))
  133. call.waitForSendOperationsToFinish()
  134. let response = try! call.closeAndReceive()
  135. XCTAssertEqual("Swift echo collect: foo bar baz", response.text)
  136. waitForExpectations(timeout: defaultTimeout)
  137. }
  138. func testClientStreamingLotsOfMessages() {
  139. let completionHandlerExpectation = expectation(description: "completion handler called")
  140. let call = try! client.collect { callResult in
  141. XCTAssertEqual(.ok, callResult.statusCode)
  142. completionHandlerExpectation.fulfill()
  143. }
  144. for string in NIOServerTests.lotsOfStrings {
  145. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: string)))
  146. }
  147. call.waitForSendOperationsToFinish()
  148. let response = try! call.closeAndReceive()
  149. XCTAssertEqual("Swift echo collect: " + NIOServerTests.lotsOfStrings.joined(separator: " "), response.text)
  150. waitForExpectations(timeout: defaultTimeout)
  151. }
  152. }
  153. extension NIOServerTests {
  154. func testServerStreaming() {
  155. let completionHandlerExpectation = expectation(description: "completion handler called")
  156. let call = try! client.expand(Echo_EchoRequest(text: "foo bar baz")) { callResult in
  157. XCTAssertEqual(.ok, callResult.statusCode)
  158. completionHandlerExpectation.fulfill()
  159. }
  160. XCTAssertEqual("Swift echo expand (0): foo", try! call.receive()!.text)
  161. XCTAssertEqual("Swift echo expand (1): bar", try! call.receive()!.text)
  162. XCTAssertEqual("Swift echo expand (2): baz", try! call.receive()!.text)
  163. XCTAssertNil(try! call.receive())
  164. waitForExpectations(timeout: defaultTimeout)
  165. }
  166. func testServerStreamingLotsOfMessages() {
  167. let completionHandlerExpectation = expectation(description: "completion handler called")
  168. let call = try! client.expand(Echo_EchoRequest(text: NIOServerTests.lotsOfStrings.joined(separator: " "))) { callResult in
  169. XCTAssertEqual(.ok, callResult.statusCode)
  170. completionHandlerExpectation.fulfill()
  171. }
  172. for string in NIOServerTests.lotsOfStrings {
  173. XCTAssertEqual("Swift echo expand (\(string)): \(string)", try! call.receive()!.text)
  174. }
  175. XCTAssertNil(try! call.receive())
  176. waitForExpectations(timeout: defaultTimeout)
  177. }
  178. }
  179. extension NIOServerTests {
  180. func testBidirectionalStreamingBatched() {
  181. let finalCompletionHandlerExpectation = expectation(description: "final completion handler called")
  182. let call = try! client.update { callResult in
  183. XCTAssertEqual(.ok, callResult.statusCode)
  184. finalCompletionHandlerExpectation.fulfill()
  185. }
  186. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "foo")))
  187. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "bar")))
  188. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "baz")))
  189. call.waitForSendOperationsToFinish()
  190. XCTAssertNoThrow(try call.closeSend())
  191. XCTAssertEqual("Swift echo update (0): foo", try! call.receive()!.text)
  192. XCTAssertEqual("Swift echo update (1): bar", try! call.receive()!.text)
  193. XCTAssertEqual("Swift echo update (2): baz", try! call.receive()!.text)
  194. XCTAssertNil(try! call.receive())
  195. waitForExpectations(timeout: defaultTimeout)
  196. }
  197. func testBidirectionalStreamingPingPong() {
  198. let finalCompletionHandlerExpectation = expectation(description: "final completion handler called")
  199. let call = try! client.update { callResult in
  200. XCTAssertEqual(.ok, callResult.statusCode)
  201. finalCompletionHandlerExpectation.fulfill()
  202. }
  203. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "foo")))
  204. XCTAssertEqual("Swift echo update (0): foo", try! call.receive()!.text)
  205. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "bar")))
  206. XCTAssertEqual("Swift echo update (1): bar", try! call.receive()!.text)
  207. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: "baz")))
  208. XCTAssertEqual("Swift echo update (2): baz", try! call.receive()!.text)
  209. call.waitForSendOperationsToFinish()
  210. XCTAssertNoThrow(try call.closeSend())
  211. XCTAssertNil(try! call.receive())
  212. waitForExpectations(timeout: defaultTimeout)
  213. }
  214. func testBidirectionalStreamingLotsOfMessagesBatched() {
  215. let finalCompletionHandlerExpectation = expectation(description: "final completion handler called")
  216. let call = try! client.update { callResult in
  217. XCTAssertEqual(.ok, callResult.statusCode)
  218. finalCompletionHandlerExpectation.fulfill()
  219. }
  220. for string in NIOServerTests.lotsOfStrings {
  221. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: string)))
  222. }
  223. call.waitForSendOperationsToFinish()
  224. XCTAssertNoThrow(try call.closeSend())
  225. for string in NIOServerTests.lotsOfStrings {
  226. XCTAssertEqual("Swift echo update (\(string)): \(string)", try! call.receive()!.text)
  227. }
  228. XCTAssertNil(try! call.receive())
  229. waitForExpectations(timeout: defaultTimeout)
  230. }
  231. func testBidirectionalStreamingLotsOfMessagesPingPong() {
  232. let finalCompletionHandlerExpectation = expectation(description: "final completion handler called")
  233. let call = try! client.update { callResult in
  234. XCTAssertEqual(.ok, callResult.statusCode)
  235. finalCompletionHandlerExpectation.fulfill()
  236. }
  237. for string in NIOServerTests.lotsOfStrings {
  238. XCTAssertNoThrow(try call.send(Echo_EchoRequest(text: string)))
  239. XCTAssertEqual("Swift echo update (\(string)): \(string)", try! call.receive()!.text)
  240. }
  241. call.waitForSendOperationsToFinish()
  242. XCTAssertNoThrow(try call.closeSend())
  243. XCTAssertNil(try! call.receive())
  244. waitForExpectations(timeout: defaultTimeout)
  245. }
  246. }