ServerWebTests.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 GRPC
  22. import EchoModel
  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(rpcMethod: String, message: String?, handler: @escaping (Data?, Error?) -> Void) {
  49. let serverURL = URL(string: "http://localhost:\(self.port!)/echo.Echo/\(rpcMethod)")!
  50. var request = URLRequest(url: serverURL)
  51. request.httpMethod = "POST"
  52. request.setValue("application/grpc-web-text", forHTTPHeaderField: "content-type")
  53. if let message = message {
  54. request.httpBody = gRPCEncodedEchoRequest(message).base64EncodedData()
  55. }
  56. let sem = DispatchSemaphore(value: 0)
  57. URLSession.shared.dataTask(with: request) { (data, response, error) in
  58. handler(data, error)
  59. sem.signal()
  60. }.resume()
  61. _ = sem.wait()
  62. }
  63. }
  64. extension ServerWebTests {
  65. func testUnary() {
  66. let message = "hello, world!"
  67. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebTrailers()
  68. let expectedResponse = expectedData.base64EncodedString()
  69. let completionHandlerExpectation = expectation(description: "completion handler called")
  70. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  71. XCTAssertNil(error)
  72. if let data = data {
  73. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  74. completionHandlerExpectation.fulfill()
  75. } else {
  76. XCTFail("no data returned")
  77. }
  78. }
  79. waitForExpectations(timeout: defaultTestTimeout)
  80. }
  81. func testUnaryWithoutRequestMessage() {
  82. let expectedData = gRPCWebTrailers(
  83. status: 12, message: "request cardinality violation; method requires exactly one request but client sent none")
  84. let expectedResponse = expectedData.base64EncodedString()
  85. let completionHandlerExpectation = expectation(description: "completion handler called")
  86. sendOverHTTP1(rpcMethod: "Get", message: nil) { data, error in
  87. XCTAssertNil(error)
  88. if let data = data {
  89. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  90. completionHandlerExpectation.fulfill()
  91. } else {
  92. XCTFail("no data returned")
  93. }
  94. }
  95. waitForExpectations(timeout: defaultTestTimeout)
  96. }
  97. func testUnaryLotsOfRequests() {
  98. // Sending that many requests at once can sometimes trip things up, it seems.
  99. let clockStart = clock()
  100. let numberOfRequests = 2_000
  101. let completionHandlerExpectation = expectation(description: "completion handler called")
  102. completionHandlerExpectation.expectedFulfillmentCount = numberOfRequests
  103. completionHandlerExpectation.assertForOverFulfill = true
  104. for i in 0..<numberOfRequests {
  105. let message = "foo \(i)"
  106. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebTrailers()
  107. let expectedResponse = expectedData.base64EncodedString()
  108. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  109. XCTAssertNil(error)
  110. if let data = data {
  111. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  112. completionHandlerExpectation.fulfill()
  113. }
  114. }
  115. }
  116. waitForExpectations(timeout: 10)
  117. print("total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  118. }
  119. func testServerStreaming() {
  120. let message = "foo bar baz"
  121. var expectedData = Data()
  122. var index = 0
  123. message.split(separator: " ").forEach { (component) in
  124. expectedData.append(gRPCEncodedEchoRequest("Swift echo expand (\(index)): \(component)"))
  125. index += 1
  126. }
  127. expectedData.append(gRPCWebTrailers())
  128. let expectedResponse = expectedData.base64EncodedString()
  129. let completionHandlerExpectation = expectation(description: "completion handler called")
  130. sendOverHTTP1(rpcMethod: "Expand", message: message) { data, error in
  131. XCTAssertNil(error)
  132. if let data = data {
  133. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  134. completionHandlerExpectation.fulfill()
  135. }
  136. }
  137. waitForExpectations(timeout: defaultTestTimeout)
  138. }
  139. }