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

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

505 lines
31 KiB
Swift

import XCTest
@testable import suixinkan
/// 新设备状态合同的隔离回归,覆盖拍摄结果与物理返航分离、批次和受理确认保护。
@MainActor
final class DroneDockFlightControlTests: XCTestCase {
/// 起飞准备仍在巢内,既不能当作未知,也不能冒充本批次已返航。
func testStartingInsideShowsTravelAndKeepsExplicitReturnPermission() async throws {
let fixture = try FlightControlFixture(state: "starting")
await fixture.model.refresh()
XCTAssertEqual(fixture.model.flightControlState, .starting)
XCTAssertEqual(fixture.model.presentation.phase, .navigating)
XCTAssertEqual(fixture.model.presentation.title, "无人机正在赶来")
XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, false)
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome), "合同允许起飞准备阶段取消本次出发")
XCTAssertFalse(fixture.model.canResummon)
XCTAssertFalse(fixture.model.canStartShooting)
XCTAssertFalse(fixture.model.isRecordingFinished)
XCTAssertNil(fixture.model.countdownRemainingSeconds)
}
/// 首点自动悬停保留待开拍和本地倒计时,原始 DJI paused 不等于用户紧急暂停。
func testArrivalWaitShowsReadyCountdownAndIndependentSafetyActions() async throws {
let fixture = try FlightControlFixture()
var control = DroneDockShootingTaskTestData.flightControl(batch: 9001,
resumePhase: "arrived_pending_start", pauseReason: "arrival_wait")
control["dji_task_status"] = "paused"
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start",
changes: ["flight_control": control])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.flightControlState, .executing)
XCTAssertEqual(fixture.model.presentation.phase, .ready)
XCTAssertEqual(fixture.model.presentation.title, "无人机已到达")
XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30)
XCTAssertTrue(fixture.model.canStartShooting)
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertFalse(fixture.model.canSendCommand(.resume))
XCTAssertTrue(fixture.service.commands.isEmpty)
XCTAssertEqual(fixture.service.startCount, 0)
}
/// 待开拍时手动暂停后继续只恢复等待,倒计时沿用本批次期限,不自动开拍。
func testManualPauseFromArrivalResumesReadyWithoutRestartingCountdownOrStartingShoot() async throws {
let clock = DroneDockCountdownTestClock()
let fixture = try FlightControlFixture(countdownNow: { clock.now() })
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start")
await fixture.model.refresh()
clock.advance(by: .seconds(12))
fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 2,
resumePhase: "arrived_pending_start"))
XCTAssertEqual(fixture.model.presentation.phase, .paused)
XCTAssertFalse(fixture.model.canStartShooting)
XCTAssertNil(fixture.model.countdownRemainingSeconds)
XCTAssertTrue(fixture.model.canSendCommand(.resume))
clock.advance(by: .seconds(5))
fixture.service.nextSnapshot = try FlightControlFixture.snapshot(state: "executing", version: 3,
phase: "arrived_pending_start")
await fixture.model.sendCommand(.resume)
XCTAssertEqual(fixture.service.commands, [.resume])
XCTAssertEqual(fixture.service.startCount, 0)
XCTAssertEqual(fixture.model.presentation.phase, .ready)
XCTAssertEqual(fixture.model.countdownRemainingSeconds, 13)
XCTAssertTrue(fixture.model.canStartShooting)
}
/// 起飞遥测三态仅供展示;执行、暂停和返航的安全操作均以明确 can_* 为准。
func testExplicitSafetyPermissionsAreIndependentOfAirborneTelemetry() async throws {
let states: [(String, Set<DroneDockSafetyCommand>)] = [
("executing", [.pause, .returnHome]), ("paused", [.resume, .returnHome]), ("returning", [.pause])]
for (state, allowed) in states {
for airborne: Bool? in [true, false, nil] {
let fixture = try FlightControlFixture()
let control = DroneDockShootingTaskTestData.flightControl(state: state, batch: 9001,
canPause: allowed.contains(.pause), canResume: allowed.contains(.resume),
canReturn: allowed.contains(.returnHome), resumePhase: "shooting",
droneInDock: "outside", isAirborne: airborne, pauseReason: state == "paused" ? "manual" : nil)
fixture.service.value = try FlightControlFixture.snapshot(state: state, changes: ["flight_control": control])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, airborne)
XCTAssertNotEqual(fixture.model.flightControlState, .unknown)
for command in DroneDockSafetyCommand.allCases {
XCTAssertEqual(fixture.model.canSendCommand(command), allowed.contains(command), "\(state): \(command)")
}
XCTAssertFalse(fixture.model.canResummon)
XCTAssertTrue(fixture.service.commands.isEmpty)
}
}
}
/// 有效遥测和已知飞行态都不能补造缺失或明确禁止的安全许可。
func testMissingOrFalseSafetyPermissionsRemainDeniedWithValidTelemetry() async throws {
for permission: Any in [NSNull(), false] {
let fixture = try FlightControlFixture()
var control = DroneDockShootingTaskTestData.flightControl(batch: 9001)
for field in ["can_pause", "can_resume", "can_return_home"] { control[field] = permission }
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", changes: ["flight_control": control])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, true)
XCTAssertTrue(fixture.model.availableSafetyCommands.isEmpty)
for command in DroneDockSafetyCommand.allCases { XCTAssertFalse(fixture.model.canSendCommand(command)) }
}
}
/// 业务失败或素材完成不代表飞机已落地,安全动作独立服从本批次飞控许可。
func testBusinessFailureAndCompletionDoNotBlockAuthorizedSafetyActions() async throws {
for (status, phase, wayline) in [(40, "failed_restartable", 91), (30, "completed", 50),
(25, "post_shoot_uploading", 30), (40, "post_shoot_upload_failed", 39)] {
let fixture = try FlightControlFixture()
let task: [String: Any] = ["id": 501, "status": status, "wayline_status": wayline]
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: phase,
changes: ["task": task, "order_flight_task": task])
await fixture.model.refresh()
XCTAssertTrue(fixture.model.canSendCommand(.pause), phase)
XCTAssertTrue(fixture.model.canSendCommand(.returnHome), phase)
XCTAssertFalse(fixture.model.canStartShooting)
XCTAssertFalse(fixture.model.canResummon)
}
}
/// 同批次读数缺失时保留最近指标并标记过期,新批次清空旧读数和旧控制态。
func testRetainedStaleMetricsStayWithinCurrentExecutionBatch() async throws {
let fixture = try FlightControlFixture()
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", changes: [
"metrics": [["key": "battery", "value": "76%"], ["key": "wind_speed", "value": "2m/s"]],
"metrics_stale": false])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.telemetry.batteryText, "76%")
XCTAssertFalse(fixture.model.isTelemetryStale)
fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 2,
changes: ["metrics": [], "metrics_stale": true]))
XCTAssertEqual(fixture.model.telemetry.batteryText, "76%")
XCTAssertEqual(fixture.model.telemetry.windText, "2m/s")
XCTAssertTrue(fixture.model.isTelemetryStale)
XCTAssertTrue(fixture.model.canSendCommand(.resume), "指标过期不覆盖独立飞控许可")
fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "starting", batch: 9002,
changes: ["metrics": [], "metrics_stale": true]))
XCTAssertEqual(fixture.model.telemetry.batteryText, "—")
XCTAssertEqual(fixture.model.telemetry.windText, "—")
XCTAssertEqual(fixture.model.presentation.phase, .navigating)
XCTAssertFalse(fixture.model.canSendCommand(.resume))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 99)), .outdated)
XCTAssertEqual(fixture.model.response?.executionBatch, 9002)
XCTAssertEqual(fixture.model.telemetry.batteryText, "—")
}
func testPausedUsesLocalCopyAndResumePermissionInsteadOfStartGateOrCommandLabels() async throws {
let fixture = try FlightControlFixture(state: "paused")
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, .paused)
XCTAssertEqual(fixture.model.presentation.title, "无人机已暂停")
XCTAssertEqual(fixture.model.presentation.actionTitle, "继续任务")
XCTAssertTrue(fixture.model.presentation.isActionEnabled)
XCTAssertFalse(fixture.model.canStartShooting)
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.resume))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
fixture.service.nextSnapshot = try FlightControlFixture.snapshot(state: "executing", version: 2)
await fixture.model.sendCommand(.resume)
XCTAssertEqual(fixture.service.commands, [.resume])
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
XCTAssertNil(fixture.model.pendingCommand)
}
func testMissingUnknownMismatchedAndContradictoryControlCannotEnableAnyDeviceAction() async throws {
let controls: [Any] = [NSNull(), [:], ["state": "future", "execution_batch": 9001],
["state": "executing", "execution_batch": 9002, "can_pause": true],
["state": "paused", "execution_batch": 9001, "resume_phase": "shooting", "drone_in_dock": "inside", "can_resume": true],
["state": "returned", "execution_batch": 9001, "drone_in_dock": "outside"],
["state": "returned", "execution_batch": 9001]]
for control in controls {
let fixture = try FlightControlFixture()
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start",
changes: ["flight_control": control, "execute_gate": ["can_execute": true, "primary_action": "start_shoot"],
"restart_gate": ["can_restart": true]])
await fixture.model.refresh()
for command in DroneDockSafetyCommand.allCases { XCTAssertFalse(fixture.model.canSendCommand(command)) }
XCTAssertFalse(fixture.model.canStartShooting)
XCTAssertFalse(fixture.model.canResummon)
}
}
func testManualReturnKeepsFailureResultAndRequiresInsideAndRestartGate() async throws {
let fixture = try FlightControlFixture(state: "returning", reason: "manual")
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, .returning)
XCTAssertEqual(fixture.model.presentation.title, "无人机正在返航")
XCTAssertEqual(fixture.model.presentation.actionTitle, "拍摄已中断")
XCTAssertFalse(fixture.model.presentation.isActionEnabled)
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.returnHome))
XCTAssertFalse(fixture.model.canResummon)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
for gate in [false, true] {
fixture.service.value = try FlightControlFixture.snapshot(state: "returned", reason: "manual", version: gate ? 3 : 2,
changes: ["restart_gate": ["can_restart": gate]])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, .returned)
XCTAssertEqual(fixture.model.response?.task?.status, 40)
XCTAssertEqual(fixture.model.canResummon, gate)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
XCTAssertTrue(fixture.model.availableSafetyCommands.isEmpty)
}
}
/// 手动返航可伴随航线下载态,仍是中断;回巢、机巢空闲和重召许可缺一不可。
func testManualReturnWithDownloadingWaylineWaitsForReturnedIdleAndRestartGate() async throws {
let fixture = try FlightControlFixture(state: "returning", reason: "manual")
let task: [String: Any] = ["id": 501, "status": 40, "wayline_status": 24,
"result_code": "return_home", "result_message": "立即返航中断任务"]
let stages: [(state: String, workStatus: Int, gate: Bool, code: String, mayRestart: Bool)] = [
("returning", 2, false, "await_returned", false),
("returned", 2, false, "await_dock_idle", false),
("returned", 1, false, "low_battery", false),
("returned", 2, true, "ok", false),
("returned", 1, true, "ok", true)
]
for (index, stage) in stages.enumerated() {
fixture.service.value = try FlightControlFixture.snapshot(state: stage.state, reason: "manual", version: index + 1,
phase: stage.state == "returned" ? "failed_restartable" : "returning_home", changes: [
"task": task, "order_flight_task": task, "shoot_complete_returning": false,
"current_plane": ["id": 58, "sn_number": "LOCAL-FLIGHT-058", "work_status": stage.workStatus, "online_status": 1],
"restart_gate": ["can_restart": stage.gate, "code": stage.code]
])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, stage.state == "returned" ? .returned : .returning)
XCTAssertEqual(fixture.model.response?.orderFlightTask?.status, 40)
XCTAssertEqual(fixture.model.response?.task?.waylineStatus, 24)
XCTAssertEqual(fixture.model.response?.orderFlightTask?.resultCode, "return_home")
XCTAssertFalse(fixture.model.isRecordingFinished)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
XCTAssertFalse(fixture.model.isShootCompleteReturning)
XCTAssertEqual(fixture.model.shouldStopLiveReception, stage.state == "returned")
XCTAssertEqual(fixture.model.canResummon, stage.mayRestart, stage.code)
}
XCTAssertEqual(fixture.model.presentation.action, .retry)
XCTAssertTrue(fixture.model.presentation.isActionEnabled)
XCTAssertTrue(fixture.service.commands.isEmpty)
XCTAssertEqual(fixture.service.startCount, 0)
}
func testIdleAndFailureCannotProveReturnEvenIfBackendRestartGateIsTrue() async throws {
for state in ["returning", "unknown"] {
let fixture = try FlightControlFixture(state: state, reason: "manual")
fixture.service.value = try FlightControlFixture.snapshot(state: state, reason: "manual",
changes: ["restart_gate": ["can_restart": true]])
await fixture.model.refresh()
XCTAssertFalse(fixture.model.canResummon)
XCTAssertNotEqual(fixture.model.presentation.phase, .returned)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
}
}
func testPausedReturnResumesReturningAndNeverStartsShooting() async throws {
let fixture = try FlightControlFixture(state: "paused", reason: "manual")
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, .paused)
XCTAssertTrue(fixture.model.presentation.message.contains("恢复返航"))
XCTAssertTrue(fixture.model.canSendCommand(.resume))
XCTAssertFalse(fixture.model.canSendCommand(.returnHome))
fixture.service.nextSnapshot = try FlightControlFixture.snapshot(state: "returning", reason: "manual", version: 2)
await fixture.model.sendCommand(.resume)
XCTAssertEqual(fixture.service.commands, [.resume])
XCTAssertEqual(fixture.service.startCount, 0)
XCTAssertEqual(fixture.model.presentation.phase, .returning)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
}
func testNormalRecordingCompletionStaysDistinctFromInterruptedReturnIncludingPausedReturn() async throws {
for state in ["returning", "returned", "unknown", "paused"] {
let fixture = try FlightControlFixture(state: state, reason: "normal_complete")
await fixture.model.refresh()
XCTAssertEqual(fixture.model.response?.task?.status, 25)
XCTAssertTrue(fixture.model.isRecordingFinished)
XCTAssertEqual(fixture.model.presentation.phase, state == "paused" ? .paused : .postShootUploading)
XCTAssertFalse(fixture.model.canResummon)
if state == "paused" { XCTAssertTrue(fixture.model.canSendCommand(.resume)) }
}
}
/// 未知业务枚举不能开放开拍,也不能抹掉独立且可信的安全控制权限。
func testUnknownBusinessStatusKeepsAuthorizedSafetyActionsWithoutEnablingStart() async throws {
let fixture = try FlightControlFixture()
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start", changes: [
"task": ["id": 501, "status": 99], "order_flight_task": ["id": 501, "status": 99]])
await fixture.model.refresh()
XCTAssertTrue(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertFalse(fixture.model.canSendCommand(.resume))
XCTAssertFalse(fixture.model.canSendCommand(.cancelReturn))
XCTAssertFalse(fixture.model.canStartShooting)
}
/// 身份和版本是所有控制的前提,已知业务状态额外约束开拍而非安全指令。
func testStartRequiresResponseIdentityAndVersionWithKnownTaskState() async throws {
let cases: [(changes: [String: Any], canReturn: Bool)] = [
(["order_flight_task_id": NSNull(), "task": ["status": 20], "order_flight_task": ["status": 20]], false),
(["state_version": NSNull()], false),
(["task": ["id": 501, "status": 99], "order_flight_task": ["id": 501, "status": 99]], true)
]
for (changes, canReturn) in cases {
let fixture = try FlightControlFixture()
let gates: [String: Any] = ["execute_gate": ["can_execute": true, "primary_action": "start_shoot"]]
fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start",
changes: gates.merging(changes) { _, new in new })
await fixture.model.refresh()
XCTAssertFalse(fixture.model.canStartShooting)
XCTAssertEqual(fixture.model.canSendCommand(.returnHome), canReturn)
}
}
func testAcceptedReceiptWaitsForNewMatchingFullSnapshot() async throws {
let fixture = try FlightControlFixture()
await fixture.model.refresh()
fixture.service.receiptChanges = ["device_confirmed": false, "state_version": 3]
await fixture.model.sendCommand(.pause)
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
XCTAssertEqual(fixture.model.presentation.title, "无人机正在拍摄中")
XCTAssertTrue(fixture.model.isCommandLoading(.pause))
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertTrue(fixture.model.canSendCommand(.returnHome))
XCTAssertEqual(fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 1)), .outdated)
XCTAssertNotNil(fixture.model.pendingCommand)
XCTAssertEqual(fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 2)), .outdated)
XCTAssertNotNil(fixture.model.pendingCommand, "不能早于指令回执对应版本")
fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "unknown", version: 3))
XCTAssertNotNil(fixture.model.pendingCommand, "新版本本身不是执行确认")
fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 4))
XCTAssertNil(fixture.model.pendingCommand)
XCTAssertEqual(fixture.model.presentation.phase, .paused)
XCTAssertTrue(fixture.model.canSendCommand(.resume))
}
func testFullSnapshotArrivingBeforeReceiptCanConfirmSameOperation() async throws {
let fixture = try FlightControlFixture()
await fixture.model.refresh()
fixture.service.onCommand = {
fixture.model.applyTaskSnapshot(try! FlightControlFixture.snapshot(state: "paused", version: 2))
}
fixture.service.receiptChanges = ["state_version": 2]
await fixture.model.sendCommand(.pause)
XCTAssertNil(fixture.model.pendingCommand)
XCTAssertEqual(fixture.model.presentation.phase, .paused)
}
func testWrongReceiptIdentityOrMissingAcceptanceKeepsUnknownOutcomeLock() async throws {
for changes: [String: Any] in [
["execution_batch": 9002], ["plane_id": 99], ["airport_sn": "OTHER"], ["accepted": NSNull()],
["flight_control": ["execution_batch": 9002]]
] {
let fixture = try FlightControlFixture()
await fixture.model.refresh()
fixture.service.receiptChanges = changes
await fixture.model.sendCommand(.pause)
XCTAssertTrue(fixture.model.commandOutcomeUnknown)
XCTAssertFalse(fixture.model.canSendCommand(.pause))
XCTAssertNil(fixture.model.commandResponse)
}
}
func testExplicitRejectedReceiptAllowsUserRetryWithoutPretendingAccepted() async throws {
let fixture = try FlightControlFixture()
await fixture.model.refresh()
fixture.service.receiptChanges = ["accepted": false]
await fixture.model.sendCommand(.pause)
XCTAssertFalse(fixture.model.commandOutcomeUnknown)
XCTAssertNil(fixture.model.pendingCommand)
XCTAssertEqual(fixture.model.presentation.phase, .shooting)
XCTAssertTrue(fixture.model.canSendCommand(.pause))
}
func testNewBatchDiscardsPendingCommandAndLateOldReceipt() async throws {
let fixture = try FlightControlFixture()
await fixture.model.refresh()
fixture.service.onCommand = {
fixture.model.applyTaskSnapshot(try! FlightControlFixture.snapshot(state: "executing", batch: 9002))
}
await fixture.model.sendCommand(.pause)
XCTAssertNil(fixture.model.pendingCommand)
XCTAssertNil(fixture.model.commandResponse)
XCTAssertFalse(fixture.model.commandOutcomeUnknown)
XCTAssertEqual(fixture.model.response?.executionBatch, 9002)
XCTAssertTrue(fixture.model.canSendCommand(.pause))
}
func testNewBatchIgnoresLateFailureOfOldCommand() async throws {
let fixture = try FlightControlFixture()
await fixture.model.refresh()
fixture.service.commandError = APIError.networkFailed("旧批次指令网络失败")
fixture.service.onCommand = {
fixture.model.applyTaskSnapshot(try! FlightControlFixture.snapshot(state: "executing", batch: 9002))
}
await fixture.model.sendCommand(.pause)
XCTAssertNil(fixture.model.pendingCommand)
XCTAssertFalse(fixture.model.commandOutcomeUnknown)
XCTAssertEqual(fixture.model.response?.executionBatch, 9002)
XCTAssertTrue(fixture.model.canSendCommand(.pause))
}
func testConflictingReturnResultCannotDeclareCompletionOrEnableResummon() async throws {
let fixture = try FlightControlFixture()
let task: [String: Any] = ["id": 501, "status": 40, "result_code": "return_home"]
fixture.service.value = try FlightControlFixture.snapshot(state: "returned", reason: "normal_complete",
changes: ["task": task, "order_flight_task": task])
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, .unknown)
XCTAssertFalse(fixture.model.canResummon)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
XCTAssertFalse(fixture.model.isRecordingFinished)
}
func testAbnormalReturnNeverUsesStaleCompletionPhaseToStopLive() async throws {
let fixture = try FlightControlFixture(state: "returning", reason: "abnormal")
fixture.service.value = try FlightControlFixture.snapshot(state: "returning", reason: "abnormal", phase: "post_shoot_uploading")
await fixture.model.refresh()
XCTAssertEqual(fixture.model.presentation.phase, .returning)
XCTAssertFalse(fixture.model.isRecordingFinished)
XCTAssertFalse(fixture.model.shouldStopLiveReception)
XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion)
}
}
/// 每份匿名快照明确区分设备飞行态与拍摄结果,所有操作只在内存记录。
@MainActor
private struct FlightControlFixture {
let service: FlightControlService
let model: DroneDockShootingTaskViewModel
init(state: String = "executing", reason: String? = nil,
countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now }) throws {
service = FlightControlService(value: try Self.snapshot(state: state, reason: reason))
let context = DroneDockShootingTaskTestData.context()
model = DroneDockShootingTaskViewModel(context: context, taskID: 501, order: try DroneDockShootingTaskTestData.order(),
service: service, startService: service, commandService: service, resummonService: service,
countdownNow: countdownNow, currentContext: { context })
}
static func snapshot(state: String, reason: String? = nil, version: Int = 1, batch: Int = 9001,
phase: String? = nil, resumePhase: String? = nil,
changes: [String: Any] = [:]) throws -> DroneDockShootingResponse {
let interrupted = reason == "manual" || reason == "abnormal"
let normal = reason == "normal_complete"
let status = interrupted ? 40 : normal ? 25 : 20
let businessPhase = phase ?? (state == "starting" ? "going_to_spot" : state == "paused" ? "manual_paused"
: normal ? "post_shoot_uploading" : interrupted ? "returning_home" : "shooting")
let resume = resumePhase ?? (reason != nil ? "returning" : businessPhase == "arrived_pending_start" ? "arrived_pending_start"
: state == "starting" ? "going_to_spot" : "shooting")
let control = DroneDockShootingTaskTestData.flightControl(state: state, batch: batch,
canPause: state == "executing" || state == "returning", canResume: state == "paused",
canReturn: state == "starting" || state == "executing" || (state == "paused" && resume != "returning"),
resumePhase: resume, returnReason: reason,
droneInDock: state == "unknown" ? nil : state == "returned" || state == "starting" ? "inside" : "outside",
isAirborne: state == "unknown" ? nil : state != "returned" && state != "starting",
pauseReason: state == "paused" ? "manual" : businessPhase == "arrived_pending_start" ? "arrival_wait" : nil)
let task: [String: Any] = ["id": 501, "status": status, "wayline_status": normal ? 24 : interrupted ? 91 : 20,
"result_code": interrupted ? "return_home" : ""]
let value: [String: Any] = [
"order_flight_task_id": 501, "execution_batch": batch, "state_version": version, "snapshot_kind": "full",
"task": task, "order_flight_task": task,
"current_plane": ["id": 58, "sn_number": "LOCAL-FLIGHT-058", "work_status": 1, "online_status": 1],
"restart_gate": ["can_restart": true],
"execute_gate": ["can_execute": businessPhase == "arrived_pending_start",
"primary_action": businessPhase == "arrived_pending_start" ? "start_shoot" : "blocked"],
"ui": ["phase": businessPhase,
"title": "错误接口标题", "message": "错误接口提示", "commands": [["command": "return_home_cancel"]]],
"flight_control": control]
return try DroneDockShootingTaskTestData.decode(value.merging(changes) { _, new in new })
}
}
/// 不访问网络的同任务读取、控制和重召唤替身。
@MainActor
private final class FlightControlService: DroneDockShootingServing, DroneDockCommandSending, DroneDockStartShooting, DroneDockResummonServing {
var value: DroneDockShootingResponse
var nextSnapshot: DroneDockShootingResponse?
var receiptChanges: [String: Any] = [:]
var onCommand: (() -> Void)?
var commandError: Error?
var commands: [DroneDockSafetyCommand] = []
var startCount = 0
init(value: DroneDockShootingResponse) { self.value = value }
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { value }
func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse {
commands.append(command)
let batch = value.executionBatch ?? 9001
onCommand?()
if let commandError { throw commandError }
if let nextSnapshot { value = nextSnapshot }
let receipt: [String: Any] = ["order_flight_task_id": taskID, "command": command.rawValue,
"execution_batch": batch, "accepted": true, "device_confirmed": false,
"command_id": "local-flight-\(clientRequestID)", "client_request_id": clientRequestID,
"plane_id": 58, "airport_sn": "LOCAL-FLIGHT-058"]
return try JSONDecoder().decode(DroneDockCommandResponse.self,
from: JSONSerialization.data(withJSONObject: receipt.merging(receiptChanges) { _, new in new }))
}
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse {
startCount += 1
throw APIError.networkFailed("本地测试不应触发开拍")
}
func resummon(taskID: Int) async throws -> DroneDockShootResponse { throw APIError.networkFailed("本地测试不触发重召唤") }
}