Repository Public License
1import Foundation23/// Thrown by `waitUntil` when the condition did not become true in time.4public struct WaitTimeout: Error, CustomStringConvertible {5 public let what: String6 public let seconds: Double7 public var description: String { "Timed out after \(seconds)s waiting for: \(what)" }8}910/// Polls `condition` on the main actor until it is true. Suspending between polls returns control to the main11/// run loop, which is what delivers WebKit delegate callbacks and KVO notifications during a test.12@MainActor13public func waitUntil(_ what: String, timeout: Double = 10, pollMilliseconds: Int = 15,14 _ condition: @MainActor () -> Bool) async throws {15 let deadline = Date().addingTimeInterval(timeout)16 while !condition() {17 if Date() > deadline { throw WaitTimeout(what: what, seconds: timeout) }18 try await Task.sleep(for: .milliseconds(pollMilliseconds))19 }20}2122/// Same as `waitUntil`, for conditions that must themselves await (script evaluation, actor state).23@MainActor24public func waitUntilAsync(_ what: String, timeout: Double = 10, pollMilliseconds: Int = 25,25 _ condition: @MainActor () async -> Bool) async throws {26 let deadline = Date().addingTimeInterval(timeout)27 while !(await condition()) {28 if Date() > deadline { throw WaitTimeout(what: what, seconds: timeout) }29 try await Task.sleep(for: .milliseconds(pollMilliseconds))30 }31}3233/// Lets the main run loop turn for a fixed time; for asserting that something did *not* happen.34@MainActor35public func settle(milliseconds: Int = 250) async {36 try? await Task.sleep(for: .milliseconds(milliseconds))37}3839/// A directory under the system temporary folder, removed by `remove()`.40public struct TemporaryDirectory: Sendable {41 public let url: URL4243 public init(prefix: String = "orix-test") throws {44 url = FileManager.default.temporaryDirectory45 .appendingPathComponent("\(prefix)-\(UUID().uuidString)", isDirectory: true)46 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)47 }4849 public func remove() { try? FileManager.default.removeItem(at: url) }50}51