import Foundation import XCTest @testable import suixinkan /// 安全控制仅通过隔离服务验证请求、单次回查及重复操作保护,不连接后端或设备。 @MainActor final class DroneDockCommandViewModelTests: XCTestCase { /// 正式页默认不注入控制服务,即使快照提供指令也不可发送。 func testDefaultReadonlyModelCannotSendCommands() async throws { let fixture = try CommandTaskFixture(allowCommands: false) await fixture.model.refresh() for command in DroneDockSafetyCommand.allCases { XCTAssertFalse(fixture.model.canSendCommand(command)) await fixture.model.sendCommand(command) } XCTAssertTrue(fixture.write.requests.isEmpty) } /// 新版权限来自 flight_control,旧指令列表的顺序和文案不改变本地安全动作。 func testFlightControlPermissionsDoNotUseStartGateOrLegacyCommands() async throws { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(commands: ["unknown_command", "return_home", "flighttask_pause", "flighttask_pause"])) await fixture.model.refresh() XCTAssertEqual(Set(fixture.model.availableSafetyCommands), Set([.returnHome, .pause])) XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, false) XCTAssertTrue(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) XCTAssertFalse(fixture.model.canSendCommand(.resume)) await fixture.model.sendCommand(.resume) XCTAssertTrue(fixture.write.requests.isEmpty) } /// 缺少明确任务身份、锁定飞机或当前指令时,不将其它状态字段推导为许可。 func testIncompleteSnapshotCannotSendCommands() async throws { for snapshot in [ try CommandTaskData.snapshot(includeFlightControl: false), try CommandTaskData.snapshot(lockedPlane: false), try CommandTaskData.snapshot(includeTaskIdentity: false) ] { let fixture = try CommandTaskFixture() fixture.read.result = .success(snapshot) await fixture.model.refresh() XCTAssertFalse(fixture.model.canSendCommand(.pause)) await fixture.model.sendCommand(.pause) XCTAssertTrue(fixture.write.requests.isEmpty) } } /// 接受回执时仍保留旧画面,只按随后同任务读取结果切换阶段,不轮询。 func testSuccessRetainsSnapshotUntilSingleSameTaskRead() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() let previous = fixture.model.response let paused = try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 2) fixture.write.onRequest = { fixture.read.result = .success(paused) } var observedReceiptBeforeRefresh = false await fixture.model.sendCommand(.pause) { if fixture.model.commandResponse != nil && fixture.model.response == previous { observedReceiptBeforeRefresh = true XCTAssertTrue(fixture.model.isCommandLoading(.pause)) XCTAssertFalse(fixture.model.isSendingCommand) XCTAssertFalse(fixture.model.presentation.isActionEnabled) } } XCTAssertTrue(observedReceiptBeforeRefresh) XCTAssertEqual(fixture.write.requests.map(\.taskID), [501]) XCTAssertEqual(fixture.write.requests.map(\.command), [.pause]) XCTAssertEqual(fixture.read.requests, [501, 501]) XCTAssertEqual(fixture.model.response, paused) XCTAssertEqual(fixture.model.presentation.phase, .paused) XCTAssertNotNil(fixture.model.commandResponse?.dataJSON) XCTAssertFalse(fixture.model.isSendingCommand) XCTAssertNil(fixture.model.activeCommand) XCTAssertTrue(fixture.model.canSendCommand(.resume)) XCTAssertFalse(fixture.model.canSendCommand(.pause)) } /// 回查仍返回旧指令时,不重复提交已受理的同一指令。 func testAcceptedCommandCannotRepeatFromStaleSnapshot() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() await fixture.model.sendCommand(.pause) XCTAssertFalse(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) fixture.model.invalidate(preservingSnapshot: true) await fixture.model.refresh() await fixture.model.sendCommand(.pause) XCTAssertEqual(fixture.write.requests.count, 1) XCTAssertFalse(fixture.model.commandOutcomeUnknown) } /// 暂停等待确认仅锁住暂停,仍可提交后端允许的返航,且不覆盖中央业务阶段。 func testAcceptedPauseDoesNotBlockIndependentReturnCommand() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() await fixture.model.sendCommand(.pause) XCTAssertFalse(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) XCTAssertEqual(fixture.model.presentation.phase, .shooting) await fixture.model.sendCommand(.returnHome) XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) await fixture.model.sendCommand(.returnHome) XCTAssertEqual(fixture.write.requests.map(\.command), [.pause, .returnHome]) XCTAssertEqual(Set(fixture.write.requests.map(\.clientRequestID)).count, 2) XCTAssertEqual(fixture.model.presentation.phase, .shooting) } /// 暂停、恢复再暂停使用新的权限快照,可按用户操作继续调试同一任务。 func testPauseResumeCycleAcceptsFreshCommandAvailability() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 2)) await fixture.model.sendCommand(.pause) fixture.read.result = .success(try CommandTaskData.snapshot(version: 3)) await fixture.model.sendCommand(.resume) fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 4)) await fixture.model.sendCommand(.pause) XCTAssertEqual(fixture.write.requests.map(\.command), [.pause, .resume, .pause]) XCTAssertEqual(fixture.read.requests, [501, 501, 501, 501]) XCTAssertEqual(fixture.model.presentation.phase, .paused) } /// 明确业务拒绝保留旧状态,只在再次点击时重试。 func testBusinessRejectionAllowsExplicitRetryWithoutRead() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() let previous = fixture.model.response fixture.write.result = .failure(APIError.serverCode(100099, "模拟设备拒绝暂停")) await fixture.model.sendCommand(.pause) XCTAssertEqual(fixture.write.requests.count, 1) XCTAssertEqual(fixture.read.requests.count, 1) XCTAssertEqual(fixture.model.response, previous) XCTAssertEqual(fixture.model.commandErrorMessage, "模拟设备拒绝暂停") XCTAssertFalse(fixture.model.commandOutcomeUnknown) XCTAssertTrue(fixture.model.canSendCommand(.pause)) fixture.write.result = nil await fixture.model.sendCommand(.pause) XCTAssertEqual(fixture.write.requests.count, 2) XCTAssertNil(fixture.model.commandErrorMessage) XCTAssertNotNil(fixture.model.commandResponse) } /// 网络或解析失败仅锁定结果未知的动作及开拍,另一安全动作仍可依据可信权限执行。 func testUnknownOutcomeLocksSameCommandAndStartAcrossRefresh() async throws { for error in [APIError.networkFailed("模拟超时"), APIError.httpStatus(500, "模拟异常"), APIError.decodeFailed("模拟回执无法解析")] { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) await fixture.model.refresh() XCTAssertTrue(fixture.model.canStartShooting) let previous = fixture.model.response fixture.write.result = .failure(error) await fixture.model.sendCommand(.pause) XCTAssertTrue(fixture.model.commandOutcomeUnknown) XCTAssertFalse(fixture.model.canStartShooting) XCTAssertEqual(fixture.model.response, previous) XCTAssertEqual(fixture.model.presentation.phase, .ready) XCTAssertFalse(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) fixture.model.invalidate(preservingSnapshot: true) await fixture.model.refresh() await fixture.model.sendCommand(.pause) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) await fixture.model.startShooting() XCTAssertEqual(fixture.write.requests.count, 1) XCTAssertTrue(fixture.start.requests.isEmpty) } } /// 后端明确拒绝不误判为结果未知,刷新和页面离开均不自动重发。 func testBusinessRejectionIsNotAnUnknownRemoteOutcome() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() fixture.write.result = .failure(APIError.serverCode(100050, "服务暂不可用,请稍后重试")) await fixture.model.sendCommand(.pause) fixture.model.invalidate(preservingSnapshot: true) XCTAssertFalse(fixture.model.commandOutcomeUnknown) XCTAssertEqual(fixture.model.commandErrorMessage, "服务暂不可用,请稍后重试") XCTAssertNil(fixture.model.commandResponse) XCTAssertEqual(fixture.read.requests.count, 1) } /// 指令在途时拒绝同按钮连点与开拍,但不无条件禁用另一安全按钮。 func testPendingCommandRejectsDoubleTapAndStartWithoutBlockingReturn() async throws { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) await fixture.model.refresh() let previous = fixture.model.response fixture.write.suspend = true let sent = expectation(description: "指令进入隔离服务") fixture.write.onRequest = { sent.fulfill() } let pending = Task { await fixture.model.sendCommand(.pause) } await fulfillment(of: [sent], timeout: 2) XCTAssertTrue(fixture.model.isSendingCommand) XCTAssertEqual(fixture.model.response, previous) await fixture.model.sendCommand(.pause) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) await fixture.model.startShooting() XCTAssertEqual(fixture.write.requests.count, 1) XCTAssertTrue(fixture.start.requests.isEmpty) XCTAssertEqual(fixture.read.requests.count, 1) fixture.write.finish() await pending.value XCTAssertEqual(fixture.read.requests.count, 2) } /// 开拍在途时底部指令也保持互斥,不产生第二条控制请求。 func testPendingStartRejectsCommands() async throws { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) await fixture.model.refresh() fixture.start.suspend = true let sent = expectation(description: "开拍进入隔离服务") fixture.start.onRequest = { sent.fulfill() } let pending = Task { await fixture.model.startShooting() } await fulfillment(of: [sent], timeout: 2) XCTAssertFalse(fixture.model.canSendCommand(.pause)) await fixture.model.sendCommand(.pause) XCTAssertTrue(fixture.write.requests.isEmpty) fixture.start.finish() await pending.value } /// 取消、离页后的迟到成功不能回填,也不能触发新的 shooting 读取。 func testCancelledOrInvalidatedRequestIgnoresLateReceipt() async throws { for leavePage in [false, true] { let fixture = try CommandTaskFixture() await fixture.model.refresh() let previous = fixture.model.response fixture.write.suspend = true let sent = expectation(description: "指令等待取消") fixture.write.onRequest = { sent.fulfill() } let pending = Task { await fixture.model.sendCommand(.pause) } await fulfillment(of: [sent], timeout: 2) if leavePage { fixture.model.invalidate(preservingSnapshot: true) } else { pending.cancel() } fixture.write.finish() await pending.value XCTAssertTrue(fixture.model.commandOutcomeUnknown) XCTAssertNil(fixture.model.commandResponse) XCTAssertEqual(fixture.model.response, previous) XCTAssertEqual(fixture.read.requests.count, 1) XCTAssertFalse(fixture.model.isSendingCommand) XCTAssertNil(fixture.model.activeCommand) await fixture.model.sendCommand(.pause) XCTAssertEqual(fixture.write.requests.count, 1) } } /// 点击前身份变化不发送;在途身份变化则撤下旧任务及回执。 func testIdentityChangeBeforeOrDuringCommandClearsSnapshot() async throws { let before = try CommandTaskFixture() await before.model.refresh() before.scope.scenicID = 999 await before.model.sendCommand(.pause) XCTAssertTrue(before.write.requests.isEmpty) XCTAssertNil(before.model.response) let during = try CommandTaskFixture() await during.model.refresh() during.write.suspend = true let sent = expectation(description: "指令等待身份变化") during.write.onRequest = { sent.fulfill() } let pending = Task { await during.model.sendCommand(.pause) } await fulfillment(of: [sent], timeout: 2) during.scope.scenicID = 999 during.write.finish() await pending.value XCTAssertNil(during.model.response) XCTAssertNil(during.model.commandResponse) XCTAssertNil(during.model.commandErrorMessage) XCTAssertFalse(during.model.canSendCommand(.pause)) XCTAssertEqual(during.read.requests.count, 1) } /// 即使替身绕过 API 校验,任务或回显指令错误也不能接受为成功。 func testMismatchedReceiptLocksOutcomeWithoutFollowupRead() async throws { for receipt in [try CommandTaskData.receipt(command: .pause, taskID: 999), try CommandTaskData.receipt(command: .returnHome)] { let fixture = try CommandTaskFixture() await fixture.model.refresh() fixture.write.result = .success(receipt) await fixture.model.sendCommand(.pause) XCTAssertTrue(fixture.model.commandOutcomeUnknown) XCTAssertNil(fixture.model.commandResponse) XCTAssertEqual(fixture.read.requests.count, 1) } } /// 新版返航权限不会借旧 commands 开放取消返航,拍摄中断不能自动恢复。 func testReturningDoesNotPermitLegacyCancelReturnCommand() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "returning", commands: ["return_home_cancel"], taskStatus: 40, version: 2)) await fixture.model.sendCommand(.returnHome) XCTAssertEqual(fixture.model.presentation.phase, .returning) XCTAssertFalse(fixture.model.canSendCommand(.cancelReturn)) XCTAssertFalse(fixture.model.canSendCommand(.resume)) await fixture.model.sendCommand(.cancelReturn) XCTAssertEqual(fixture.write.requests.map(\.command), [.returnHome]) XCTAssertEqual(fixture.model.presentation.phase, .returning) XCTAssertFalse(fixture.model.canStartShooting) XCTAssertEqual(fixture.model.availableSafetyCommands, [.pause]) } /// 已接受后读取失败保留旧快照与本动作等待,另一安全动作仍使用已确认的许可。 func testAcceptedCommandWithFailedReadKeepsSnapshotAndReceipt() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() let previous = fixture.model.response fixture.read.result = .failure(APIError.networkFailed("模拟回查失败")) await fixture.model.sendCommand(.pause) XCTAssertNotNil(fixture.model.commandResponse) XCTAssertEqual(fixture.model.response, previous) XCTAssertFalse(fixture.model.commandOutcomeUnknown) XCTAssertFalse(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 2)) await fixture.model.refresh() XCTAssertTrue(fixture.model.canSendCommand(.resume)) } /// 调用前已经取消的任务不能进入指令服务。 func testCancellationBeforeSubmissionSendsNothing() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() let pending = Task { await fixture.model.sendCommand(.pause) } pending.cancel() await pending.value XCTAssertTrue(fixture.write.requests.isEmpty) XCTAssertFalse(fixture.model.commandOutcomeUnknown) } } /// 隔离账号、读取、开拍及安全控制依赖,共用匿名任务身份。 @MainActor private struct CommandTaskFixture { let scope: CommandTaskScope let read: CommandTaskReadService let write: CommandTaskWriteService let start: CommandTaskStartService let model: DroneDockShootingTaskViewModel init(allowCommands: Bool = true) throws { scope = CommandTaskScope() read = CommandTaskReadService(result: .success(try CommandTaskData.snapshot())) write = CommandTaskWriteService() start = CommandTaskStartService() let boundScope = scope model = DroneDockShootingTaskViewModel(context: boundScope.value, taskID: 501, order: try DroneDockShootingTaskTestData.order(), service: read, startService: start, commandService: allowCommands ? write : nil, currentContext: { boundScope.value }) } } /// 显式切换景区,不改动共享登录状态。 @MainActor private final class CommandTaskScope { var scenicID = 128 var value: DroneDockHomeContext { DroneDockShootingTaskTestData.context(scenicID: scenicID) } } /// 只返回配置的内存快照,记录回查次数。 @MainActor private final class CommandTaskReadService: DroneDockShootingServing { var result: Result private(set) var requests: [Int] = [] init(result: Result) { self.result = result } func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { requests.append(taskID) return try result.get() } } /// 支持挂起和错误注入的安全控制替身,不具有联网能力。 @MainActor private final class CommandTaskWriteService: DroneDockCommandSending { var result: Result? var onRequest: (() -> Void)? var suspend = false private(set) var requests: [(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String)] = [] private var continuation: CheckedContinuation? func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { requests.append((taskID, command, clientRequestID)) onRequest?() if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } return try result?.get() ?? CommandTaskData.receipt(command: command, clientRequestID: clientRequestID) } func finish() { let receipt = result ?? Result { try CommandTaskData.receipt(command: requests.last?.command ?? .pause, clientRequestID: requests.last?.clientRequestID) } continuation?.resume(with: receipt) continuation = nil } } /// 仅用于确认开拍与安全控制互斥的内存替身。 @MainActor private final class CommandTaskStartService: DroneDockStartShooting { var onRequest: (() -> Void)? var suspend = false private(set) var requests: [Int] = [] private var continuation: CheckedContinuation? func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { requests.append(taskID) onRequest?() if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } return try CommandTaskData.startReceipt() } func finish() { continuation?.resume(with: Result { try CommandTaskData.startReceipt() }) continuation = nil } } /// 按接口合同构造的合成数据,不表示真实设备状态或受理回执。 private enum CommandTaskData { static func snapshot(phase: String = "shooting", commands: [String] = ["flighttask_pause", "return_home"], taskStatus: Int = 20, lockedPlane: Bool = true, includeTaskIdentity: Bool = true, includeFlightControl: Bool = true, version: Int = 1) throws -> DroneDockShootingResponse { var task: [String: Any] = ["status": taskStatus] if includeTaskIdentity { task["id"] = 501 } let paused = phase == "paused" let returning = phase == "returning" if returning { task["result_code"] = "return_home" } let control = DroneDockShootingTaskTestData.flightControl( state: paused ? "paused" : returning ? "returning" : "executing", canPause: !paused, canResume: paused, canReturn: !returning, resumePhase: paused ? "shooting" : returning ? "returning" : nil, returnReason: returning ? "manual" : nil, isAirborne: true, pauseReason: paused ? "manual" : phase == "arrived_pending_start" ? "arrival_wait" : nil) return try DroneDockShootingTaskTestData.response(changes: [ "execution_batch": 100, "state_version": version, "snapshot_kind": "full", "flight_control": includeFlightControl ? control : NSNull(), "order_flight_task": task, "task": task, "current_plane": ["id": lockedPlane ? 58 : 0, "sn_number": "LOCAL-COMMAND-PLANE-058"], "execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": phase == "arrived_pending_start" ? "start_shoot" : phase], "ui": ["phase": paused ? "manual_paused" : returning ? "returning_home" : phase, "title": "模拟安全指令阶段", "message": "本地模拟,未发送设备指令", "commands": commands.map { ["command": $0] }] ]) } static func receipt(command: DroneDockSafetyCommand, taskID: Int = 501, clientRequestID: String? = nil) throws -> DroneDockCommandResponse { let commandID = "local-\(command.rawValue)-\(clientRequestID ?? "fixture")" let payload: [String: Any] = ["order_flight_task_id": taskID, "command": command.rawValue, "accepted": true, "device_confirmed": false, "execution_batch": 100, "command_id": commandID, "client_request_id": clientRequestID as Any? ?? NSNull(), "pending_command": ["command_id": commandID, "client_request_id": clientRequestID as Any? ?? NSNull(), "command": command.rawValue, "status": "pending"], "airport_sn": "LOCAL-COMMAND-PLANE-058", "plane_id": 58, "dji_status": NSNull(), "metrics": []] return try JSONDecoder().decode(DroneDockCommandResponse.self, from: JSONSerialization.data(withJSONObject: payload)) } static func startReceipt() throws -> DroneDockStartShootResponse { try JSONDecoder().decode(DroneDockStartShootResponse.self, from: Data(#"{"order_flight_task_id":501,"plane_id":58}"#.utf8)) } }