Created
November 26, 2024 22:00
-
-
Save jubishop/d4aa2af9bc3718aad125c34b8eb45eee to your computer and use it in GitHub Desktop.
Swift Asynchronous Testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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