ServerThrowingTests.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 Dispatch
  17. import EchoModel
  18. import Foundation
  19. @testable import GRPC
  20. import NIO
  21. import NIOHPACK
  22. import NIOHTTP1
  23. import NIOHTTP2
  24. import XCTest
  25. let thrownError = GRPCStatus(code: .internalError, message: "expected error")
  26. let transformedError = GRPCStatus(code: .aborted, message: "transformed error")
  27. let transformedMetadata = HPACKHeaders([("transformed", "header")])
  28. // Motivation for two different providers: Throwing immediately causes the event observer future (in the
  29. // client-streaming and bidi-streaming cases) to throw immediately, _before_ the corresponding handler has even added
  30. // to the channel. We want to test that case as well as the one where we throw only _after_ the handler has been added
  31. // to the channel.
  32. class ImmediateThrowingEchoProvider: Echo_EchoProvider {
  33. var interceptors: Echo_EchoServerInterceptorFactoryProtocol? { return nil }
  34. func get(request: Echo_EchoRequest,
  35. context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  36. return context.eventLoop.makeFailedFuture(thrownError)
  37. }
  38. func expand(
  39. request: Echo_EchoRequest,
  40. context: StreamingResponseCallContext<Echo_EchoResponse>
  41. ) -> EventLoopFuture<GRPCStatus> {
  42. return context.eventLoop.makeFailedFuture(thrownError)
  43. }
  44. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  45. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  46. return context.eventLoop.makeFailedFuture(thrownError)
  47. }
  48. func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  49. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  50. return context.eventLoop.makeFailedFuture(thrownError)
  51. }
  52. }
  53. extension EventLoop {
  54. func makeFailedFuture<T>(_ error: Error, delay: TimeInterval) -> EventLoopFuture<T> {
  55. return self.scheduleTask(in: .nanoseconds(Int64(delay * 1000 * 1000 * 1000))) { () }
  56. .futureResult
  57. .flatMapThrowing { _ -> T in throw error }
  58. }
  59. }
  60. /// See `ImmediateThrowingEchoProvider`.
  61. class DelayedThrowingEchoProvider: Echo_EchoProvider {
  62. let interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil
  63. func get(request: Echo_EchoRequest,
  64. context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  65. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  66. }
  67. func expand(
  68. request: Echo_EchoRequest,
  69. context: StreamingResponseCallContext<Echo_EchoResponse>
  70. ) -> EventLoopFuture<GRPCStatus> {
  71. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  72. }
  73. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  74. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  75. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  76. }
  77. func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  78. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  79. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  80. }
  81. }
  82. /// Ensures that fulfilling the status promise (where possible) with an error yields the same result as failing the future.
  83. class ErrorReturningEchoProvider: ImmediateThrowingEchoProvider {
  84. // There's no status promise to fulfill for unary calls (only the response promise), so that case is omitted.
  85. override func expand(
  86. request: Echo_EchoRequest,
  87. context: StreamingResponseCallContext<Echo_EchoResponse>
  88. ) -> EventLoopFuture<GRPCStatus> {
  89. return context.eventLoop.makeSucceededFuture(thrownError)
  90. }
  91. override func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  92. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  93. return context.eventLoop.makeSucceededFuture({ _ in
  94. context.responseStatus = thrownError
  95. context.responsePromise.succeed(Echo_EchoResponse())
  96. })
  97. }
  98. override func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  99. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  100. return context.eventLoop.makeSucceededFuture({ _ in
  101. context.statusPromise.succeed(thrownError)
  102. })
  103. }
  104. }
  105. private class ErrorTransformingDelegate: ServerErrorDelegate {
  106. func transformRequestHandlerError(_ error: Error,
  107. headers: HPACKHeaders) -> GRPCStatusAndTrailers? {
  108. return GRPCStatusAndTrailers(status: transformedError, trailers: transformedMetadata)
  109. }
  110. }
  111. class ServerThrowingTests: EchoTestCaseBase {
  112. var expectedError: GRPCStatus { return thrownError }
  113. var expectedMetadata: HPACKHeaders? {
  114. return HPACKHeaders([("grpc-status", "13"), ("grpc-message", "expected error")])
  115. }
  116. override func makeEchoProvider() -> Echo_EchoProvider { return ImmediateThrowingEchoProvider() }
  117. }
  118. class ServerDelayedThrowingTests: ServerThrowingTests {
  119. override func makeEchoProvider() -> Echo_EchoProvider { return DelayedThrowingEchoProvider() }
  120. }
  121. class ClientThrowingWhenServerReturningErrorTests: ServerThrowingTests {
  122. override func makeEchoProvider() -> Echo_EchoProvider { return ErrorReturningEchoProvider() }
  123. }
  124. class ServerErrorTransformingTests: ServerThrowingTests {
  125. override var expectedError: GRPCStatus { return transformedError }
  126. override var expectedMetadata: HPACKHeaders? {
  127. return HPACKHeaders([("grpc-status", "10"), ("grpc-message", "transformed error"),
  128. ("transformed", "header")])
  129. }
  130. override func makeErrorDelegate() -> ServerErrorDelegate? { return ErrorTransformingDelegate() }
  131. }
  132. extension ServerThrowingTests {
  133. func testUnary() throws {
  134. let call = client.get(Echo_EchoRequest(text: "foo"))
  135. XCTAssertEqual(self.expectedError, try call.status.wait())
  136. let trailers = try call.trailingMetadata.wait()
  137. if let expected = self.expectedMetadata {
  138. for (name, value, _) in expected {
  139. XCTAssertTrue(trailers[name].contains(value))
  140. }
  141. }
  142. XCTAssertThrowsError(try call.response.wait()) {
  143. XCTAssertEqual(expectedError, $0 as? GRPCStatus)
  144. }
  145. }
  146. func testClientStreaming() throws {
  147. let call = client.collect()
  148. // This is racing with the server error; it might fail, it might not.
  149. try? call.sendEnd().wait()
  150. XCTAssertEqual(self.expectedError, try call.status.wait())
  151. let trailers = try call.trailingMetadata.wait()
  152. if let expected = self.expectedMetadata {
  153. for (name, value, _) in expected {
  154. XCTAssertTrue(trailers[name].contains(value))
  155. }
  156. }
  157. if type(of: self.makeEchoProvider()) != ErrorReturningEchoProvider.self {
  158. // With `ErrorReturningEchoProvider` we actually _return_ a response, which means that the `response` future
  159. // will _not_ fail, so in that case this test doesn't apply.
  160. XCTAssertThrowsError(try call.response.wait()) {
  161. XCTAssertEqual(expectedError, $0 as? GRPCStatus)
  162. }
  163. }
  164. }
  165. func testServerStreaming() throws {
  166. let call = client
  167. .expand(Echo_EchoRequest(text: "foo")) { XCTFail("no message expected, got \($0)") }
  168. // Nothing to throw here, but the `status` should be the expected error.
  169. XCTAssertEqual(self.expectedError, try call.status.wait())
  170. let trailers = try call.trailingMetadata.wait()
  171. if let expected = self.expectedMetadata {
  172. for (name, value, _) in expected {
  173. XCTAssertTrue(trailers[name].contains(value))
  174. }
  175. }
  176. }
  177. func testBidirectionalStreaming() throws {
  178. let call = client.update { XCTFail("no message expected, got \($0)") }
  179. // This is racing with the server error; it might fail, it might not.
  180. try? call.sendEnd().wait()
  181. // Nothing to throw here, but the `status` should be the expected error.
  182. XCTAssertEqual(self.expectedError, try call.status.wait())
  183. let trailers = try call.trailingMetadata.wait()
  184. if let expected = self.expectedMetadata {
  185. for (name, value, _) in expected {
  186. XCTAssertTrue(trailers[name].contains(value))
  187. }
  188. }
  189. }
  190. }