Result+CatchingTests.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 2023, 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 XCTest
  17. @testable import GRPCCore
  18. final class ResultCatchingTests: XCTestCase {
  19. func testResultCatching() async {
  20. let result = await Result {
  21. try? await Task.sleep(nanoseconds: 1)
  22. throw RPCError(code: .unknown, message: "foo")
  23. }
  24. switch result {
  25. case .success:
  26. XCTFail()
  27. case .failure(let error):
  28. XCTAssertEqual(error as? RPCError, RPCError(code: .unknown, message: "foo"))
  29. }
  30. }
  31. func testCastToErrorOfCorrectType() async {
  32. let result = Result<Void, any Error>.failure(RPCError(code: .unknown, message: "foo"))
  33. let typedFailure = result.castError(to: RPCError.self) { _ in
  34. XCTFail("buildError(_:) was called")
  35. return RPCError(code: .failedPrecondition, message: "shouldn't happen")
  36. }
  37. switch typedFailure {
  38. case .success:
  39. XCTFail()
  40. case .failure(let error):
  41. XCTAssertEqual(error, RPCError(code: .unknown, message: "foo"))
  42. }
  43. }
  44. func testCastToErrorOfIncorrectType() async {
  45. struct WrongError: Error {}
  46. let result = Result<Void, any Error>.failure(WrongError())
  47. let typedFailure = result.castError(to: RPCError.self) { _ in
  48. return RPCError(code: .invalidArgument, message: "fallback")
  49. }
  50. switch typedFailure {
  51. case .success:
  52. XCTFail()
  53. case .failure(let error):
  54. XCTAssertEqual(error, RPCError(code: .invalidArgument, message: "fallback"))
  55. }
  56. }
  57. }