2
0

XCTest+AsyncAwait.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2021, 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. #if compiler(>=5.5)
  17. import XCTest
  18. extension XCTestCase {
  19. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  20. /// Cross-platform XCTest support for async-await tests.
  21. ///
  22. /// Currently the Linux implementation of XCTest doesn't have async-await support.
  23. /// Until it does, we make use of this shim which uses a detached `Task` along with
  24. /// `XCTest.wait(for:timeout:)` to wrap the operation.
  25. ///
  26. /// - NOTE: Support for Linux is tracked by https://bugs.swift.org/browse/SR-14403.
  27. /// - NOTE: Implementation currently in progress: https://github.com/apple/swift-corelibs-xctest/pull/326
  28. func XCTAsyncTest(
  29. expectationDescription: String = "Async operation",
  30. timeout: TimeInterval = 30,
  31. file: StaticString = #filePath,
  32. line: UInt = #line,
  33. function: StaticString = #function,
  34. operation: @escaping () async throws -> Void
  35. ) {
  36. let expectation = self.expectation(description: expectationDescription)
  37. Task {
  38. do {
  39. try await operation()
  40. } catch {
  41. XCTFail("Error thrown while executing \(function): \(error)", file: file, line: line)
  42. Thread.callStackSymbols.forEach { print($0) }
  43. }
  44. expectation.fulfill()
  45. }
  46. self.wait(for: [expectation], timeout: timeout)
  47. }
  48. }
  49. @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
  50. internal func XCTAssertThrowsError<T>(
  51. _ expression: @autoclosure () async throws -> T,
  52. verify: (Error) -> Void = { _ in },
  53. file: StaticString = #file,
  54. line: UInt = #line
  55. ) async {
  56. do {
  57. _ = try await expression()
  58. XCTFail("Expression did not throw error", file: file, line: line)
  59. } catch {
  60. verify(error)
  61. }
  62. }
  63. #endif // compiler(>=5.5)