ServerWebTests.swift 5.8 KB

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