NIOFunctionalTests.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. * Copyright 2019, 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 SwiftGRPCNIO
  22. import XCTest
  23. class NIOFunctionalTestsInsecureTransport: NIOEchoTestCaseBase {
  24. override var transportSecurity: TransportSecurity {
  25. return .none
  26. }
  27. var aFewStrings: [String] {
  28. return ["foo", "bar", "baz"]
  29. }
  30. var lotsOfStrings: [String] {
  31. return (0..<5_000).map {
  32. String(describing: $0)
  33. }
  34. }
  35. }
  36. extension NIOFunctionalTestsInsecureTransport {
  37. func doTestUnary(request: Echo_EchoRequest, expect response: Echo_EchoResponse, file: StaticString = #file, line: UInt = #line) {
  38. let responseExpectation = self.makeResponseExpectation()
  39. let statusExpectation = self.makeStatusExpectation()
  40. let call = client.get(request)
  41. call.response.assertEqual(response, fulfill: responseExpectation, file: file, line: line)
  42. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  43. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  44. }
  45. func doTestUnary(message: String, file: StaticString = #file, line: UInt = #line) {
  46. self.doTestUnary(request: Echo_EchoRequest(text: message), expect: Echo_EchoResponse(text: "Swift echo get: \(message)"), file: file, line: line)
  47. }
  48. func testUnary() throws {
  49. self.doTestUnary(message: "foo")
  50. }
  51. func testUnaryLotsOfRequests() throws {
  52. // Sending that many requests at once can sometimes trip things up, it seems.
  53. let clockStart = clock()
  54. let numberOfRequests = 2_000
  55. // Due to https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401 we need to
  56. // limit the number of active streams. The default in NIOHTTP2 is 100, so we'll use it too.
  57. //
  58. // In the future we might want to build in some kind of mechanism which handles this for the
  59. // user.
  60. let batchSize = 100
  61. // Instead of setting a timeout out on the test we'll set one for each batch, if any of them
  62. // timeout then we'll bail out of the test.
  63. let batchTimeout: TimeInterval = 5.0
  64. self.continueAfterFailure = false
  65. for lowerBound in stride(from: 0, to: numberOfRequests, by: batchSize) {
  66. let upperBound = min(lowerBound + batchSize, numberOfRequests)
  67. let numberOfCalls = upperBound - lowerBound
  68. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: numberOfCalls)
  69. let statusExpectation = self.makeStatusExpectation(expectedFulfillmentCount: numberOfCalls)
  70. for i in lowerBound..<upperBound {
  71. let request = Echo_EchoRequest(text: "foo \(i)")
  72. let response = Echo_EchoResponse(text: "Swift echo get: foo \(i)")
  73. let get = client.get(request)
  74. get.response.assertEqual(response, fulfill: responseExpectation)
  75. get.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  76. }
  77. if upperBound % 1_000 == 0 {
  78. print("\(upperBound) requests sent so far, elapsed time: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  79. }
  80. self.wait(for: [responseExpectation, statusExpectation], timeout: batchTimeout)
  81. }
  82. print("total time to receive \(numberOfRequests) responses: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  83. }
  84. func testUnaryWithLargeData() throws {
  85. // Default max frame size is: 16,384. We'll exceed this as we also have to send the size and compression flag.
  86. let longMessage = String(repeating: "e", count: 16_384)
  87. self.doTestUnary(message: longMessage)
  88. }
  89. func testUnaryEmptyRequest() throws {
  90. self.doTestUnary(request: Echo_EchoRequest(), expect: Echo_EchoResponse(text: "Swift echo get: "))
  91. }
  92. }
  93. extension NIOFunctionalTestsInsecureTransport {
  94. func doTestClientStreaming(messages: [String], file: StaticString = #file, line: UInt = #line) throws {
  95. let responseExpectation = self.makeResponseExpectation()
  96. let statusExpectation = self.makeStatusExpectation()
  97. let call = client.collect(callOptions: CallOptions(timeout: .infinite))
  98. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  99. call.response.assertEqual(Echo_EchoResponse(text: "Swift echo collect: \(messages.joined(separator: " "))"), fulfill: responseExpectation)
  100. var queue = call.newMessageQueue()
  101. for message in messages {
  102. queue = queue.flatMap { call.sendMessage(Echo_EchoRequest(text: message)) }
  103. }
  104. queue.whenSuccess { call.sendEnd(promise: nil) }
  105. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  106. }
  107. func testClientStreaming() {
  108. XCTAssertNoThrow(try doTestClientStreaming(messages: aFewStrings))
  109. }
  110. func testClientStreamingLotsOfMessages() throws {
  111. self.defaultTestTimeout = 15.0
  112. XCTAssertNoThrow(try doTestClientStreaming(messages: lotsOfStrings))
  113. }
  114. }
  115. extension NIOFunctionalTestsInsecureTransport {
  116. func doTestServerStreaming(messages: [String], file: StaticString = #file, line: UInt = #line) throws {
  117. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  118. let statusExpectation = self.makeStatusExpectation()
  119. var iterator = messages.enumerated().makeIterator()
  120. let call = client.expand(Echo_EchoRequest(text: messages.joined(separator: " "))) { response in
  121. if let (index, message) = iterator.next() {
  122. XCTAssertEqual(Echo_EchoResponse(text: "Swift echo expand (\(index)): \(message)"), response, file: file, line: line)
  123. responseExpectation.fulfill()
  124. } else {
  125. XCTFail("Too many responses received", file: file, line: line)
  126. }
  127. }
  128. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  129. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  130. }
  131. func testServerStreaming() {
  132. XCTAssertNoThrow(try doTestServerStreaming(messages: aFewStrings))
  133. }
  134. func testServerStreamingLotsOfMessages() {
  135. self.defaultTestTimeout = 15.0
  136. XCTAssertNoThrow(try doTestServerStreaming(messages: lotsOfStrings))
  137. }
  138. }
  139. extension NIOFunctionalTestsInsecureTransport {
  140. private func doTestBidirectionalStreaming(messages: [String], waitForEachResponse: Bool = false, file: StaticString = #file, line: UInt = #line) throws {
  141. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  142. let statusExpectation = self.makeStatusExpectation()
  143. let responseReceived = waitForEachResponse ? DispatchSemaphore(value: 0) : nil
  144. var iterator = messages.enumerated().makeIterator()
  145. let call = client.update { response in
  146. if let (index, message) = iterator.next() {
  147. XCTAssertEqual(Echo_EchoResponse(text: "Swift echo update (\(index)): \(message)"), response, file: file, line: line)
  148. responseExpectation.fulfill()
  149. responseReceived?.signal()
  150. } else {
  151. XCTFail("Too many responses received", file: file, line: line)
  152. }
  153. }
  154. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  155. messages.forEach { part in
  156. call.sendMessage(Echo_EchoRequest(text: part), promise: nil)
  157. XCTAssertNotEqual(responseReceived?.wait(timeout: .now() + .seconds(1)), .some(.timedOut), file: file, line: line)
  158. }
  159. call.sendEnd(promise: nil)
  160. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  161. }
  162. func testBidirectionalStreamingBatched() throws {
  163. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: aFewStrings))
  164. }
  165. func testBidirectionalStreamingPingPong() throws {
  166. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: aFewStrings, waitForEachResponse: true))
  167. }
  168. func testBidirectionalStreamingLotsOfMessagesBatched() throws {
  169. self.defaultTestTimeout = 15.0
  170. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: lotsOfStrings))
  171. }
  172. func testBidirectionalStreamingLotsOfMessagesPingPong() throws {
  173. self.defaultTestTimeout = 15.0
  174. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: lotsOfStrings, waitForEachResponse: true))
  175. }
  176. }
  177. class NIOFunctionalTestsAnonymousClient: NIOFunctionalTestsInsecureTransport {
  178. override var transportSecurity: TransportSecurity {
  179. return .anonymousClient
  180. }
  181. }
  182. class NIOFunctionalTestsMutualAuthentication: NIOFunctionalTestsInsecureTransport {
  183. override var transportSecurity: TransportSecurity {
  184. return .mutualAuthentication
  185. }
  186. }