⏰ 一些时钟,使 Swift 并发更易于测试和更通用。
这个库是在 Point-Free 的剧集中设计的,Point-Free 是一个由 Brandon Williams 和 Stephen Celis 主持的探索 Swift 编程语言的视频系列。
您可以在这里观看所有剧集。
Swift 中的 Clock
协议为 Swift 结构化并发中的基于时间的异步操作提供了强大的抽象。仅使用一个 sleep
方法,您就可以表达许多强大的异步运算符,例如定时器、debounce
、throttle
、timeout
等(请参阅 swift-async-algorithms)。
然而,当您在异步代码中使用具体的时钟,或直接使用 Task.sleep
时,您会立即失去轻松测试和预览功能的能力,迫使您等待真实世界的时间流逝才能看到您的功能如何工作。
这个库提供了新的 Clock
一致性,使您可以将任何基于时间的异步代码转换为更易于测试和调试的东西
一个可以以确定性方式控制时间的时钟。
这个时钟对于测试时间流逝如何影响异步和并发代码非常有用。这包括任何使用 sleep
或任何基于时间的异步运算符的代码,例如 debounce
、throttle
、timeout
等。
例如,假设您有一个模型,该模型封装了一个可以启动和停止的定时器的行为,并且每次定时器滴答时,计数器值都会递增
@MainActor
class FeatureModel: ObservableObject {
@Published var count = 0
let clock: any Clock<Duration>
var timerTask: Task<Void, Error>?
init(clock: any Clock<Duration>) {
self.clock = clock
}
func startTimerButtonTapped() {
self.timerTask = Task {
while true {
try await self.clock.sleep(for: .seconds(1))
self.count += 1
}
}
}
func stopTimerButtonTapped() {
self.timerTask?.cancel()
self.timerTask = nil
}
}
请注意,我们已显式强制提供时钟以构建 FeatureModel
。这使得在设备或模拟器上运行时可以使用真实的时钟(例如 ContinuousClock
),并在测试中使用更可控的时钟(例如 TestClock
)。
为了为此功能编写测试,我们可以使用 TestClock
构建 FeatureModel
,然后向前推进时钟,并断言模型如何变化
func testTimer() async {
let clock = TestClock()
let model = FeatureModel(clock: clock)
XCTAssertEqual(model.count, 0)
model.startTimerButtonTapped()
// Advance the clock 1 second and prove that the model's
// count incremented by one.
await clock.advance(by: .seconds(1))
XCTAssertEqual(model.count, 1)
// Advance the clock 4 seconds and prove that the model's
// count incremented by 4.
await clock.advance(by: .seconds(4))
XCTAssertEqual(model.count, 5)
// Stop the timer, run the clock until there is no more
// suspensions, and prove that the count did not increment.
model.stopTimerButtonTapped()
await clock.run()
XCTAssertEqual(model.count, 5)
}
这个测试很容易编写,确定性地通过,并且只需不到一秒的时间即可运行。如果您要在功能中使用具体的时钟,则此类测试将很难编写。您将不得不等待真实时间流逝,从而减慢测试套件的速度,并且您将不得不格外小心,以允许基于时间的异步操作中固有的不精确性,以免出现不稳定的测试。
一个在睡眠时不会暂停的时钟。
这个时钟对于将所有时间压缩到一个瞬间非常有用,强制任何 sleep
立即执行。例如,假设您有一个功能需要在执行某些操作(例如显示欢迎消息)之前等待 5 秒钟
struct Feature: View {
@State var message: String?
var body: some View {
VStack {
if let message = self.message {
Text(self.message)
}
}
.task {
do {
try await Task.sleep(for: .seconds(5))
self.message = "Welcome!"
} catch {}
}
}
}
当前,这通过调用 Task.sleep
来使用真实的时钟,这意味着您对这个功能的样式和行为所做的每次更改都必须等待 5 秒的真实时间过去,才能看到效果。这将严重影响您在 Xcode 预览中快速迭代功能的能力。
解决方法是让您的视图持有时钟,以便可以从外部控制它
struct Feature: View {
@State var message: String?
let clock: any Clock<Duration>
var body: some View {
VStack {
if let message = self.message {
Text(self.message)
}
}
.task {
do {
try await self.clock.sleep(for: .seconds(5))
self.message = "Welcome!"
} catch {}
}
}
}
然后,您可以在设备或模拟器上运行时使用 ContinuousClock
构建此视图,并在 Xcode 预览中运行时使用 ImmediateClock
struct Feature_Previews: PreviewProvider {
static var previews: some View {
Feature(clock: ImmediateClock())
}
}
现在,每次对视图进行更改时,欢迎消息都会立即显示。无需等待 5 秒的真实世界时间过去。
您还可以通过库附带的 continuousClock
和 suspendingClock
环境变量将时钟传播到 SwiftUI 视图
struct Feature: View {
@State var message: String?
@Environment(\.continuousClock) var clock
var body: some View {
VStack {
if let message = self.message {
Text(self.message)
}
}
.task {
do {
try await self.clock.sleep(for: .seconds(5))
self.message = "Welcome!"
} catch {}
}
}
}
struct Feature_Previews: PreviewProvider {
static var previews: some View {
Feature()
.environment(\.continuousClock, ImmediateClock())
}
}
一个时钟,当调用其任何端点时,会导致 XCTest 失败。
当必须提供时钟依赖项以测试功能时,但您实际上并不希望在您正在执行的特定执行流程中使用时钟时,此时钟很有用。
例如,考虑以下模型,该模型封装了能够递增和递减计数以及启动和停止每秒递增计数器的定时器的行为
@MainActor
class FeatureModel: ObservableObject {
@Published var count = 0
let clock: any Clock<Duration>
var timerTask: Task<Void, Error>?
init(clock: some Clock<Duration>) {
self.clock = clock
}
func incrementButtonTapped() {
self.count += 1
}
func decrementButtonTapped() {
self.count -= 1
}
func startTimerButtonTapped() {
self.timerTask = Task {
for await _ in self.clock.timer(interval: .seconds(1)) {
self.count += 1
}
}
}
func stopTimerButtonTapped() {
self.timerTask?.cancel()
self.timerTask = nil
}
}
如果我们测试用户递增和递减计数的流程,则不需要时钟。我们不希望发生任何基于时间的异步操作。为了明确这一点,我们可以使用 UnimplementedClock
func testIncrementDecrement() {
let model = FeatureModel(clock: UnimplementedClock())
XCTAssertEqual(model.count, 0)
self.model.incrementButtonTapped()
XCTAssertEqual(model.count, 1)
self.model.decrementButtonTapped()
XCTAssertEqual(model.count, 0)
}
如果此测试通过,则明确证明在正在测试的用户流程中根本未使用时钟,从而使此测试更强大。如果将来,递增和递减端点开始使用基于时间的异步操作(使用时钟),我们将立即收到测试失败的通知。这将帮助我们找到应更新的测试,以断言功能中的新行为。
现在,所有时钟都带有一个方法,该方法允许您在持续时间指定的间隔上创建基于 AsyncSequence
的定时器。这使您可以使用简单的 for await
语法处理定时器,例如这个 observable 对象,它公开了启动和停止定时器以每秒递增值的能力
@MainActor
class FeatureModel: ObservableObject {
@Published var count = 0
let clock: any Clock<Duration>
var timerTask: Task<Void, Error>?
init(clock: any Clock<Duration>) {
self.clock = clock
}
func startTimerButtonTapped() {
self.timerTask = Task {
for await _ in self.clock.timer(interval: .seconds(1)) {
self.count += 1
}
}
}
func stopTimerButtonTapped() {
self.timerTask?.cancel()
self.timerTask = nil
}
}
通过使用上面讨论的 TestClock
也可以轻松测试此功能
func testTimer() async {
let clock = TestClock()
let model = FeatureModel(clock: clock)
XCTAssertEqual(model.count, 0)
model.startTimerButtonTapped()
await clock.advance(by: .seconds(1))
XCTAssertEqual(model.count, 1)
await clock.advance(by: .seconds(4))
XCTAssertEqual(model.count, 5)
model.stopTimerButtonTapped()
await clock.run()
}
any Clock
的具体版本。
此类型使可以将时钟存在类型传递给原本会禁止它的 API。
例如,Async Algorithms 包提供了许多接受时钟的 API,但由于 Swift 的限制,它们无法接受 any Clock
形式的时钟存在类型
class Model: ObservableObject {
let clock: any Clock<Duration>
init(clock: some Clock<Duration>) {
self.clock = clock
}
func task() async {
// 🛑 Type 'any Clock<Duration>' cannot conform to 'Clock'
for await _ in stream.debounce(for: .seconds(1), clock: self.clock) {
// ...
}
}
}
通过使用具体的 AnyClock
,我们可以绕过此限制
// ✅
for await _ in stream.debounce(for: .seconds(1), clock: AnyClock(self.clock)) {
// ...
}
此库的最新文档可在此处获取。
此库在 MIT 许可下发布。有关详细信息,请参阅 LICENSE。