FunctionalTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 GRPC
  22. import EchoModel
  23. import XCTest
  24. class FunctionalTestsInsecureTransport: EchoTestCaseBase {
  25. override var transportSecurity: TransportSecurity {
  26. return .none
  27. }
  28. var aFewStrings: [String] {
  29. return ["foo", "bar", "baz"]
  30. }
  31. var lotsOfStrings: [String] {
  32. return (0..<5_000).map {
  33. String(describing: $0)
  34. }
  35. }
  36. func doTestUnary(request: Echo_EchoRequest, expect response: Echo_EchoResponse, file: StaticString = #file, line: UInt = #line) {
  37. let responseExpectation = self.makeResponseExpectation()
  38. let statusExpectation = self.makeStatusExpectation()
  39. let call = client.get(request)
  40. call.response.assertEqual(response, fulfill: responseExpectation, file: file, line: line)
  41. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  42. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  43. }
  44. func doTestUnary(message: String, file: StaticString = #file, line: UInt = #line) {
  45. self.doTestUnary(request: Echo_EchoRequest(text: message), expect: Echo_EchoResponse(text: "Swift echo get: \(message)"), file: file, line: line)
  46. }
  47. func testUnary() throws {
  48. self.doTestUnary(message: "foo")
  49. }
  50. func testUnaryLotsOfRequests() throws {
  51. guard self.runTimeSensitiveTests() else { return }
  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 = 30.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. func doTestClientStreaming(messages: [String], file: StaticString = #file, line: UInt = #line) throws {
  93. let responseExpectation = self.makeResponseExpectation()
  94. let statusExpectation = self.makeStatusExpectation()
  95. let call = client.collect(callOptions: CallOptions(timeLimit: .none))
  96. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  97. call.response.assertEqual(Echo_EchoResponse(text: "Swift echo collect: \(messages.joined(separator: " "))"), fulfill: responseExpectation)
  98. call.sendMessages(messages.map { .init(text: $0) }, promise: nil)
  99. call.sendEnd(promise: nil)
  100. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  101. }
  102. func testClientStreaming() {
  103. XCTAssertNoThrow(try doTestClientStreaming(messages: aFewStrings))
  104. }
  105. func testClientStreamingLotsOfMessages() throws {
  106. guard self.runTimeSensitiveTests() else { return }
  107. XCTAssertNoThrow(try doTestClientStreaming(messages: lotsOfStrings))
  108. }
  109. private func doTestServerStreaming(messages: [String], line: UInt = #line) throws {
  110. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  111. let statusExpectation = self.makeStatusExpectation()
  112. var iterator = messages.enumerated().makeIterator()
  113. let call = client.expand(Echo_EchoRequest(text: messages.joined(separator: " "))) { response in
  114. if let (index, message) = iterator.next() {
  115. XCTAssertEqual(Echo_EchoResponse(text: "Swift echo expand (\(index)): \(message)"), response, line: line)
  116. responseExpectation.fulfill()
  117. } else {
  118. XCTFail("Too many responses received", line: line)
  119. }
  120. }
  121. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, line: line)
  122. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  123. }
  124. func testServerStreaming() {
  125. XCTAssertNoThrow(try doTestServerStreaming(messages: aFewStrings))
  126. }
  127. func testServerStreamingLotsOfMessages() {
  128. guard self.runTimeSensitiveTests() else { return }
  129. XCTAssertNoThrow(try doTestServerStreaming(messages: lotsOfStrings))
  130. }
  131. private func doTestBidirectionalStreaming(messages: [String], waitForEachResponse: Bool = false, line: UInt = #line) throws {
  132. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  133. let statusExpectation = self.makeStatusExpectation()
  134. let responseReceived = waitForEachResponse ? DispatchSemaphore(value: 0) : nil
  135. var iterator = messages.enumerated().makeIterator()
  136. let call = client.update { response in
  137. if let (index, message) = iterator.next() {
  138. XCTAssertEqual(Echo_EchoResponse(text: "Swift echo update (\(index)): \(message)"), response, line: line)
  139. responseExpectation.fulfill()
  140. responseReceived?.signal()
  141. } else {
  142. XCTFail("Too many responses received", line: line)
  143. }
  144. }
  145. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, line: line)
  146. messages.forEach { part in
  147. call.sendMessage(Echo_EchoRequest(text: part), promise: nil)
  148. XCTAssertNotEqual(responseReceived?.wait(timeout: .now() + .seconds(30)), .some(.timedOut), line: line)
  149. }
  150. call.sendEnd(promise: nil)
  151. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  152. }
  153. func testBidirectionalStreamingBatched() throws {
  154. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: aFewStrings))
  155. }
  156. func testBidirectionalStreamingPingPong() throws {
  157. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: aFewStrings, waitForEachResponse: true))
  158. }
  159. func testBidirectionalStreamingLotsOfMessagesBatched() throws {
  160. guard self.runTimeSensitiveTests() else { return }
  161. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: lotsOfStrings))
  162. }
  163. func testBidirectionalStreamingLotsOfMessagesPingPong() throws {
  164. guard self.runTimeSensitiveTests() else { return }
  165. XCTAssertNoThrow(try doTestBidirectionalStreaming(messages: lotsOfStrings, waitForEachResponse: true))
  166. }
  167. }
  168. class FunctionalTestsAnonymousClient: FunctionalTestsInsecureTransport {
  169. override var transportSecurity: TransportSecurity {
  170. return .anonymousClient
  171. }
  172. }
  173. class FunctionalTestsMutualAuthentication: FunctionalTestsInsecureTransport {
  174. override var transportSecurity: TransportSecurity {
  175. return .mutualAuthentication
  176. }
  177. }
  178. // MARK: - Variants using NIO TS and Network.framework
  179. // Unfortunately `swift test --generate-linuxmain` uses the macOS test discovery. Because of this
  180. // it's difficult to avoid tests which run on Linux. To get around this shortcoming we can just
  181. // run no-op tests on Linux.
  182. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  183. class FunctionalTestsInsecureTransportNIOTS: FunctionalTestsInsecureTransport {
  184. override var networkPreference: NetworkPreference {
  185. #if canImport(Network)
  186. return .userDefined(.networkFramework)
  187. #else
  188. // We shouldn't need this, since the tests won't do anything. However, we still need to be able
  189. // to compile this class.
  190. return .userDefined(.posix)
  191. #endif
  192. }
  193. override func testBidirectionalStreamingBatched() throws {
  194. #if canImport(Network)
  195. try super.testBidirectionalStreamingBatched()
  196. #endif
  197. }
  198. override func testBidirectionalStreamingLotsOfMessagesBatched() throws {
  199. #if canImport(Network)
  200. try super.testBidirectionalStreamingLotsOfMessagesBatched()
  201. #endif
  202. }
  203. override func testBidirectionalStreamingLotsOfMessagesPingPong() throws {
  204. #if canImport(Network)
  205. try super.testBidirectionalStreamingLotsOfMessagesPingPong()
  206. #endif
  207. }
  208. override func testBidirectionalStreamingPingPong() throws {
  209. #if canImport(Network)
  210. try super.testBidirectionalStreamingPingPong()
  211. #endif
  212. }
  213. override func testClientStreaming() {
  214. #if canImport(Network)
  215. super.testClientStreaming()
  216. #endif
  217. }
  218. override func testClientStreamingLotsOfMessages() throws {
  219. #if canImport(Network)
  220. try super.testClientStreamingLotsOfMessages()
  221. #endif
  222. }
  223. override func testServerStreaming() {
  224. #if canImport(Network)
  225. super.testServerStreaming()
  226. #endif
  227. }
  228. override func testServerStreamingLotsOfMessages() {
  229. #if canImport(Network)
  230. super.testServerStreamingLotsOfMessages()
  231. #endif
  232. }
  233. override func testUnary() throws {
  234. #if canImport(Network)
  235. try super.testUnary()
  236. #endif
  237. }
  238. override func testUnaryEmptyRequest() throws {
  239. #if canImport(Network)
  240. try super.testUnaryEmptyRequest()
  241. #endif
  242. }
  243. override func testUnaryLotsOfRequests() throws {
  244. #if canImport(Network)
  245. try super.testUnaryLotsOfRequests()
  246. #endif
  247. }
  248. override func testUnaryWithLargeData() throws {
  249. #if canImport(Network)
  250. try super.testUnaryWithLargeData()
  251. #endif
  252. }
  253. }
  254. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  255. class FunctionalTestsAnonymousClientNIOTS: FunctionalTestsInsecureTransportNIOTS {
  256. override var transportSecurity: TransportSecurity {
  257. return .anonymousClient
  258. }
  259. }
  260. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  261. class FunctionalTestsMutualAuthenticationNIOTS: FunctionalTestsInsecureTransportNIOTS {
  262. override var transportSecurity: TransportSecurity {
  263. return .mutualAuthentication
  264. }
  265. }