ServerWebTests.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 EchoModel
  21. @testable import GRPC
  22. import NIO
  23. import XCTest
  24. // Only test Unary and ServerStreaming, as ClientStreaming is not
  25. // supported in HTTP1.
  26. // TODO: Add tests for application/grpc-web as well.
  27. class ServerWebTests: EchoTestCaseBase {
  28. private func gRPCEncodedEchoRequest(_ text: String) -> Data {
  29. var request = Echo_EchoRequest()
  30. request.text = text
  31. var data = try! request.serializedData()
  32. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  33. for i in 0 ..< 4 {
  34. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  35. }
  36. data.insert(UInt8(0), at: 0)
  37. return data
  38. }
  39. private func gRPCWebTrailers(status: Int = 0, message: String = "OK") -> Data {
  40. var data = "grpc-status: \(status)\r\ngrpc-message: \(message)".data(using: .utf8)!
  41. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  42. for i in 0 ..< 4 {
  43. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  44. }
  45. data.insert(UInt8(0x80), at: 0)
  46. return data
  47. }
  48. private func sendOverHTTP1(
  49. rpcMethod: String,
  50. message: String?,
  51. handler: @escaping (Data?, Error?) -> Void
  52. ) {
  53. let serverURL = URL(string: "http://localhost:\(self.port!)/echo.Echo/\(rpcMethod)")!
  54. var request = URLRequest(url: serverURL)
  55. request.httpMethod = "POST"
  56. request.setValue("application/grpc-web-text", forHTTPHeaderField: "content-type")
  57. if let message = message {
  58. request.httpBody = self.gRPCEncodedEchoRequest(message).base64EncodedData()
  59. }
  60. let sem = DispatchSemaphore(value: 0)
  61. URLSession.shared.dataTask(with: request) { data, _, error in
  62. handler(data, error)
  63. sem.signal()
  64. }.resume()
  65. sem.wait()
  66. }
  67. }
  68. extension ServerWebTests {
  69. func testUnary() {
  70. let message = "hello, world!"
  71. let expectedData = self.gRPCEncodedEchoRequest("Swift echo get: \(message)") + self
  72. .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 = self.gRPCWebTrailers(
  88. status: 13,
  89. message: "Request stream cardinality violation"
  90. )
  91. let expectedResponse = expectedData.base64EncodedString()
  92. let completionHandlerExpectation = expectation(description: "completion handler called")
  93. sendOverHTTP1(rpcMethod: "Get", message: nil) { data, error in
  94. XCTAssertNil(error)
  95. if let data = data {
  96. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  97. completionHandlerExpectation.fulfill()
  98. } else {
  99. XCTFail("no data returned")
  100. }
  101. }
  102. waitForExpectations(timeout: defaultTestTimeout)
  103. }
  104. func testUnaryLotsOfRequests() {
  105. guard self.runTimeSensitiveTests() else { return }
  106. // Sending that many requests at once can sometimes trip things up, it seems.
  107. let clockStart = clock()
  108. let numberOfRequests = 2000
  109. let completionHandlerExpectation = expectation(description: "completion handler called")
  110. completionHandlerExpectation.expectedFulfillmentCount = numberOfRequests
  111. completionHandlerExpectation.assertForOverFulfill = true
  112. for i in 0 ..< numberOfRequests {
  113. let message = "foo \(i)"
  114. let expectedData = self.gRPCEncodedEchoRequest("Swift echo get: \(message)") + self
  115. .gRPCWebTrailers()
  116. let expectedResponse = expectedData.base64EncodedString()
  117. self.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. completionHandlerExpectation.fulfill()
  122. }
  123. }
  124. }
  125. waitForExpectations(timeout: 10)
  126. print(
  127. "total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))"
  128. )
  129. }
  130. func testServerStreaming() {
  131. let message = "foo bar baz"
  132. var expectedData = Data()
  133. var index = 0
  134. message.split(separator: " ").forEach { component in
  135. expectedData.append(gRPCEncodedEchoRequest("Swift echo expand (\(index)): \(component)"))
  136. index += 1
  137. }
  138. expectedData.append(self.gRPCWebTrailers())
  139. let expectedResponse = expectedData.base64EncodedString()
  140. let completionHandlerExpectation = expectation(description: "completion handler called")
  141. sendOverHTTP1(rpcMethod: "Expand", message: message) { data, error in
  142. XCTAssertNil(error)
  143. if let data = data {
  144. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  145. completionHandlerExpectation.fulfill()
  146. }
  147. }
  148. waitForExpectations(timeout: defaultTestTimeout)
  149. }
  150. }