ServerWebTests.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 EchoModel
  17. import Foundation
  18. import NIOCore
  19. import XCTest
  20. @testable import GRPC
  21. #if canImport(FoundationNetworking)
  22. import FoundationNetworking
  23. #endif
  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? = nil) -> Data {
  40. var data: Data
  41. if let message = message {
  42. data = "grpc-status: \(status)\r\ngrpc-message: \(message)\r\n".data(using: .utf8)!
  43. } else {
  44. data = "grpc-status: \(status)\r\n".data(using: .utf8)!
  45. }
  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(
  54. rpcMethod: String,
  55. message: String?,
  56. handler: @escaping (Data?, Error?) -> Void
  57. ) {
  58. let serverURL = URL(string: "http://localhost:\(self.port!)/echo.Echo/\(rpcMethod)")!
  59. var request = URLRequest(url: serverURL)
  60. request.httpMethod = "POST"
  61. request.setValue("application/grpc-web-text", forHTTPHeaderField: "content-type")
  62. if let message = message {
  63. request.httpBody = self.gRPCEncodedEchoRequest(message).base64EncodedData()
  64. }
  65. let sem = DispatchSemaphore(value: 0)
  66. URLSession.shared.dataTask(with: request) { data, _, error in
  67. handler(data, error)
  68. sem.signal()
  69. }.resume()
  70. sem.wait()
  71. }
  72. }
  73. extension ServerWebTests {
  74. func testUnary() {
  75. let message = "hello, world!"
  76. let expectedData =
  77. self.gRPCEncodedEchoRequest("Swift echo get: \(message)") + self.gRPCWebTrailers()
  78. let expectedResponse = expectedData.base64EncodedString()
  79. let completionHandlerExpectation = expectation(description: "completion handler called")
  80. self.sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  81. XCTAssertNil(error)
  82. if let data = data {
  83. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  84. completionHandlerExpectation.fulfill()
  85. } else {
  86. XCTFail("no data returned")
  87. }
  88. }
  89. waitForExpectations(timeout: defaultTestTimeout)
  90. }
  91. func testUnaryWithoutRequestMessage() {
  92. let expectedData = self.gRPCWebTrailers(
  93. status: 13,
  94. message: "Protocol violation: End received before message"
  95. )
  96. let expectedResponse = expectedData.base64EncodedString()
  97. let completionHandlerExpectation = expectation(description: "completion handler called")
  98. self.sendOverHTTP1(rpcMethod: "Get", message: nil) { data, error in
  99. XCTAssertNil(error)
  100. if let data = data {
  101. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  102. completionHandlerExpectation.fulfill()
  103. } else {
  104. XCTFail("no data returned")
  105. }
  106. }
  107. waitForExpectations(timeout: defaultTestTimeout)
  108. }
  109. func testUnaryLotsOfRequests() {
  110. guard self.runTimeSensitiveTests() else { return }
  111. // Sending that many requests at once can sometimes trip things up, it seems.
  112. let clockStart = clock()
  113. let numberOfRequests = 2000
  114. let completionHandlerExpectation = expectation(description: "completion handler called")
  115. completionHandlerExpectation.expectedFulfillmentCount = numberOfRequests
  116. completionHandlerExpectation.assertForOverFulfill = true
  117. for i in 0 ..< numberOfRequests {
  118. let message = "foo \(i)"
  119. let expectedData =
  120. self.gRPCEncodedEchoRequest("Swift echo get: \(message)") + self.gRPCWebTrailers()
  121. let expectedResponse = expectedData.base64EncodedString()
  122. self.sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  123. XCTAssertNil(error)
  124. if let data = data {
  125. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  126. completionHandlerExpectation.fulfill()
  127. }
  128. }
  129. }
  130. waitForExpectations(timeout: 10)
  131. print(
  132. "total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))"
  133. )
  134. }
  135. func testServerStreaming() {
  136. let message = "foo bar baz"
  137. var expectedData = Data()
  138. var index = 0
  139. message.split(separator: " ").forEach { component in
  140. expectedData.append(self.gRPCEncodedEchoRequest("Swift echo expand (\(index)): \(component)"))
  141. index += 1
  142. }
  143. expectedData.append(self.gRPCWebTrailers())
  144. let expectedResponse = expectedData.base64EncodedString()
  145. let completionHandlerExpectation = expectation(description: "completion handler called")
  146. self.sendOverHTTP1(rpcMethod: "Expand", message: message) { data, error in
  147. XCTAssertNil(error)
  148. if let data = data {
  149. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  150. completionHandlerExpectation.fulfill()
  151. }
  152. }
  153. waitForExpectations(timeout: defaultTestTimeout)
  154. }
  155. }