NIOServerWebTests.swift 5.3 KB

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