ServerWebTests.swift 5.6 KB

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