NIOServerWebTests.swift 5.7 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 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. ("testUnaryLotsOfRequests", testUnaryLotsOfRequests),
  28. ("testServerStreaming", testServerStreaming),
  29. ]
  30. }
  31. var eventLoopGroup: MultiThreadedEventLoopGroup!
  32. var server: GRPCServer!
  33. override func setUp() {
  34. super.setUp()
  35. // This is how a GRPC server would actually be set up.
  36. eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  37. server = try! GRPCServer.start(
  38. hostname: "localhost", port: 5050, eventLoopGroup: eventLoopGroup, serviceProviders: [EchoProvider_NIO()])
  39. .wait()
  40. }
  41. override func tearDown() {
  42. XCTAssertNoThrow(try server.close().wait())
  43. XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
  44. eventLoopGroup = nil
  45. super.tearDown()
  46. }
  47. private func gRPCEncodedEchoRequest(_ text: String) -> Data {
  48. var request = Echo_EchoRequest()
  49. request.text = text
  50. var data = try! request.serializedData()
  51. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  52. for i in 0..<4 {
  53. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  54. }
  55. data.insert(UInt8(0), at: 0)
  56. return data
  57. }
  58. private func gRPCWebOKTrailers() -> Data {
  59. var data = "grpc-status: 0\r\ngrpc-message: OK".data(using: .utf8)!
  60. // Add the gRPC prefix with the compression byte and the 4 length bytes.
  61. for i in 0..<4 {
  62. data.insert(UInt8((data.count >> (i * 8)) & 0xFF), at: 0)
  63. }
  64. data.insert(UInt8(0x80), at: 0)
  65. return data
  66. }
  67. private func sendOverHTTP1(rpcMethod: String, message: String, handler: @escaping (Data?, Error?) -> Void) {
  68. let serverURL = URL(string: "http://localhost:5050/echo.Echo/\(rpcMethod)")!
  69. var request = URLRequest(url: serverURL)
  70. request.httpMethod = "POST"
  71. request.setValue("application/grpc-web-text", forHTTPHeaderField: "content-type")
  72. request.httpBody = gRPCEncodedEchoRequest(message).base64EncodedData()
  73. let sem = DispatchSemaphore(value: 0)
  74. URLSession.shared.dataTask(with: request) { (data, response, error) in
  75. handler(data, error)
  76. sem.signal()
  77. }.resume()
  78. _ = sem.wait()
  79. }
  80. }
  81. extension NIOServerWebTests {
  82. func testUnary() {
  83. let message = "hello, world!"
  84. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebOKTrailers()
  85. let expectedResponse = expectedData.base64EncodedString()
  86. let completionHandlerExpectation = expectation(description: "completion handler called")
  87. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  88. XCTAssertNil(error)
  89. if let data = data {
  90. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  91. completionHandlerExpectation.fulfill()
  92. }
  93. }
  94. waitForExpectations(timeout: defaultTimeout)
  95. }
  96. func testUnaryLotsOfRequests() {
  97. // Sending that many requests at once can sometimes trip things up, it seems.
  98. let clockStart = clock()
  99. let numberOfRequests = 2_000
  100. let completionHandlerExpectation = expectation(description: "completion handler called")
  101. #if os(macOS)
  102. // Linux version of Swift doesn't have this API yet.
  103. // Implemented in https://github.com/apple/swift-corelibs-xctest/pull/228 but not yet
  104. // released.
  105. completionHandlerExpectation.expectedFulfillmentCount = numberOfRequests
  106. #endif
  107. for i in 0..<numberOfRequests {
  108. let message = "foo \(i)"
  109. let expectedData = gRPCEncodedEchoRequest("Swift echo get: \(message)") + gRPCWebOKTrailers()
  110. let expectedResponse = expectedData.base64EncodedString()
  111. sendOverHTTP1(rpcMethod: "Get", message: message) { data, error in
  112. XCTAssertNil(error)
  113. if let data = data {
  114. XCTAssertEqual(String(data: data, encoding: .utf8), expectedResponse)
  115. completionHandlerExpectation.fulfill()
  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(gRPCWebOKTrailers())
  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: defaultTimeout)
  141. }
  142. }