NIOServerWebTests.swift 6.2 KB

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