ServerThrowingTests.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. @testable import GRPC
  22. import XCTest
  23. let thrownError = GRPCStatus(code: .internalError, message: "expected error")
  24. let transformedError = GRPCStatus(code: .aborted, message: "transformed error")
  25. func assertEqualStatusIgnoringTrailers(_ status: GRPCStatus, _ otherStatus: GRPCStatus?) {
  26. guard let otherStatus = otherStatus else {
  27. XCTFail("status was nil")
  28. return
  29. }
  30. XCTAssertEqual(status.code, otherStatus.code)
  31. XCTAssertEqual(status.message, otherStatus.message)
  32. }
  33. // Motivation for two different providers: Throwing immediately causes the event observer future (in the
  34. // client-streaming and bidi-streaming cases) to throw immediately, _before_ the corresponding handler has even added
  35. // to the channel. We want to test that case as well as the one where we throw only _after_ the handler has been added
  36. // to the channel.
  37. class ImmediateThrowingEchoProvider: Echo_EchoProvider {
  38. func get(request: Echo_EchoRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  39. return context.eventLoop.makeFailedFuture(thrownError)
  40. }
  41. func expand(request: Echo_EchoRequest, context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<GRPCStatus> {
  42. return context.eventLoop.makeFailedFuture(thrownError)
  43. }
  44. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  45. return context.eventLoop.makeFailedFuture(thrownError)
  46. }
  47. func update(context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  48. return context.eventLoop.makeFailedFuture(thrownError)
  49. }
  50. }
  51. extension EventLoop {
  52. func makeFailedFuture<T>(_ error: Error, delay: TimeInterval) -> EventLoopFuture<T> {
  53. return self.scheduleTask(in: .nanoseconds(TimeAmount.Value(delay * 1000 * 1000 * 1000))) { () }.futureResult
  54. .flatMapThrowing { _ -> T in throw error }
  55. }
  56. }
  57. /// See `ImmediateThrowingEchoProvider`.
  58. class DelayedThrowingEchoProvider: Echo_EchoProvider {
  59. func get(request: Echo_EchoRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Echo_EchoResponse> {
  60. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  61. }
  62. func expand(request: Echo_EchoRequest, context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<GRPCStatus> {
  63. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  64. }
  65. func collect(context: UnaryResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  66. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  67. }
  68. func update(context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  69. return context.eventLoop.makeFailedFuture(thrownError, delay: 0.01)
  70. }
  71. }
  72. /// Ensures that fulfilling the status promise (where possible) with an error yields the same result as failing the future.
  73. class ErrorReturningEchoProvider: ImmediateThrowingEchoProvider {
  74. // There's no status promise to fulfill for unary calls (only the response promise), so that case is omitted.
  75. override func expand(request: Echo_EchoRequest, context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<GRPCStatus> {
  76. return context.eventLoop.makeSucceededFuture(thrownError)
  77. }
  78. override func collect(context: UnaryResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  79. return context.eventLoop.makeSucceededFuture({ _ in
  80. context.responseStatus = thrownError
  81. context.responsePromise.succeed(Echo_EchoResponse())
  82. })
  83. }
  84. override func update(context: StreamingResponseCallContext<Echo_EchoResponse>) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  85. return context.eventLoop.makeSucceededFuture({ _ in
  86. context.statusPromise.succeed(thrownError)
  87. })
  88. }
  89. }
  90. private class ErrorTransformingDelegate: ServerErrorDelegate {
  91. func transformRequestHandlerError(_ error: Error, request: HTTPRequestHead) -> GRPCStatus? { return transformedError }
  92. }
  93. class ServerThrowingTests: EchoTestCaseBase {
  94. var expectedError: GRPCStatus { return thrownError }
  95. override func makeEchoProvider() -> Echo_EchoProvider { return ImmediateThrowingEchoProvider() }
  96. }
  97. class ServerDelayedThrowingTests: ServerThrowingTests {
  98. override func makeEchoProvider() -> Echo_EchoProvider { return DelayedThrowingEchoProvider() }
  99. }
  100. class ClientThrowingWhenServerReturningErrorTests: ServerThrowingTests {
  101. override func makeEchoProvider() -> Echo_EchoProvider { return ErrorReturningEchoProvider() }
  102. }
  103. class ServerErrorTransformingTests: ServerThrowingTests {
  104. override var expectedError: GRPCStatus { return transformedError }
  105. override func makeErrorDelegate() -> ServerErrorDelegate? { return ErrorTransformingDelegate() }
  106. }
  107. extension ServerThrowingTests {
  108. func testUnary() throws {
  109. let call = client.get(Echo_EchoRequest(text: "foo"))
  110. assertEqualStatusIgnoringTrailers(expectedError, try call.status.wait())
  111. XCTAssertThrowsError(try call.response.wait()) {
  112. assertEqualStatusIgnoringTrailers(expectedError, $0 as? GRPCStatus)
  113. }
  114. }
  115. func testClientStreaming() throws {
  116. let call = client.collect()
  117. XCTAssertNoThrow(try call.sendEnd().wait())
  118. assertEqualStatusIgnoringTrailers(expectedError, try call.status.wait())
  119. if type(of: makeEchoProvider()) != ErrorReturningEchoProvider.self {
  120. // With `ErrorReturningEchoProvider` we actually _return_ a response, which means that the `response` future
  121. // will _not_ fail, so in that case this test doesn't apply.
  122. XCTAssertThrowsError(try call.response.wait()) {
  123. assertEqualStatusIgnoringTrailers(expectedError, $0 as? GRPCStatus)
  124. }
  125. }
  126. }
  127. func testServerStreaming() throws {
  128. let call = client.expand(Echo_EchoRequest(text: "foo")) { XCTFail("no message expected, got \($0)") }
  129. // Nothing to throw here, but the `status` should be the expected error.
  130. assertEqualStatusIgnoringTrailers(expectedError, try call.status.wait())
  131. }
  132. func testBidirectionalStreaming() throws {
  133. let call = client.update() { XCTFail("no message expected, got \($0)") }
  134. XCTAssertNoThrow(try call.sendEnd().wait())
  135. // Nothing to throw here, but the `status` should be the expected error.
  136. assertEqualStatusIgnoringTrailers(expectedError, try call.status.wait())
  137. }
  138. }