NIOServerWebTests.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. * Copyright 2018, 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 Foundation
  17. #if canImport(FoundationNetworking)
  18. import FoundationNetworking
  19. #endif
  20. import NIO
  21. @testable import SwiftGRPCNIO
  22. import XCTest
  23. // Only test Unary and ServerStreaming, as ClientStreaming is not
  24. // supported in HTTP1.
  25. // TODO: Add tests for application/grpc-web as well.
  26. class NIOServerWebTests: NIOBasicEchoTestCase {
  27. static var allTests: [(String, (NIOServerWebTests) -> () throws -> Void)] {
  28. return [
  29. ("testUnary", testUnary),
  30. ("testUnaryWithoutRequestMessage", testUnaryWithoutRequestMessage),
  31. //! FIXME: Broken on Linux: https://github.com/grpc/grpc-swift/issues/382
  32. // ("testUnaryLotsOfRequests", testUnaryLotsOfRequests),
  33. ("testServerStreaming", testServerStreaming),
  34. ]
  35. }
  36. private func gRPCEncodedEchoRequest(_ text: String) -> Data {
  37. var request = Echo_EchoRequest()
  38. request.text = text
  39. var data = try! request.serializedData()
  40. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  41. for i in 0..<4 {
  42. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  43. }
  44. data.insert(UInt8(0), at: 0)
  45. return data
  46. }
  47. private func gRPCWebTrailers(status: Int = 0, message: String = "OK") -> Data {
  48. var data = "grpc-status: \(status)\r\ngrpc-message: \(message)".data(using: .utf8)!
  49. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  50. for i in 0..<4 {
  51. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  52. }
  53. data.insert(UInt8(0x80), at: 0)
  54. return data
  55. }
  56. private func sendOverHTTP1(rpcMethod: String, message: String?, handler: @escaping (Data?, Error?) -> Void) {
  57. let serverURL = URL(string: "http://localhost:5050/echo.Echo/\(rpcMethod)")!
  58. var request = URLRequest(url: serverURL)
  59. request.httpMethod = "POST"
  60. request.setValue("application/grpc-web-text", forHTTPHeaderField: "content-type")
  61. if let message = message {
  62. request.httpBody = gRPCEncodedEchoRequest(message).base64EncodedData()
  63. }
  64. let sem = DispatchSemaphore(value: 0)
  65. URLSession.shared.dataTask(with: request) { (data, response, error) in
  66. handler(data, error)
  67. sem.signal()
  68. }.resume()
  69. _ = sem.wait()
  70. }
  71. }
  72. extension NIOServerWebTests {
  73. func testUnary() {
  74. let message = "hello, world!"
  75. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebTrailers()
  76. let expectedResponse = expectedData.base64EncodedString()
  77. let completionHandlerExpectation = expectation(description: "completion handler called")
  78. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  79. XCTAssertNil(error)
  80. if let data = data {
  81. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  82. completionHandlerExpectation.fulfill()
  83. } else {
  84. XCTFail("no data returned")
  85. }
  86. }
  87. waitForExpectations(timeout: defaultTestTimeout)
  88. }
  89. func testUnaryWithoutRequestMessage() {
  90. let expectedData = gRPCWebTrailers(
  91. status: 12, message: "request cardinality violation; method requires exactly one request but client sent none")
  92. let expectedResponse = expectedData.base64EncodedString()
  93. let completionHandlerExpectation = expectation(description: "completion handler called")
  94. sendOverHTTP1(rpcMethod: "Get", message: nil) { data, error in
  95. XCTAssertNil(error)
  96. if let data = data {
  97. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  98. completionHandlerExpectation.fulfill()
  99. } else {
  100. XCTFail("no data returned")
  101. }
  102. }
  103. waitForExpectations(timeout: defaultTestTimeout)
  104. }
  105. func testUnaryLotsOfRequests() {
  106. // Sending that many requests at once can sometimes trip things up, it seems.
  107. let clockStart = clock()
  108. let numberOfRequests = 2_000
  109. let completionHandlerExpectation = expectation(description: "completion handler called")
  110. // Linux version of Swift doesn't have the `expectedFulfillmentCount` API yet.
  111. // Implemented in https://github.com/apple/swift-corelibs-xctest/pull/228 but not yet
  112. // released.
  113. //
  114. // Wait for the expected number of responses (i.e. `numberOfRequests`) instead.
  115. var responses = 0
  116. for i in 0..<numberOfRequests {
  117. let message = "foo \(i)"
  118. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebTrailers()
  119. let expectedResponse = expectedData.base64EncodedString()
  120. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  121. XCTAssertNil(error)
  122. if let data = data {
  123. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  124. responses += 1
  125. if responses == numberOfRequests {
  126. completionHandlerExpectation.fulfill()
  127. }
  128. }
  129. }
  130. }
  131. waitForExpectations(timeout: 10)
  132. print("total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  133. }
  134. func testServerStreaming() {
  135. let message = "foo bar baz"
  136. var expectedData = Data()
  137. var index = 0
  138. message.split(separator: " ").forEach { (component) in
  139. expectedData.append(gRPCEncodedEchoRequest("Swift echo expand (\(index)): \(component)"))
  140. index += 1
  141. }
  142. expectedData.append(gRPCWebTrailers())
  143. let expectedResponse = expectedData.base64EncodedString()
  144. let completionHandlerExpectation = expectation(description: "completion handler called")
  145. sendOverHTTP1(rpcMethod: "Expand", message: message) { data, error in
  146. XCTAssertNil(error)
  147. if let data = data {
  148. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  149. completionHandlerExpectation.fulfill()
  150. }
  151. }
  152. waitForExpectations(timeout: defaultTestTimeout)
  153. }
  154. }