NIOFunctionalTests.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 makeExpectation(description: String, expectedFulfillmentCount: Int = 1, assertForOverFulfill: Bool = true) -> XCTestExpectation {
  38. let expectation = self.expectation(description: description)
  39. expectation.expectedFulfillmentCount = expectedFulfillmentCount
  40. expectation.assertForOverFulfill = assertForOverFulfill
  41. return expectation
  42. }
  43. func makeStatusExpectation(expectedFulfillmentCount: Int = 1) -> XCTestExpectation {
  44. return makeExpectation(description: "Expecting status received",
  45. expectedFulfillmentCount: expectedFulfillmentCount)
  46. }
  47. func makeResponseExpectation(expectedFulfillmentCount: Int = 1) -> XCTestExpectation {
  48. return makeExpectation(description: "Expecting \(expectedFulfillmentCount) response(s)",
  49. expectedFulfillmentCount: expectedFulfillmentCount)
  50. }
  51. }
  52. extension NIOFunctionalTestsInsecureTransport {
  53. func doTestUnary(request: Echo_EchoRequest, expect response: Echo_EchoResponse, file: StaticString = #file, line: UInt = #line) {
  54. let responseExpectation = self.makeResponseExpectation()
  55. let statusExpectation = self.makeStatusExpectation()
  56. let call = client.get(request)
  57. call.response.assertEqual(response, fulfill: responseExpectation, file: file, line: line)
  58. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  59. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  60. }
  61. func doTestUnary(message: String, file: StaticString = #file, line: UInt = #line) {
  62. self.doTestUnary(request: Echo_EchoRequest(text: message), expect: Echo_EchoResponse(text: "Swift echo get: \(message)"), file: file, line: line)
  63. }
  64. func testUnary() throws {
  65. self.doTestUnary(message: "foo")
  66. }
  67. func testUnaryLotsOfRequests() throws {
  68. self.defaultTestTimeout = 60.0
  69. // Sending that many requests at once can sometimes trip things up, it seems.
  70. let clockStart = clock()
  71. let numberOfRequests = 2_000
  72. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: numberOfRequests)
  73. let statusExpectation = self.makeStatusExpectation(expectedFulfillmentCount: numberOfRequests)
  74. for i in 0..<numberOfRequests {
  75. if i % 1_000 == 0 && i > 0 {
  76. print("\(i) requests sent so far, elapsed time: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  77. }
  78. let request = Echo_EchoRequest(text: "foo \(i)")
  79. let response = Echo_EchoResponse(text: "Swift echo get: foo \(i)")
  80. let call = client.get(request)
  81. call.response.assertEqual(response, fulfill: responseExpectation)
  82. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  83. // Sleep for 250 us to avoid the quadratic runtime described in
  84. // https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401.
  85. Thread.sleep(forTimeInterval: 0.00025)
  86. }
  87. print("total time to send \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  88. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  89. print("total time to receive \(numberOfRequests) responses: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  90. }
  91. func testUnaryWithLargeData() throws {
  92. // Default max frame size is: 16,384. We'll exceed this as we also have to send the size and compression flag.
  93. let longMessage = String(repeating: "e", count: 16_384)
  94. self.doTestUnary(message: longMessage)
  95. }
  96. func testUnaryEmptyRequest() throws {
  97. self.doTestUnary(request: Echo_EchoRequest(), expect: Echo_EchoResponse(text: "Swift echo get: "))
  98. }
  99. }
  100. extension NIOFunctionalTestsInsecureTransport {
  101. func doTestClientStreaming(messages: [String], file: StaticString = #file, line: UInt = #line) throws {
  102. let responseExpectation = self.makeResponseExpectation()
  103. let statusExpectation = self.makeStatusExpectation()
  104. let call = client.collect(callOptions: CallOptions(timeout: .infinite))
  105. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  106. call.response.assertEqual(Echo_EchoResponse(text: "Swift echo collect: \(messages.joined(separator: " "))"), fulfill: responseExpectation)
  107. var queue = call.newMessageQueue()
  108. for message in messages {
  109. queue = queue.flatMap { call.sendMessage(Echo_EchoRequest(text: message)) }
  110. }
  111. queue.whenSuccess { call.sendEnd(promise: nil) }
  112. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  113. }
  114. func testClientStreaming() {
  115. XCTAssertNoThrow(try doTestClientStreaming(messages: aFewStrings))
  116. }
  117. func testClientStreamingLotsOfMessages() throws {
  118. self.defaultTestTimeout = 15.0
  119. XCTAssertNoThrow(try doTestClientStreaming(messages: lotsOfStrings))
  120. }
  121. }
  122. extension NIOFunctionalTestsInsecureTransport {
  123. func doTestServerStreaming(messages: [String], file: StaticString = #file, line: UInt = #line) throws {
  124. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  125. let statusExpectation = self.makeStatusExpectation()
  126. var iterator = messages.enumerated().makeIterator()
  127. let call = client.expand(Echo_EchoRequest(text: messages.joined(separator: " "))) { response in
  128. if let (index, message) = iterator.next() {
  129. XCTAssertEqual(Echo_EchoResponse(text: "Swift echo expand (\(index)): \(message)"), response, file: file, line: line)
  130. responseExpectation.fulfill()
  131. } else {
  132. XCTFail("Too many responses received", file: file, line: line)
  133. }
  134. }
  135. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  136. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  137. }
  138. func testServerStreaming() {
  139. XCTAssertNoThrow(try doTestServerStreaming(messages: aFewStrings))
  140. }
  141. func testServerStreamingLotsOfMessages() {
  142. self.defaultTestTimeout = 15.0
  143. XCTAssertNoThrow(try doTestServerStreaming(messages: lotsOfStrings))
  144. }
  145. }
  146. extension NIOFunctionalTestsInsecureTransport {
  147. private func doTestBidirectionalStreaming(messages: [String], waitForEachResponse: Bool = false, file: StaticString = #file, line: UInt = #line) throws {
  148. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  149. let statusExpectation = self.makeStatusExpectation()
  150. let responseReceived = waitForEachResponse ? DispatchSemaphore(value: 0) : nil
  151. var iterator = messages.enumerated().makeIterator()
  152. let call = client.update { response in
  153. if let (index, message) = iterator.next() {
  154. XCTAssertEqual(Echo_EchoResponse(text: "Swift echo update (\(index)): \(message)"), response, file: file, line: line)
  155. responseExpectation.fulfill()
  156. responseReceived?.signal()
  157. } else {
  158. XCTFail("Too many responses received", file: file, line: line)
  159. }
  160. }
  161. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  162. messages.forEach { part in
  163. call.sendMessage(Echo_EchoRequest(text: part), promise: nil)
  164. XCTAssertNotEqual(responseReceived?.wait(timeout: .now() + .seconds(1)), .some(.timedOut), file: file, line: line)
  165. }
  166. call.sendEnd(promise: nil)
  167. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  168. }
  169. func testBidirectionalStreamingBatched() throws {
  170. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: aFewStrings))
  171. }
  172. func testBidirectionalStreamingPingPong() throws {
  173. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: aFewStrings, waitForEachResponse: true))
  174. }
  175. func testBidirectionalStreamingLotsOfMessagesBatched() throws {
  176. self.defaultTestTimeout = 15.0
  177. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: lotsOfStrings))
  178. }
  179. func testBidirectionalStreamingLotsOfMessagesPingPong() throws {
  180. self.defaultTestTimeout = 15.0
  181. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: lotsOfStrings, waitForEachResponse: true))
  182. }
  183. }
  184. class NIOFunctionalTestsAnonymousClient: NIOFunctionalTestsInsecureTransport {
  185. override var transportSecurity: TransportSecurity {
  186. return .anonymousClient
  187. }
  188. }
  189. class NIOFunctionalTestsMutualAuthentication: NIOFunctionalTestsInsecureTransport {
  190. override var transportSecurity: TransportSecurity {
  191. return .mutualAuthentication
  192. }
  193. }