Result+CatchingTests.swift 2.0 KB

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