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