GRPCStatusCodeTests.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /*
  2. * Copyright 2019, 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 EchoModel
  17. import Foundation
  18. import Logging
  19. import NIOCore
  20. import NIOEmbedded
  21. import NIOHPACK
  22. import NIOHTTP1
  23. import NIOHTTP2
  24. import XCTest
  25. @testable import GRPC
  26. class GRPCStatusCodeTests: GRPCTestCase {
  27. var channel: EmbeddedChannel!
  28. override func setUp() {
  29. super.setUp()
  30. let handler = GRPCClientChannelHandler(
  31. callType: .unary,
  32. maximumReceiveMessageLength: .max,
  33. logger: GRPCLogger(wrapping: self.logger)
  34. )
  35. self.channel = EmbeddedChannel(handler: handler)
  36. }
  37. func headersFramePayload(status: HTTPResponseStatus) -> HTTP2Frame.FramePayload {
  38. let headers: HPACKHeaders = [":status": "\(status.code)"]
  39. return .headers(.init(headers: headers))
  40. }
  41. func sendRequestHead() {
  42. let requestHead = _GRPCRequestHead(
  43. method: "POST",
  44. scheme: "http",
  45. path: "/foo/bar",
  46. host: "localhost",
  47. deadline: .distantFuture,
  48. customMetadata: [:],
  49. encoding: .disabled
  50. )
  51. let clientRequestHead: _RawGRPCClientRequestPart = .head(requestHead)
  52. XCTAssertNoThrow(try self.channel.writeOutbound(clientRequestHead))
  53. }
  54. func doTestResponseStatus(_ status: HTTPResponseStatus, expected: GRPCStatus.Code) throws {
  55. // Send the request head so we're in a valid state to receive headers.
  56. self.sendRequestHead()
  57. XCTAssertThrowsError(
  58. try self.channel
  59. .writeInbound(self.headersFramePayload(status: status))
  60. ) { error in
  61. guard let withContext = error as? GRPCError.WithContext,
  62. let invalidHTTPStatus = withContext.error as? GRPCError.InvalidHTTPStatus
  63. else {
  64. XCTFail("Unexpected error: \(error)")
  65. return
  66. }
  67. XCTAssertEqual(invalidHTTPStatus.makeGRPCStatus().code, expected)
  68. }
  69. }
  70. func testTooManyRequests() throws {
  71. try self.doTestResponseStatus(.tooManyRequests, expected: .unavailable)
  72. }
  73. func testBadGateway() throws {
  74. try self.doTestResponseStatus(.badGateway, expected: .unavailable)
  75. }
  76. func testServiceUnavailable() throws {
  77. try self.doTestResponseStatus(.serviceUnavailable, expected: .unavailable)
  78. }
  79. func testGatewayTimeout() throws {
  80. try self.doTestResponseStatus(.gatewayTimeout, expected: .unavailable)
  81. }
  82. func testBadRequest() throws {
  83. try self.doTestResponseStatus(.badRequest, expected: .internalError)
  84. }
  85. func testUnauthorized() throws {
  86. try self.doTestResponseStatus(.unauthorized, expected: .unauthenticated)
  87. }
  88. func testForbidden() throws {
  89. try self.doTestResponseStatus(.forbidden, expected: .permissionDenied)
  90. }
  91. func testNotFound() throws {
  92. try self.doTestResponseStatus(.notFound, expected: .unimplemented)
  93. }
  94. func testStatusCodeAndMessageAreRespectedForNon200Responses() throws {
  95. let status = GRPCStatus(code: .unknown, message: "Not the HTTP error phrase")
  96. let headers: HPACKHeaders = [
  97. ":status": "\(HTTPResponseStatus.imATeapot.code)",
  98. GRPCHeaderName.statusCode: "\(status.code.rawValue)",
  99. GRPCHeaderName.statusMessage: status.message!,
  100. ]
  101. self.sendRequestHead()
  102. let headerFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers))
  103. try self.channel.writeInbound(headerFramePayload)
  104. let responsePart1 = try XCTUnwrap(
  105. self.channel.readInbound(as: _GRPCClientResponsePart<ByteBuffer>.self)
  106. )
  107. switch responsePart1 {
  108. case .trailingMetadata:
  109. ()
  110. case .initialMetadata, .message, .status:
  111. XCTFail("Unexpected response part \(responsePart1)")
  112. }
  113. let responsePart2 = try XCTUnwrap(
  114. self.channel.readInbound(as: _GRPCClientResponsePart<ByteBuffer>.self)
  115. )
  116. switch responsePart2 {
  117. case .initialMetadata, .message, .trailingMetadata:
  118. XCTFail("Unexpected response part \(responsePart2)")
  119. case let .status(actual):
  120. XCTAssertEqual(actual.code, status.code)
  121. XCTAssertEqual(actual.message, status.message)
  122. }
  123. }
  124. func testNon200StatusCodesAreConverted() throws {
  125. let tests: [(Int, GRPCStatus.Code)] = [
  126. (400, .internalError),
  127. (401, .unauthenticated),
  128. (403, .permissionDenied),
  129. (404, .unimplemented),
  130. (429, .unavailable),
  131. (502, .unavailable),
  132. (503, .unavailable),
  133. (504, .unavailable),
  134. ]
  135. for (httpStatusCode, grpcStatusCode) in tests {
  136. let headers: HPACKHeaders = [":status": "\(httpStatusCode)"]
  137. self.setUp()
  138. self.sendRequestHead()
  139. let headerFramePayload = HTTP2Frame.FramePayload
  140. .headers(.init(headers: headers, endStream: true))
  141. try self.channel.writeInbound(headerFramePayload)
  142. let responsePart1 = try XCTUnwrap(
  143. self.channel.readInbound(as: _GRPCClientResponsePart<ByteBuffer>.self)
  144. )
  145. switch responsePart1 {
  146. case .trailingMetadata:
  147. ()
  148. case .initialMetadata, .message, .status:
  149. XCTFail("Unexpected response part \(responsePart1)")
  150. }
  151. let responsePart2 = try XCTUnwrap(
  152. self.channel.readInbound(as: _GRPCClientResponsePart<ByteBuffer>.self)
  153. )
  154. switch responsePart2 {
  155. case .initialMetadata, .message, .trailingMetadata:
  156. XCTFail("Unexpected response part \(responsePart2)")
  157. case let .status(actual):
  158. XCTAssertEqual(actual.code, grpcStatusCode)
  159. }
  160. }
  161. }
  162. func testCodeFromRawValue() {
  163. XCTAssertEqual(GRPCStatus.Code(rawValue: 0), .ok)
  164. XCTAssertEqual(GRPCStatus.Code(rawValue: 1), .cancelled)
  165. XCTAssertEqual(GRPCStatus.Code(rawValue: 2), .unknown)
  166. XCTAssertEqual(GRPCStatus.Code(rawValue: 3), .invalidArgument)
  167. XCTAssertEqual(GRPCStatus.Code(rawValue: 4), .deadlineExceeded)
  168. XCTAssertEqual(GRPCStatus.Code(rawValue: 5), .notFound)
  169. XCTAssertEqual(GRPCStatus.Code(rawValue: 6), .alreadyExists)
  170. XCTAssertEqual(GRPCStatus.Code(rawValue: 7), .permissionDenied)
  171. XCTAssertEqual(GRPCStatus.Code(rawValue: 8), .resourceExhausted)
  172. XCTAssertEqual(GRPCStatus.Code(rawValue: 9), .failedPrecondition)
  173. XCTAssertEqual(GRPCStatus.Code(rawValue: 10), .aborted)
  174. XCTAssertEqual(GRPCStatus.Code(rawValue: 11), .outOfRange)
  175. XCTAssertEqual(GRPCStatus.Code(rawValue: 12), .unimplemented)
  176. XCTAssertEqual(GRPCStatus.Code(rawValue: 13), .internalError)
  177. XCTAssertEqual(GRPCStatus.Code(rawValue: 14), .unavailable)
  178. XCTAssertEqual(GRPCStatus.Code(rawValue: 15), .dataLoss)
  179. XCTAssertEqual(GRPCStatus.Code(rawValue: 16), .unauthenticated)
  180. XCTAssertNil(GRPCStatus.Code(rawValue: -1))
  181. XCTAssertNil(GRPCStatus.Code(rawValue: 17))
  182. }
  183. }