NIOServerWebTests.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 SwiftGRPCNIO
  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 NIOServerWebTests: NIOServerTestCase {
  24. static var allTests: [(String, (NIOServerWebTests) -> () throws -> Void)] {
  25. return [
  26. ("testUnary", testUnary),
  27. //! FIXME: Broken on Linux: https://github.com/grpc/grpc-swift/issues/382
  28. // ("testUnaryLotsOfRequests", testUnaryLotsOfRequests),
  29. ("testServerStreaming", testServerStreaming),
  30. ]
  31. }
  32. var eventLoopGroup: MultiThreadedEventLoopGroup!
  33. var server: GRPCServer!
  34. override func setUp() {
  35. super.setUp()
  36. // This is how a GRPC server would actually be set up.
  37. eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  38. server = try! GRPCServer.start(
  39. hostname: "localhost", port: 5050, eventLoopGroup: eventLoopGroup, serviceProviders: [EchoProvider_NIO()])
  40. .wait()
  41. }
  42. override func tearDown() {
  43. XCTAssertNoThrow(try server.close().wait())
  44. XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
  45. eventLoopGroup = nil
  46. super.tearDown()
  47. }
  48. private func gRPCEncodedEchoRequest(_ text: String) -> Data {
  49. var request = Echo_EchoRequest()
  50. request.text = text
  51. var data = try! request.serializedData()
  52. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  53. for i in 0..<4 {
  54. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  55. }
  56. data.insert(UInt8(0), at: 0)
  57. return data
  58. }
  59. private func gRPCWebOKTrailers() -> Data {
  60. var data = "grpc-status: 0\r\ngrpc-message: OK".data(using: .utf8)!
  61. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  62. for i in 0..<4 {
  63. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  64. }
  65. data.insert(UInt8(0x80), at: 0)
  66. return data
  67. }
  68. private func sendOverHTTP1(rpcMethod: String, message: String, handler: @escaping (Data?, Error?) -> Void) {
  69. let serverURL = URL(string: "http://localhost:5050/echo.Echo/\(rpcMethod)")!
  70. var request = URLRequest(url: serverURL)
  71. request.httpMethod = "POST"
  72. request.setValue("application/grpc-web-text", forHTTPHeaderField: "content-type")
  73. request.httpBody = gRPCEncodedEchoRequest(message).base64EncodedData()
  74. let sem = DispatchSemaphore(value: 0)
  75. URLSession.shared.dataTask(with: request) { (data, response, error) in
  76. handler(data, error)
  77. sem.signal()
  78. }.resume()
  79. _ = sem.wait()
  80. }
  81. }
  82. extension NIOServerWebTests {
  83. func testUnary() {
  84. let message = "hello, world!"
  85. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebOKTrailers()
  86. let expectedResponse = expectedData.base64EncodedString()
  87. let completionHandlerExpectation = expectation(description: "completion handler called")
  88. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  89. XCTAssertNil(error)
  90. if let data = data {
  91. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  92. completionHandlerExpectation.fulfill()
  93. }
  94. }
  95. waitForExpectations(timeout: defaultTimeout)
  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. // Linux version of Swift doesn't have the `expectedFulfillmentCount` API yet.
  103. // Implemented in https://github.com/apple/swift-corelibs-xctest/pull/228 but not yet
  104. // released.
  105. //
  106. // Wait for the expected number of responses (i.e. `numberOfRequests`) instead.
  107. var responses = 0
  108. for i in 0..<numberOfRequests {
  109. let message = "foo \(i)"
  110. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebOKTrailers()
  111. let expectedResponse = expectedData.base64EncodedString()
  112. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  113. XCTAssertNil(error)
  114. if let data = data {
  115. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  116. responses += 1
  117. if responses == numberOfRequests {
  118. completionHandlerExpectation.fulfill()
  119. }
  120. }
  121. }
  122. }
  123. waitForExpectations(timeout: 10)
  124. print("total time for \(numberOfRequests) requests: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))")
  125. }
  126. func testServerStreaming() {
  127. let message = "foo bar baz"
  128. var expectedData = Data()
  129. var index = 0
  130. message.split(separator: " ").forEach { (component) in
  131. expectedData.append(gRPCEncodedEchoRequest("Swift echo expand (\(index)): \(component)"))
  132. index += 1
  133. }
  134. expectedData.append(gRPCWebOKTrailers())
  135. let expectedResponse = expectedData.base64EncodedString()
  136. let completionHandlerExpectation = expectation(description: "completion handler called")
  137. sendOverHTTP1(rpcMethod: "Expand", message: message) { data, error in
  138. XCTAssertNil(error)
  139. if let data = data {
  140. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  141. completionHandlerExpectation.fulfill()
  142. }
  143. }
  144. waitForExpectations(timeout: defaultTimeout)
  145. }
  146. }