FunctionalTests.swift 12 KB

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