ServerThrowingTests.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 = HTTPHeaders([("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. func get(request: Echo_EchoRequest,
  34. context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  35. return context.eventLoop.makeFailedFuture(thrownError)
  36. }
  37. func expand(
  38. request: Echo_EchoRequest,
  39. context: StreamingResponseCallContext<Echo_EchoResponse>
  40. ) -> EventLoopFuture<GRPCStatus> {
  41. return context.eventLoop.makeFailedFuture(thrownError)
  42. }
  43. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  44. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  45. return context.eventLoop.makeFailedFuture(thrownError)
  46. }
  47. func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  48. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  49. return context.eventLoop.makeFailedFuture(thrownError)
  50. }
  51. }
  52. extension EventLoop {
  53. func makeFailedFuture<T>(_ error: Error, delay: TimeInterval) -> EventLoopFuture<T> {
  54. return self.scheduleTask(in: .nanoseconds(Int64(delay * 1000 * 1000 * 1000))) { () }
  55. .futureResult
  56. .flatMapThrowing { _ -> T in throw error }
  57. }
  58. }
  59. /// See `ImmediateThrowingEchoProvider`.
  60. class DelayedThrowingEchoProvider: Echo_EchoProvider {
  61. func get(request: Echo_EchoRequest,
  62. context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  63. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  64. }
  65. func expand(
  66. request: Echo_EchoRequest,
  67. context: StreamingResponseCallContext<Echo_EchoResponse>
  68. ) -> EventLoopFuture<GRPCStatus> {
  69. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  70. }
  71. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  72. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  73. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  74. }
  75. func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  76. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  77. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  78. }
  79. }
  80. /// Ensures that fulfilling the status promise (where possible) with an error yields the same result as failing the future.
  81. class ErrorReturningEchoProvider: ImmediateThrowingEchoProvider {
  82. // There's no status promise to fulfill for unary calls (only the response promise), so that case is omitted.
  83. override func expand(
  84. request: Echo_EchoRequest,
  85. context: StreamingResponseCallContext<Echo_EchoResponse>
  86. ) -> EventLoopFuture<GRPCStatus> {
  87. return context.eventLoop.makeSucceededFuture(thrownError)
  88. }
  89. override func collect(context: UnaryResponseCallContext<Echo_EchoResponse>)
  90. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  91. return context.eventLoop.makeSucceededFuture({ _ in
  92. context.responseStatus = thrownError
  93. context.responsePromise.succeed(Echo_EchoResponse())
  94. })
  95. }
  96. override func update(context: StreamingResponseCallContext<Echo_EchoResponse>)
  97. -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  98. return context.eventLoop.makeSucceededFuture({ _ in
  99. context.statusPromise.succeed(thrownError)
  100. })
  101. }
  102. }
  103. private class ErrorTransformingDelegate: ServerErrorDelegate {
  104. func transformRequestHandlerError(_ error: Error,
  105. request: HTTPRequestHead) -> GRPCStatusAndMetadata? {
  106. return GRPCStatusAndMetadata(status: transformedError, metadata: transformedMetadata)
  107. }
  108. }
  109. class ServerThrowingTests: EchoTestCaseBase {
  110. var expectedError: GRPCStatus { return thrownError }
  111. var expectedMetadata: HPACKHeaders? {
  112. return HPACKHeaders([("grpc-status", "13"), ("grpc-message", "expected error")])
  113. }
  114. override func makeEchoProvider() -> Echo_EchoProvider { return ImmediateThrowingEchoProvider() }
  115. }
  116. class ServerDelayedThrowingTests: ServerThrowingTests {
  117. override func makeEchoProvider() -> Echo_EchoProvider { return DelayedThrowingEchoProvider() }
  118. }
  119. class ClientThrowingWhenServerReturningErrorTests: ServerThrowingTests {
  120. override func makeEchoProvider() -> Echo_EchoProvider { return ErrorReturningEchoProvider() }
  121. }
  122. class ServerErrorTransformingTests: ServerThrowingTests {
  123. override var expectedError: GRPCStatus { return transformedError }
  124. override var expectedMetadata: HPACKHeaders? {
  125. return HPACKHeaders([("grpc-status", "10"), ("grpc-message", "transformed error"),
  126. ("transformed", "header")])
  127. }
  128. override func makeErrorDelegate() -> ServerErrorDelegate? { return ErrorTransformingDelegate() }
  129. }
  130. extension ServerThrowingTests {
  131. func testUnary() throws {
  132. let call = client.get(Echo_EchoRequest(text: "foo"))
  133. XCTAssertEqual(self.expectedError, try call.status.wait())
  134. XCTAssertEqual(self.expectedMetadata, try call.trailingMetadata.wait())
  135. XCTAssertThrowsError(try call.response.wait()) {
  136. XCTAssertEqual(expectedError, $0 as? GRPCStatus)
  137. }
  138. }
  139. func testClientStreaming() throws {
  140. let call = client.collect()
  141. // This is racing with the server error; it might fail, it might not.
  142. try? call.sendEnd().wait()
  143. XCTAssertEqual(self.expectedError, try call.status.wait())
  144. XCTAssertEqual(self.expectedMetadata, try call.trailingMetadata.wait())
  145. if type(of: self.makeEchoProvider()) != ErrorReturningEchoProvider.self {
  146. // With `ErrorReturningEchoProvider` we actually _return_ a response, which means that the `response` future
  147. // will _not_ fail, so in that case this test doesn't apply.
  148. XCTAssertThrowsError(try call.response.wait()) {
  149. XCTAssertEqual(expectedError, $0 as? GRPCStatus)
  150. }
  151. }
  152. }
  153. func testServerStreaming() throws {
  154. let call = client
  155. .expand(Echo_EchoRequest(text: "foo")) { XCTFail("no message expected, got \($0)") }
  156. // Nothing to throw here, but the `status` should be the expected error.
  157. XCTAssertEqual(self.expectedError, try call.status.wait())
  158. XCTAssertEqual(self.expectedMetadata, try call.trailingMetadata.wait())
  159. }
  160. func testBidirectionalStreaming() throws {
  161. let call = client.update { XCTFail("no message expected, got \($0)") }
  162. // This is racing with the server error; it might fail, it might not.
  163. try? call.sendEnd().wait()
  164. // Nothing to throw here, but the `status` should be the expected error.
  165. XCTAssertEqual(self.expectedError, try call.status.wait())
  166. XCTAssertEqual(self.expectedMetadata, try call.trailingMetadata.wait())
  167. }
  168. }