示例工程 20-async-await-structured-concurrency
20-async-await-structured-concurrency/Tests/Ch20KitTests/AsyncTests.swift
import Testing
@testable import Ch20Kit
@Suite("结构化并发")
struct FetchingTests {
let downloader = SimulatedDownloader(delay: .milliseconds(5))
@Test func serialPreservesOrder() async {
let results = await Fetching.serial([1, 2, 3], downloader: downloader)
#expect(results == ["item-1", "item-2", "item-3"])
}
@Test func concurrentReturnsAllResults() async {
let results = await Fetching.concurrent([1, 2, 3, 4], downloader: downloader)
#expect(results.sorted() == ["item-1", "item-2", "item-3", "item-4"])
}
@Test func concurrentMatchesSerialAsSet() async {
let serial = await Fetching.serial([1, 2, 3], downloader: downloader)
let concurrent = await Fetching.concurrent([1, 2, 3], downloader: downloader)
#expect(Set(serial) == Set(concurrent))
}
@Test func asyncLetCombinesBothResults() async {
let results = await Fetching.pair(downloader: downloader)
#expect(results.sorted() == ["item-1", "item-2"])
}
@Test func emptyInputReturnsEmptyResults() async {
let serial = await Fetching.serial([], downloader: downloader)
let concurrent = await Fetching.concurrent([], downloader: downloader)
#expect(serial.isEmpty)
#expect(concurrent.isEmpty)
}
}
@Suite("取消与返回值")
struct CancellationTests {
@Test func cancelledTaskStopsEarly() async {
let task = Task {
await CancellationLab.countUntilCancelled(limit: 1000)
}
try? await Task.sleep(for: .milliseconds(20))
task.cancel()
let count = await task.value
#expect(count < 1000)
#expect(count >= 0)
}
@Test func uncancelledTaskCompletes() async {
let count = await CancellationLab.countUntilCancelled(limit: 5)
#expect(count == 5)
}
@Test func asyncFunctionReturnsValue() async {
let sum = await CancellationLab.add(20, 22)
#expect(sum == 42)
}
}