Files
suixinkan_uikit/suixinkanTests/DroneDockCommandProgressTests.swift
lujiuyin 34ee60b8b2 完善机巢任务实时同步并开放双构建真实操作
订阅明确无缓存时使用新发起的有效 HTTP 全量响应衔接首包,保留任务、批次和版本校验。
移除 Debug/Release 的设备指令、图传和 RTC 构建拦截,保留后端权限、身份、防重复提交及结果未知保护。
更新开发约定并补充隔离传输、飞控状态和页面回归测试。

验证:iPhone 真机 500 项相关测试通过;iOS Release 无签名编译通过。
2026-11-05 10:59:26 +08:00

454 lines
26 KiB
Swift

import Foundation
import XCTest
@testable import suixinkan
/// 指令进度只更新对应按钮;所有请求、延迟和回执均由内存替身产生。
@MainActor
final class DroneDockCommandProgressTests: XCTestCase {
/// 第二个按钮立即进入等待,HTTP 串行发出,但无需等第一条设备指令确认。
func testIndependentButtonsQueueHTTPInOrderWithoutWaitingForDeviceConfirmation() async throws {
let fixture = try CommandProgressFixture()
defer { fixture.service.cancelAll() }
await fixture.model.refresh()
fixture.service.holdsCommands = true
let pause = Task { await fixture.model.sendCommand(.pause) }
try await wait { fixture.service.requests.count == 1 }
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
let returning = Task { await fixture.model.sendCommand(.returnHome) }
try await wait { fixture.model.isCommandLoading(.returnHome) }
XCTAssertEqual(fixture.service.requests.map(\.command), [.pause])
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
try fixture.service.resolve(0, changes: ["state_version": 2])
try await wait { fixture.service.requests.count == 2 }
XCTAssertEqual(fixture.service.requests.map(\.command), [.pause, .returnHome])
XCTAssertTrue(fixture.model.isCommandLoading(.pause), "第一条仍在等待设备确认,第二条已经可以提交")
try fixture.service.resolve(1, changes: ["state_version": 3])
await pause.value
await returning.value
XCTAssertEqual(fixture.service.maximumConcurrentCommands, 1)
XCTAssertEqual(Set(fixture.service.requests.map(\.clientRequestID)).count, 2)
XCTAssertFalse(fixture.model.isCommandLoading(.pause), "后受理的返航取代旧暂停意图")
XCTAssertTrue(fixture.model.isCommandLoading(.returnHome))
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.model.presentation.phase, .shooting, "受理回执不替代完整业务快照")
}
/// 排队期间已收到本批次回巢证据,尚未发出的暂停不能继续沿用点击时的飞行许可。
func testQueuedPauseIsNotSentAfterReturned() async throws {
let fixture = try CommandProgressFixture()
defer { fixture.service.cancelAll() }
await fixture.model.refresh()
fixture.service.holdsCommands = true
let returning = Task { await fixture.model.sendCommand(.returnHome) }
try await wait { fixture.service.requests.count == 1 }
let pause = Task { await fixture.model.sendCommand(.pause) }
try await wait { fixture.model.isCommandLoading(.pause) }
fixture.service.value = try DroneDockShootingTaskTestData.response(changes: [
"order_flight_task_id": 501, "execution_batch": 9001, "state_version": 3,
"task": ["id": 501, "status": 40, "result_code": "return_home"],
"order_flight_task": ["id": 501, "status": 40, "result_code": "return_home"],
"current_plane": ["id": 58, "sn_number": "LOCAL-PROGRESS-058", "work_status": 1],
"flight_control": DroneDockShootingTaskTestData.flightControl(state: "returned", batch: 9001,
canPause: false, canResume: false, canReturn: false, resumePhase: "returning",
returnReason: "manual", droneInDock: "inside", isAirborne: false),
"ui": ["phase": "failed_restartable"]])
XCTAssertEqual(fixture.model.applyTaskSnapshot(fixture.service.value), .applied)
try fixture.service.resolve(0)
await returning.value
await pause.value
XCTAssertEqual(fixture.service.requests.map(\.command), [.returnHome])
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertEqual(fixture.model.flightControlState, .returned)
}
/// 权限撤销后,队列中尚未发出的另一安全指令必须取消,不能继续使用旧快照权限。
func testQueuedCommandIsNotSentAfterAccessDenied() async throws {
let fixture = try CommandProgressFixture()
defer { fixture.service.cancelAll() }
await fixture.model.refresh()
fixture.service.holdsCommands = true
let pause = Task { await fixture.model.sendCommand(.pause) }
try await wait { fixture.service.requests.count == 1 }
let returning = Task { await fixture.model.sendCommand(.returnHome) }
try await wait { fixture.model.isCommandLoading(.returnHome) }
fixture.model.stopReading(message: "当前账号无权限操作该任务")
try fixture.service.resolve(0)
await pause.value
await returning.value
XCTAssertEqual(fixture.service.requests.map(\.command), [.pause])
XCTAssertFalse(fixture.model.isCommandLoading(.returnHome))
XCTAssertFalse(fixture.model.canSendCommand(.returnHome))
XCTAssertNotNil(fixture.model.readAccessError)
}
/// 回执已报告更高版本时,迟到的较低版本完整快照不能回退状态或确认按钮。
func testAcceptedReceiptVersionFloorRejectsOlderFullSnapshots() async throws {
let fixture = try CommandProgressFixture()
await fixture.model.refresh()
fixture.service.receiptChanges = ["state_version": 5]
await fixture.model.sendCommand(.pause)
let request = try XCTUnwrap(fixture.service.requests.first)
let old = try CommandProgressFixture.snapshot(version: 4, state: "paused",
progress: request.progress(status: "succeeded"))
XCTAssertEqual(fixture.model.applyTaskSnapshot(old), .outdated)
XCTAssertEqual(fixture.model.response?.stateVersion, 1)
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
XCTAssertEqual(fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 5,
progress: request.progress(status: "pending"))), .applied)
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
XCTAssertEqual(fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 6, state: "paused",
progress: request.progress(status: "succeeded"))), .applied)
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.resume))
}
/// succeeded、failed 和 superseded 都结束对应动画,不触发另一条设备指令。
func testMatchingTerminalProgressStopsOnlyItsButtonLoading() async throws {
for status in ["succeeded", "failed", "superseded"] {
let fixture = try CommandProgressFixture()
await fixture.model.refresh()
await fixture.model.sendCommand(.pause)
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
let request = try XCTUnwrap(fixture.service.requests.first)
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 3,
state: status == "succeeded" ? "paused" : "executing",
progress: request.progress(status: status)))
XCTAssertFalse(fixture.model.isCommandLoading(.pause), status)
XCTAssertFalse(fixture.model.isCommandLoading(.returnHome), status)
XCTAssertTrue(fixture.model.canSendCommand(.returnHome), status)
XCTAssertEqual(fixture.service.requests.count, 1)
if status == "failed" {
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertNotNil(fixture.model.commandErrorMessage(for: .pause))
XCTAssertNil(fixture.model.commandErrorMessage(for: .returnHome))
}
if status == "superseded" { XCTAssertTrue(fixture.model.canSendCommand(.pause)) }
}
}
/// 指令或请求标识不匹配的终态不能停止本按钮等待,普通新版本也不能冒充确认。
func testUnrelatedProgressCannotFinishCurrentOperation() async throws {
let fixture = try CommandProgressFixture()
await fixture.model.refresh()
await fixture.model.sendCommand(.pause)
let request = try XCTUnwrap(fixture.service.requests.first)
for (offset, changes) in [
["command_id": "another-command"],
["client_request_id": "another-request"],
["command": DroneDockSafetyCommand.returnHome.rawValue]
].enumerated() {
let unrelated = request.progress(status: "succeeded").merging(changes) { _, new in new }
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: offset + 3, progress: unrelated))
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
}
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 6, state: "paused",
progress: request.progress(status: "succeeded")))
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertEqual(fixture.service.requests.count, 1)
}
/// 缺省 pending 的设备确认回执可停动画,旧权限快照仍不能让同一按钮重复提交。
func testDeviceConfirmedStopsSpinnerButNeedsFreshStateBeforeSameActionCanRepeat() async throws {
let fixture = try CommandProgressFixture()
await fixture.model.refresh()
fixture.service.receiptChanges = ["pending_command": NSNull(), "device_confirmed": true, "state_version": 2]
await fixture.model.sendCommand(.pause)
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
await fixture.model.sendCommand(.pause)
XCTAssertEqual(fixture.service.requests.count, 1)
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 2, state: "paused"))
XCTAssertTrue(fixture.model.canSendCommand(.resume))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 3))
XCTAssertTrue(fixture.model.canSendCommand(.pause), "完整状态已经完成暂停和恢复后才允许新的暂停操作")
}
/// 恢复已确认先结束动画,随后同批次 executing 完整快照才清理暂停与恢复防重锁。
func testRecoverySucceededWaitsForExecutingSnapshotThenRestoresPausePermission() async throws {
let fixture = try CommandProgressFixture()
defer { fixture.service.cancelAll() }
fixture.service.value = try CommandProgressFixture.snapshot(state: "paused")
await fixture.model.refresh()
XCTAssertTrue(fixture.model.canSendCommand(.resume))
fixture.service.holdsCommands = true
let recovery = Task { await fixture.model.sendCommand(.resume) }
try await wait { fixture.service.requests.count == 1 }
let request = try XCTUnwrap(fixture.service.requests.first)
try fixture.service.resolve(0, changes: ["device_confirmed": true, "state_version": 2,
"pending_command": request.progress(status: "succeeded")])
await recovery.value
XCTAssertFalse(fixture.model.isCommandLoading(.resume))
XCTAssertEqual(fixture.model.presentation.phase, .paused)
XCTAssertFalse(fixture.model.canSendCommand(.resume), "设备确认回执不能让旧暂停快照再次发送恢复")
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 2, state: "paused",
progress: request.progress(status: "succeeded"))), .applied)
XCTAssertEqual(fixture.model.presentation.phase, .paused)
XCTAssertFalse(fixture.model.canSendCommand(.pause))
await fixture.model.sendCommand(.resume)
XCTAssertEqual(fixture.service.requests.count, 1)
XCTAssertEqual(fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 3,
progress: request.progress(status: "succeeded"))), .applied)
XCTAssertEqual(fixture.model.flightControlState, .executing)
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertFalse(fixture.model.canSendCommand(.resume))
XCTAssertFalse(fixture.model.isCommandLoading(.resume))
XCTAssertEqual(fixture.service.requests.map(\.command), [.resume])
}
/// 数据库错误使用整数业务码与空数组,真实 API 解码进入业务错误且不自动重发设备指令。
func testIntegerDatabaseFailurePreservesSnapshotWithoutDenyingAccessOrRetryingCommand() async throws {
let message = "任务状态处理失败,请稍后重试"
let data = try JSONSerialization.data(withJSONObject: ["code": 100050, "msg": message, "data": []] as [String: Any])
let session = MockURLSession(responses: [data])
let context = DroneDockShootingTaskTestData.context()
let service = CommandProgressService(value: try CommandProgressFixture.snapshot())
let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501,
order: DroneDockShootingTaskTestData.order(), service: service,
commandService: DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)),
currentContext: { context })
await model.refresh()
let previous = model.response
await model.sendCommand(.pause)
XCTAssertEqual(model.commandErrorMessage(for: .pause), message)
XCTAssertFalse(model.isCommandOutcomeUnknown(.pause), "100050 是明确业务错误,不是解析失败导致的未知结果")
XCTAssertFalse(model.isCommandLoading(.pause))
XCTAssertEqual(model.response, previous)
XCTAssertEqual(model.presentation.phase, .shooting)
XCTAssertNil(model.readAccessError)
XCTAssertTrue(model.canContinuePolling)
XCTAssertTrue(model.canSendCommand(.pause))
XCTAssertTrue(model.canSendCommand(.returnHome))
XCTAssertEqual(service.readCount, 1, "拒绝的写入不附加回查")
await model.refresh()
await model.refresh()
XCTAssertEqual(session.requests.count, 1, "只读核对不能自动重新发送设备指令")
XCTAssertEqual(session.requests.first?.url?.path, "/api/app/airport/command")
XCTAssertEqual(service.readCount, 3)
XCTAssertEqual(model.response, previous)
}
/// 重新进入时仅从服务器 pending 锁住对应动作,不显示中央受理阶段。
func testRemotePendingLocksOnlyMatchingButtonAndClearsOnExplicitFailure() async throws {
let fixture = try CommandProgressFixture()
let request = CommandProgressRequest(taskID: 501, command: .pause, clientRequestID: "remote-request", batch: 9001)
fixture.service.value = try CommandProgressFixture.snapshot(progress: request.progress(status: "pending"))
await fixture.model.refresh()
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 2,
progress: request.progress(status: "failed")))
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.service.requests.isEmpty)
}
/// 结果未知只锁住该动作;重复刷新不重发,另一安全按钮仍保留明确授权。
func testUnknownResultLocksOnlyItsActionWithoutAutomaticallyResending() async throws {
for error in [APIError.networkFailed("本地超时"), APIError.decodeFailed("本地错误回执")] {
let fixture = try CommandProgressFixture()
await fixture.model.refresh()
fixture.service.commandError = error
await fixture.model.sendCommand(.pause)
XCTAssertTrue(fixture.model.isCommandOutcomeUnknown(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertFalse(fixture.model.isCommandOutcomeUnknown(.returnHome))
XCTAssertNil(fixture.model.commandErrorMessage(for: .returnHome))
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
await fixture.model.refresh()
await fixture.model.sendCommand(.pause)
XCTAssertEqual(fixture.service.requests.count, 1)
}
}
/// 明确业务拒绝不是未知结果,同一按钮仅由再次点击触发重试。
func testKnownFailureStopsLoadingAndLeavesOtherActionUntouched() async throws {
for error: Error in [APIError.serverCode(100099, "模拟拒绝"), APIError.serverCode(100050, "服务暂不可用")] {
let fixture = try CommandProgressFixture()
await fixture.model.refresh()
fixture.service.commandError = error
await fixture.model.sendCommand(.pause)
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.isCommandOutcomeUnknown(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertNil(fixture.model.commandErrorMessage(for: .returnHome))
XCTAssertEqual(fixture.service.requests.count, 1)
XCTAssertEqual(fixture.service.readCount, 1)
}
}
/// 传输故意忽略取消,旧批次成功或失败均不能在新批次重建按钮等待或错误。
func testNewBatchRejectsLateOldReceiptAndFailure() async throws {
for succeeds in [true, false] {
let fixture = try CommandProgressFixture()
defer { fixture.service.cancelAll() }
await fixture.model.refresh()
fixture.service.holdsCommands = true
let operation = Task { await fixture.model.sendCommand(.pause) }
try await wait { fixture.service.requests.count == 1 }
fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(batch: 9002, state: "starting"))
if succeeds { try fixture.service.resolve(0) }
else { fixture.service.fail(0, error: APIError.networkFailed("迟到的旧批次失败")) }
await operation.value
XCTAssertEqual(fixture.model.response?.executionBatch, 9002)
XCTAssertEqual(fixture.model.presentation.phase, .navigating)
XCTAssertFalse(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.commandOutcomeUnknown)
XCTAssertNil(fixture.model.commandResponse)
XCTAssertNil(fixture.model.commandErrorMessage)
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.service.requests.count, 1)
}
}
/// 仅等待内存任务调度,不接触网络或设备。
private func wait(_ condition: () -> Bool) async throws {
for _ in 0..<200 {
if condition() { return }
try await Task.sleep(for: .milliseconds(10))
}
XCTFail("隔离指令任务未进入预期状态")
throw CommandProgressTestError.timedOut
}
}
/// 仅用于及时退出未完成的内存调度等待,避免测试继续挂起。
private enum CommandProgressTestError: Error { case timedOut }
/// 记录一个逻辑请求,服务端 ID 与客户端幂等键分别建模。
private struct CommandProgressRequest {
let taskID: Int
let command: DroneDockSafetyCommand
let clientRequestID: String
let batch: Int64
var commandID: String { "server-\(clientRequestID)" }
/// 构造 HTTP/WS 共用的同一条指令进度。
func progress(status: String) -> [String: Any] {
["command_id": commandID, "client_request_id": clientRequestID,
"command": command.rawValue, "status": status,
"message": status == "failed" ? "本地设备执行失败" : ""]
}
/// 合成受理回执,不将受理作为设备已经执行的证据。
func receipt(changes: [String: Any] = [:]) throws -> DroneDockCommandResponse {
let data: [String: Any] = [
"order_flight_task_id": taskID, "execution_batch": batch, "state_version": 2,
"plane_id": 58, "airport_sn": "LOCAL-PROGRESS-058",
"accepted": true, "device_confirmed": false, "command": command.rawValue,
"command_id": commandID, "client_request_id": clientRequestID,
"pending_command": progress(status: "pending")]
return try JSONDecoder().decode(DroneDockCommandResponse.self,
from: JSONSerialization.data(withJSONObject: data.merging(changes) { _, new in new }))
}
}
/// 当前任务与服务完整隔离,快照默认有已确认的飞行状态和两项安全许可。
@MainActor
private struct CommandProgressFixture {
let service: CommandProgressService
let model: DroneDockShootingTaskViewModel
/// 注入只读与指令内存替身,不提供任何真实传输能力。
init() throws {
service = CommandProgressService(value: try Self.snapshot())
let context = DroneDockShootingTaskTestData.context()
model = DroneDockShootingTaskViewModel(context: context, taskID: 501,
order: try DroneDockShootingTaskTestData.order(), service: service, commandService: service,
currentContext: { context })
}
/// 提供当前批次完整状态,进度放在合同规定的 flight_control.pending_command 下。
static func snapshot(version: Int = 1, batch: Int = 9001, state: String = "executing",
progress: [String: Any]? = nil) throws -> DroneDockShootingResponse {
let starting = state == "starting"
let paused = state == "paused"
return try DroneDockShootingTaskTestData.response(changes: [
"order_flight_task_id": 501, "execution_batch": batch, "state_version": version, "snapshot_kind": "full",
"task": ["id": 501, "status": 20], "order_flight_task": ["id": 501, "status": 20],
"current_plane": ["id": 58, "sn_number": "LOCAL-PROGRESS-058", "work_status": 2],
"flight_control": DroneDockShootingTaskTestData.flightControl(state: state, batch: batch,
canPause: !paused && !starting, canResume: paused, canReturn: true,
resumePhase: starting ? "going_to_spot" : "shooting",
droneInDock: starting ? "inside" : "outside", isAirborne: !starting,
pauseReason: paused ? "manual" : nil, pendingCommand: progress),
"ui": ["phase": starting ? "going_to_spot" : paused ? "manual_paused" : "shooting"],
"execute_gate": ["can_execute": false, "primary_action": "blocked"]])
}
}
/// 可挂起且故意忽略取消的指令服务,用于验证 FIFO 与迟到响应;从不转发网络。
@MainActor
private final class CommandProgressService: DroneDockShootingServing, DroneDockCommandSending {
var value: DroneDockShootingResponse
var holdsCommands = false
var receiptChanges: [String: Any] = [:]
var commandError: Error?
private(set) var requests: [CommandProgressRequest] = []
private(set) var readCount = 0
private(set) var maximumConcurrentCommands = 0
private var activeCommands = 0
private var continuations: [String: CheckedContinuation<DroneDockCommandResponse, Error>] = [:]
/// 使用显式内存快照初始化测试读取。
init(value: DroneDockShootingResponse) { self.value = value }
/// 只读返回同任务配置快照,实时采集参数必须关闭。
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
XCTAssertEqual(taskID, 501)
XCTAssertFalse(liveBattery)
readCount += 1
return value
}
/// 保存幂等请求并可选择挂起,允许测试控制回执顺序。
func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse {
let request = CommandProgressRequest(taskID: taskID, command: command,
clientRequestID: clientRequestID, batch: value.executionBatch ?? 9001)
requests.append(request)
activeCommands += 1
maximumConcurrentCommands = max(maximumConcurrentCommands, activeCommands)
defer { activeCommands -= 1 }
if holdsCommands {
return try await withCheckedThrowingContinuation { continuations[clientRequestID] = $0 }
}
if let commandError { throw commandError }
return try request.receipt(changes: receiptChanges)
}
/// 将指定请求完成为合成回执,保持同请求身份。
func resolve(_ index: Int, changes: [String: Any] = [:]) throws {
let request = requests[index]
let result = try request.receipt(changes: changes)
continuations.removeValue(forKey: request.clientRequestID)?.resume(returning: result)
}
/// 将指定请求完成为错误,即使其调用任务已经取消。
func fail(_ index: Int, error: Error) {
continuations.removeValue(forKey: requests[index].clientRequestID)?.resume(throwing: error)
}
/// 失败退出时释放所有测试 continuation,避免影响后续用例。
func cancelAll() {
let pending = Array(continuations.values)
continuations.removeAll()
for continuation in pending { continuation.resume(throwing: CancellationError()) }
}
}