Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created November 26, 2024 22:00
Show Gist options
  • Save jubishop/d4aa2af9bc3718aad125c34b8eb45eee to your computer and use it in GitHub Desktop.
Save jubishop/d4aa2af9bc3718aad125c34b8eb45eee to your computer and use it in GitHub Desktop.
Swift Asynchronous Testing
class Fulfillment {
var count: Int = 0
func callAsFunction(count: Int = 1) {
self.count += 1
}
}
func expectation(
_ comment: Comment,
timeout: TimeInterval = 0.1,
expectedCount: Int = 1,
_ body: (Fulfillment) async -> Void
) async {
let tries = Int(ceil(timeout / 0.01))
let fulfillment = Fulfillment()
for _ in 0..<tries {
_ = await body(fulfillment)
if fulfillment.count == expectedCount {
return
}
try! await Task.sleep(for: .seconds(0.01))
}
if fulfillment.count == 0 {
Issue.record("Fulfillment of: \"\(comment)\" never occurred")
} else {
Issue.record(
"""
Fulfillment of: \"\(comment)\" failed \
with count: \(fulfillment.count), \
expected: \(expectedCount)
"""
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment