FunctionalTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 EchoModel
  18. import Foundation
  19. @testable import GRPC
  20. import NIO
  21. import NIOHTTP1
  22. import NIOHTTP2
  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 ..< 500).map {
  33. String(describing: $0)
  34. }
  35. }
  36. func doTestUnary(
  37. request: Echo_EchoRequest,
  38. expect response: Echo_EchoResponse,
  39. file: StaticString = #file,
  40. line: UInt = #line
  41. ) {
  42. let responseExpectation = self.makeResponseExpectation()
  43. let statusExpectation = self.makeStatusExpectation()
  44. let call = client.get(request)
  45. call.response.assertEqual(response, fulfill: responseExpectation, file: file, line: line)
  46. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  47. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  48. }
  49. func doTestUnary(message: String, file: StaticString = #file, line: UInt = #line) {
  50. self.doTestUnary(
  51. request: Echo_EchoRequest(text: message),
  52. expect: Echo_EchoResponse(text: "Swift echo get: \(message)"),
  53. file: file,
  54. line: line
  55. )
  56. }
  57. func testUnary() throws {
  58. self.doTestUnary(message: "foo")
  59. }
  60. func testUnaryLotsOfRequests() throws {
  61. guard self.runTimeSensitiveTests() else { return }
  62. // Sending that many requests at once can sometimes trip things up, it seems.
  63. let clockStart = clock()
  64. let numberOfRequests = 200
  65. // Due to https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401 we need to
  66. // limit the number of active streams. The default in NIOHTTP2 is 100, so we'll use it too.
  67. //
  68. // In the future we might want to build in some kind of mechanism which handles this for the
  69. // user.
  70. let batchSize = 100
  71. // Instead of setting a timeout out on the test we'll set one for each batch, if any of them
  72. // timeout then we'll bail out of the test.
  73. let batchTimeout: TimeInterval = 30.0
  74. self.continueAfterFailure = false
  75. for lowerBound in stride(from: 0, to: numberOfRequests, by: batchSize) {
  76. let upperBound = min(lowerBound + batchSize, numberOfRequests)
  77. let numberOfCalls = upperBound - lowerBound
  78. let responseExpectation = self
  79. .makeResponseExpectation(expectedFulfillmentCount: numberOfCalls)
  80. let statusExpectation = self.makeStatusExpectation(expectedFulfillmentCount: numberOfCalls)
  81. for i in lowerBound ..< upperBound {
  82. let request = Echo_EchoRequest(text: "foo \(i)")
  83. let response = Echo_EchoResponse(text: "Swift echo get: foo \(i)")
  84. let get = client.get(request)
  85. get.response.assertEqual(response, fulfill: responseExpectation)
  86. get.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  87. }
  88. if upperBound % 100 == 0 {
  89. print(
  90. "\(upperBound) requests sent so far, elapsed time: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))"
  91. )
  92. }
  93. self.wait(for: [responseExpectation, statusExpectation], timeout: batchTimeout)
  94. }
  95. print(
  96. "total time to receive \(numberOfRequests) responses: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))"
  97. )
  98. }
  99. func testUnaryWithLargeData() throws {
  100. // Default max frame size is: 16,384. We'll exceed this as we also have to send the size and compression flag.
  101. let longMessage = String(repeating: "e", count: 16384)
  102. self.doTestUnary(message: longMessage)
  103. }
  104. func testUnaryEmptyRequest() throws {
  105. self.doTestUnary(
  106. request: Echo_EchoRequest(),
  107. expect: Echo_EchoResponse(text: "Swift echo get: ")
  108. )
  109. }
  110. func doTestClientStreaming(
  111. messages: [String],
  112. file: StaticString = #file,
  113. line: UInt = #line
  114. ) throws {
  115. let responseExpectation = self.makeResponseExpectation()
  116. let statusExpectation = self.makeStatusExpectation()
  117. let call = client.collect(callOptions: CallOptions(timeLimit: .none))
  118. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line)
  119. call.response.assertEqual(
  120. Echo_EchoResponse(text: "Swift echo collect: \(messages.joined(separator: " "))"),
  121. fulfill: responseExpectation
  122. )
  123. call.sendMessages(messages.map { .init(text: $0) }, promise: nil)
  124. call.sendEnd(promise: nil)
  125. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  126. }
  127. func testClientStreaming() {
  128. XCTAssertNoThrow(try self.doTestClientStreaming(messages: self.aFewStrings))
  129. }
  130. func testClientStreamingLotsOfMessages() throws {
  131. guard self.runTimeSensitiveTests() else { return }
  132. XCTAssertNoThrow(try self.doTestClientStreaming(messages: self.lotsOfStrings))
  133. }
  134. private func doTestServerStreaming(messages: [String], line: UInt = #line) throws {
  135. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  136. let statusExpectation = self.makeStatusExpectation()
  137. var iterator = messages.enumerated().makeIterator()
  138. let call = client.expand(Echo_EchoRequest(text: messages.joined(separator: " "))) { response in
  139. if let (index, message) = iterator.next() {
  140. XCTAssertEqual(
  141. Echo_EchoResponse(text: "Swift echo expand (\(index)): \(message)"),
  142. response,
  143. line: line
  144. )
  145. responseExpectation.fulfill()
  146. } else {
  147. XCTFail("Too many responses received", line: line)
  148. }
  149. }
  150. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, line: line)
  151. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  152. }
  153. func testServerStreaming() {
  154. XCTAssertNoThrow(try self.doTestServerStreaming(messages: self.aFewStrings))
  155. }
  156. func testServerStreamingLotsOfMessages() {
  157. guard self.runTimeSensitiveTests() else { return }
  158. XCTAssertNoThrow(try self.doTestServerStreaming(messages: self.lotsOfStrings))
  159. }
  160. private func doTestBidirectionalStreaming(
  161. messages: [String],
  162. waitForEachResponse: Bool = false,
  163. line: UInt = #line
  164. ) throws {
  165. let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count)
  166. let statusExpectation = self.makeStatusExpectation()
  167. let responseReceived = waitForEachResponse ? DispatchSemaphore(value: 0) : nil
  168. var iterator = messages.enumerated().makeIterator()
  169. let call = client.update { response in
  170. if let (index, message) = iterator.next() {
  171. XCTAssertEqual(
  172. Echo_EchoResponse(text: "Swift echo update (\(index)): \(message)"),
  173. response,
  174. line: line
  175. )
  176. responseExpectation.fulfill()
  177. responseReceived?.signal()
  178. } else {
  179. XCTFail("Too many responses received", line: line)
  180. }
  181. }
  182. call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, line: line)
  183. messages.forEach { part in
  184. call.sendMessage(Echo_EchoRequest(text: part), promise: nil)
  185. XCTAssertNotEqual(
  186. responseReceived?.wait(timeout: .now() + .seconds(30)),
  187. .some(.timedOut),
  188. line: line
  189. )
  190. }
  191. call.sendEnd(promise: nil)
  192. self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout)
  193. }
  194. func testBidirectionalStreamingBatched() throws {
  195. XCTAssertNoThrow(try self.doTestBidirectionalStreaming(messages: self.aFewStrings))
  196. }
  197. func testBidirectionalStreamingPingPong() throws {
  198. XCTAssertNoThrow(
  199. try self
  200. .doTestBidirectionalStreaming(messages: self.aFewStrings, waitForEachResponse: true)
  201. )
  202. }
  203. func testBidirectionalStreamingLotsOfMessagesBatched() throws {
  204. guard self.runTimeSensitiveTests() else { return }
  205. XCTAssertNoThrow(try self.doTestBidirectionalStreaming(messages: self.lotsOfStrings))
  206. }
  207. func testBidirectionalStreamingLotsOfMessagesPingPong() throws {
  208. guard self.runTimeSensitiveTests() else { return }
  209. XCTAssertNoThrow(
  210. try self
  211. .doTestBidirectionalStreaming(messages: self.lotsOfStrings, waitForEachResponse: true)
  212. )
  213. }
  214. }
  215. class FunctionalTestsAnonymousClient: FunctionalTestsInsecureTransport {
  216. override var transportSecurity: TransportSecurity {
  217. return .anonymousClient
  218. }
  219. }
  220. class FunctionalTestsMutualAuthentication: FunctionalTestsInsecureTransport {
  221. override var transportSecurity: TransportSecurity {
  222. return .mutualAuthentication
  223. }
  224. }
  225. // MARK: - Variants using NIO TS and Network.framework
  226. // Unfortunately `swift test --generate-linuxmain` uses the macOS test discovery. Because of this
  227. // it's difficult to avoid tests which run on Linux. To get around this shortcoming we can just
  228. // run no-op tests on Linux.
  229. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  230. class FunctionalTestsInsecureTransportNIOTS: FunctionalTestsInsecureTransport {
  231. override var networkPreference: NetworkPreference {
  232. #if canImport(Network)
  233. return .userDefined(.networkFramework)
  234. #else
  235. // We shouldn't need this, since the tests won't do anything. However, we still need to be able
  236. // to compile this class.
  237. return .userDefined(.posix)
  238. #endif
  239. }
  240. override func testBidirectionalStreamingBatched() throws {
  241. #if canImport(Network)
  242. try super.testBidirectionalStreamingBatched()
  243. #endif
  244. }
  245. override func testBidirectionalStreamingLotsOfMessagesBatched() throws {
  246. #if canImport(Network)
  247. try super.testBidirectionalStreamingLotsOfMessagesBatched()
  248. #endif
  249. }
  250. override func testBidirectionalStreamingLotsOfMessagesPingPong() throws {
  251. #if canImport(Network)
  252. try super.testBidirectionalStreamingLotsOfMessagesPingPong()
  253. #endif
  254. }
  255. override func testBidirectionalStreamingPingPong() throws {
  256. #if canImport(Network)
  257. try super.testBidirectionalStreamingPingPong()
  258. #endif
  259. }
  260. override func testClientStreaming() {
  261. #if canImport(Network)
  262. super.testClientStreaming()
  263. #endif
  264. }
  265. override func testClientStreamingLotsOfMessages() throws {
  266. #if canImport(Network)
  267. try super.testClientStreamingLotsOfMessages()
  268. #endif
  269. }
  270. override func testServerStreaming() {
  271. #if canImport(Network)
  272. super.testServerStreaming()
  273. #endif
  274. }
  275. override func testServerStreamingLotsOfMessages() {
  276. #if canImport(Network)
  277. super.testServerStreamingLotsOfMessages()
  278. #endif
  279. }
  280. override func testUnary() throws {
  281. #if canImport(Network)
  282. try super.testUnary()
  283. #endif
  284. }
  285. override func testUnaryEmptyRequest() throws {
  286. #if canImport(Network)
  287. try super.testUnaryEmptyRequest()
  288. #endif
  289. }
  290. override func testUnaryLotsOfRequests() throws {
  291. #if canImport(Network)
  292. try super.testUnaryLotsOfRequests()
  293. #endif
  294. }
  295. override func testUnaryWithLargeData() throws {
  296. #if canImport(Network)
  297. try super.testUnaryWithLargeData()
  298. #endif
  299. }
  300. }
  301. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  302. class FunctionalTestsAnonymousClientNIOTS: FunctionalTestsInsecureTransportNIOTS {
  303. override var transportSecurity: TransportSecurity {
  304. return .anonymousClient
  305. }
  306. }
  307. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  308. class FunctionalTestsMutualAuthenticationNIOTS: FunctionalTestsInsecureTransportNIOTS {
  309. override var transportSecurity: TransportSecurity {
  310. return .mutualAuthentication
  311. }
  312. }