XCTest+Utilities.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. import XCTest
  18. func XCTAssertThrowsError<T, E: Error>(
  19. ofType: E.Type,
  20. _ expression: @autoclosure () throws -> T,
  21. _ errorHandler: (E) -> Void
  22. ) {
  23. XCTAssertThrowsError(try expression()) { error in
  24. guard let error = error as? E else {
  25. return XCTFail("Error had unexpected type '\(type(of: error))'")
  26. }
  27. errorHandler(error)
  28. }
  29. }
  30. func XCTAssertDescription(
  31. _ subject: some CustomStringConvertible,
  32. _ expected: String,
  33. file: StaticString = #filePath,
  34. line: UInt = #line
  35. ) {
  36. XCTAssertEqual(String(describing: subject), expected, file: file, line: line)
  37. }
  38. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  39. func XCTUnwrapAsync<T>(_ expression: () async throws -> T?) async throws -> T {
  40. let value = try await expression()
  41. return try XCTUnwrap(value)
  42. }
  43. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  44. func XCTAssertThrowsErrorAsync<T, E: Error>(
  45. ofType: E.Type = E.self,
  46. _ expression: () async throws -> T,
  47. errorHandler: (E) -> Void
  48. ) async {
  49. do {
  50. _ = try await expression()
  51. XCTFail("Expression didn't throw")
  52. } catch let error as E {
  53. errorHandler(error)
  54. } catch {
  55. XCTFail("Error had unexpected type '\(type(of: error))'")
  56. }
  57. }
  58. func XCTAssert<T>(_ value: Any, as type: T.Type, _ verify: (T) throws -> Void) rethrows {
  59. if let value = value as? T {
  60. try verify(value)
  61. } else {
  62. XCTFail("\(value) couldn't be cast to \(T.self)")
  63. }
  64. }
  65. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  66. func XCTPoll(
  67. every interval: Duration,
  68. timeLimit: Duration = .seconds(5),
  69. until predicate: () async throws -> Bool
  70. ) async throws {
  71. let becameTrue = try await Task.poll(every: interval, timeLimit: timeLimit, until: predicate)
  72. XCTAssertTrue(becameTrue, "Predicate didn't return true within \(timeLimit)")
  73. }