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