ServerWebTests.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. completionHandlerExpectation.expectedFulfillmentCount = numberOfRequests
  99. completionHandlerExpectation.assertForOverFulfill = true
  100. for i in 0..<numberOfRequests {
  101. let message = "foo \(i)"
  102. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebTrailers()
  103. let expectedResponse = expectedData.base64EncodedString()
  104. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  105. XCTAssertNil(error)
  106. if let data = data {
  107. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  108. completionHandlerExpectation.fulfill()
  109. }
  110. }
  111. }
  112. waitForExpectations(timeout: 10)
  113. print("total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  114. }
  115. func testServerStreaming() {
  116. let message = "foo bar baz"
  117. var expectedData = Data()
  118. var index = 0
  119. message.split(separator: " ").forEach { (component) in
  120. expectedData.append(gRPCEncodedEchoRequest("Swift echo expand (\(index)): \(component)"))
  121. index += 1
  122. }
  123. expectedData.append(gRPCWebTrailers())
  124. let expectedResponse = expectedData.base64EncodedString()
  125. let completionHandlerExpectation = expectation(description: "completion handler called")
  126. sendOverHTTP1(rpcMethod: "Expand", message: message) { data, error in
  127. XCTAssertNil(error)
  128. if let data = data {
  129. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  130. completionHandlerExpectation.fulfill()
  131. }
  132. }
  133. waitForExpectations(timeout: defaultTestTimeout)
  134. }
  135. }