Files
suixinkan_uikit/suixinkanTests/DroneDockTaskControlStateViewTests.swift
T
lujiuyin cd90c3648b 适配上传中订单并完善机巢操作与订阅兜底
支持订单状态 25 和持续拍摄、交付确认;安全指令点击后直接提交;鉴权超时保留 HTTP 兜底并退避换票重连。补充对应隔离回归测试。
2026-11-05 12:35:58 +08:00

708 lines
46 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import UIKit
import XCTest
@testable import suixinkan
/// 使用内存快照核验暂停、返航和回巢面板,以及中央继续任务的实际指令连接。
@MainActor
final class DroneDockTaskControlStateViewTests: XCTestCase {
private weak var previousKeyWindow: UIWindow?
/// 诊断记录实际带秒数的按钮标题,计时更新不会改变其他操作门禁或加载状态。
func testDiagnosticFieldsReflectCountdownButtonTitleAndKeepControlState() throws {
let view = DroneDockTaskStatusView(frame: CGRect(x: 0, y: 0, width: 375, height: 180))
view.apply(DroneDockTaskPresentation(phase: .paused, title: "无人机已暂停", message: "当前悬停待命。",
deviceStatus: "", action: .resume, actionTitle: "继续任务", isActionEnabled: true), isPrimaryActionLoading: true)
view.layoutIfNeeded()
XCTAssertEqual(view.diagnosticFields["title"] as? String, "无人机已暂停")
XCTAssertEqual(view.diagnosticFields["action_title"] as? String, "继续任务")
XCTAssertEqual(view.diagnosticFields["action_loading"] as? Bool, true)
XCTAssertEqual(view.diagnosticFields["action_enabled"] as? Bool, false)
view.apply(DroneDockTaskPresentation(phase: .ready, title: "无人机已到达", message: "确认后开拍",
deviceStatus: "", action: .start, actionTitle: "开始拍摄", isActionEnabled: true, countdownSeconds: 30))
view.layoutIfNeeded()
var thirty = view.diagnosticFields
XCTAssertEqual(thirty["action_title"] as? String, "开始拍摄(30s)")
XCTAssertEqual(thirty["countdown"] as? String, "running")
XCTAssertFalse(views(in: view).contains { $0.accessibilityIdentifier == "drone.task.remote.countdown" })
view.updateCountdown(seconds: 29)
var twentyNine = view.diagnosticFields
XCTAssertEqual(twentyNine["action_title"] as? String, "开始拍摄(29s)")
XCTAssertEqual(twentyNine["countdown"] as? String, "running")
thirty.removeValue(forKey: "action_title")
twentyNine.removeValue(forKey: "action_title")
XCTAssertEqual(try JSONSerialization.data(withJSONObject: thirty, options: [.sortedKeys]),
try JSONSerialization.data(withJSONObject: twentyNine, options: [.sortedKeys]))
view.updateCountdown(seconds: 0)
XCTAssertEqual(view.diagnosticFields["action_title"] as? String, "开始拍摄(0s)")
XCTAssertEqual(view.diagnosticFields["countdown"] as? String, "zero")
XCTAssertEqual(view.diagnosticFields["action_enabled"] as? Bool, true)
view.updateCountdown(seconds: nil)
XCTAssertEqual(view.diagnosticFields["action_title"] as? String, "开始拍摄")
XCTAssertEqual(view.diagnosticFields["countdown"] as? String, "hidden")
XCTAssertEqual(view.diagnosticFields["action_enabled"] as? Bool, true)
let button = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: .orange, filled: true)
button.apply(title: "紧急暂停", subtitle: "悬停待命", enabled: true, isLoading: true)
XCTAssertEqual(button.diagnosticFields["title"] as? String, "紧急暂停")
XCTAssertEqual(button.diagnosticFields["subtitle"] as? String, "悬停待命")
XCTAssertEqual(button.diagnosticFields["loading"] as? Bool, true)
XCTAssertEqual(button.diagnosticFields["enabled"] as? Bool, false)
}
/// 相同快照重新读取不重复输出 UI 展示;导航来源与真实按钮状态可在统一会话中关联。
func testTaskPageDiagnosticsShareSessionAndDeduplicateUnchangedRender() async throws {
let logs = ControlStateDiagnosticLog()
let diagnostics = DroneDockTaskDiagnostics(sessionID: "ui-diagnostic-test", sink: { logs.append($0) })
let service = try ControlStateViewService(state: "paused")
let controller = try makeController(service: service, diagnostics: diagnostics)
controller.recordNavigationEntry(source: "preparation", fields: ["preparation_session_id": "preparation-test"])
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .paused }
let pausedRenders = logs.events.filter { ($0["central"] as? [String: Any])?["phase"] as? String == "paused" }
let render = try XCTUnwrap(pausedRenders.last)
XCTAssertEqual(render["session_id"] as? String, "ui-diagnostic-test")
XCTAssertEqual(render["entry_source"] as? String, "preparation")
let safety = try XCTUnwrap(render["safety"] as? [String: Any])
XCTAssertEqual((safety["pause"] as? [String: Any])?["enabled"] as? Bool, false)
XCTAssertEqual((safety["return_home"] as? [String: Any])?["enabled"] as? Bool, true)
let before = pausedRenders.count
try tapNavigationRefresh(controller)
try await settle(window) { !controller.viewModel.isLoading }
XCTAssertEqual(logs.events.filter { ($0["central"] as? [String: Any])?["phase"] as? String == "paused" }.count, before)
XCTAssertTrue(logs.events.contains { $0["event"] as? String == "navigation.task_entry"
&& $0["preparation_session_id"] as? String == "preparation-test" })
XCTAssertTrue(service.commands.isEmpty)
}
/// 控制状态保持固定面板和整行按钮,禁用状态不会调用操作,紧凑布局也保留点击尺寸。
func testControlPanelsUseLocalCopyAndStableActionArea() throws {
let states: [(DroneDockTaskDisplayPhase, String, String, DroneDockTaskDisplayAction, String, Bool)] = [
(.paused, "无人机已暂停", "当前悬停待命。\n确认安全后,可继续任务或立即返航。", .resume, "继续任务", true),
(.returning, "无人机正在返航", "本次拍摄已中断。\n请留意实时画面与无人机状态。", .none, "拍摄已中断", false),
(.returned, "本次拍摄已中断", "无人机已返回机巢,可在满足条件后重新召唤。", .retry, "重新召唤无人机", true)
]
for size in [CGSize(width: 320, height: 100), CGSize(width: 375, height: 160), CGSize(width: 414, height: 240)] {
let view = DroneDockTaskStatusView(frame: CGRect(origin: .zero, size: size))
var calls = 0
view.onPrimaryAction = { calls += 1 }
for (phase, title, message, action, buttonTitle, enabled) in states {
view.apply(DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: "后端设备摘要不应显示", action: action, actionTitle: buttonTitle, isActionEnabled: enabled))
view.layoutIfNeeded()
let titleLabel = try XCTUnwrap(find(in: view, id: "drone.task.remote.statusTitle") as? UILabel)
let messageLabel = try XCTUnwrap(views(in: view).first {
$0.accessibilityIdentifier == "drone.task.remote.statusMessage"
} as? UILabel)
let button = try XCTUnwrap(find(in: view, id: action == .refresh ? "drone.task.remote.refresh" : "drone.task.remote.primary") as? UIButton)
XCTAssertEqual(titleLabel.text, title)
XCTAssertEqual(messageLabel.text, message)
XCTAssertEqual(messageLabel.isHidden, size.height < 120)
XCTAssertEqual(button.configuration?.title, buttonTitle)
XCTAssertEqual(button.isEnabled, enabled)
XCTAssertGreaterThanOrEqual(button.bounds.height, 44)
XCTAssertEqual(button.bounds.width, size.width - 36, accuracy: 0.5)
XCTAssertTrue(view.bounds.insetBy(dx: -0.5, dy: -0.5).contains(button.convert(button.bounds, to: view)))
XCTAssertFalse(visibleTexts(in: view).contains("后端设备摘要不应显示"))
XCTAssertEqual(views(in: view).filter { $0.accessibilityIdentifier == "drone.task.remote.statusTitle" }.count, 1)
let previous = calls
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, previous + (enabled ? 1 : 0))
}
}
}
/// 真正渲染到 UILabel 的颜色在加载和紧凑布局切换后仍为白色,不可用时才使用灰色。
func testResumeButtonRenderedForegroundSurvivesLoadingAndLayoutChanges() async throws {
let host = UIViewController()
let panel = DroneDockTaskControlStateView(frame: CGRect(x: 0, y: 100, width: 375, height: 160))
host.view.addSubview(panel)
panel.setIdentifiersActive(true)
var calls = 0
panel.onPrimaryAction = { calls += 1 }
let window = makeWindow(root: host)
defer { close(window) }
for (enabled, loading) in [(true, false), (false, true), (false, false), (true, false)] {
panel.apply(DroneDockTaskPresentation(phase: .paused, title: "无人机已暂停", message: "当前悬停待命。",
deviceStatus: "", action: .resume, actionTitle: "继续任务", isActionEnabled: enabled),
isPrimaryActionLoading: loading)
for height: CGFloat in [160, 240, 160] {
panel.frame.size.height = height
panel.setNeedsLayout()
try await settle(window) { panel.bounds.height == height }
let primary = try XCTUnwrap(find(in: panel, id: "drone.task.remote.primary") as? UIButton)
try assertRenderedForeground(primary, expected: enabled || loading ? .white : UIColor(hex: 0x929BAE))
assertColor(try XCTUnwrap(primary.configuration?.background.backgroundColor),
equals: enabled || loading ? DroneDockStyle.primary : UIColor(hex: 0xEDF0F5))
XCTAssertEqual(primary.titleLabel?.text, "继续任务")
XCTAssertEqual(primary.isEnabled, enabled && !loading)
XCTAssertGreaterThanOrEqual(primary.bounds.height, 44)
let before = calls
primary.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, before + (enabled && !loading ? 1 : 0))
}
if loading { capture(window, name: "继续任务加载-白字蓝底(隔离模拟)") }
}
}
/// 暂停时中央继续任务只发送一次 recovery,底部暂停禁用;新的执行快照恢复拍摄中。
func testPausedPrimaryResumesSameTaskAndKeepsSafetyButtonsFixed() async throws {
let service = try ControlStateViewService(state: "paused")
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .paused }
let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton)
let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton)
XCTAssertEqual(pause.accessibilityLabel, "已暂停")
XCTAssertEqual(pause.accessibilityValue, "悬停待命")
XCTAssertFalse(pause.isEnabled)
XCTAssertEqual(returnButton.accessibilityLabel, "立即返航")
XCTAssertTrue(returnButton.isEnabled)
XCTAssertEqual(primary.configuration?.title, "继续任务")
XCTAssertTrue(primary.isEnabled)
capture(window, name: "暂停-继续任务(隔离模拟)")
primary.sendActions(for: .touchUpInside)
primary.sendActions(for: .touchUpInside)
try await settle(window) { service.commands.count == 1 && controller.viewModel.presentation.phase == .shooting }
XCTAssertEqual(service.commands.map(\.taskID), [501])
XCTAssertEqual(service.commands.map(\.command), [.resume])
XCTAssertEqual(pause.accessibilityLabel, "紧急暂停")
XCTAssertTrue(pause.isEnabled)
XCTAssertEqual(returnButton.accessibilityLabel, "立即返航")
XCTAssertFalse(visibleTexts(in: controller.view).contains("接口错误按钮名称"))
}
/// 手动返航不显示拍摄成功,确认回巢后恢复中央重召唤入口并禁用两项安全操作。
func testManualReturnUpdatesToReturnedAndReopensResummon() async throws {
let service = try ControlStateViewService(state: "returning")
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .returning }
let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
var primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton)
XCTAssertEqual(returnButton.accessibilityLabel, "返航中")
XCTAssertEqual(returnButton.accessibilityValue, "返回机巢")
XCTAssertFalse(returnButton.isEnabled)
XCTAssertEqual(primary.configuration?.title, "拍摄已中断")
XCTAssertFalse(primary.isEnabled)
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机正在返航"))
XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion)
capture(window, name: "手动返航中(隔离模拟)")
service.response = try ControlStateViewService.snapshot(state: "returned", version: 2)
try tapNavigationRefresh(controller)
try await settle(window) { controller.viewModel.presentation.phase == .returned }
primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton)
XCTAssertEqual(primary.configuration?.title, "重新召唤无人机")
XCTAssertTrue(primary.isEnabled)
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已返回机巢,可在满足条件后重新召唤。"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已返回机巢"))
XCTAssertFalse(visibleTexts(in: controller.view).contains("拍摄已完成"))
XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion)
XCTAssertEqual(returnButton.accessibilityLabel, "已返航")
XCTAssertEqual(returnButton.accessibilityValue, "已返回机巢")
XCTAssertFalse(returnButton.isEnabled)
XCTAssertFalse(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton).isEnabled)
XCTAssertTrue(service.commands.isEmpty)
capture(window, name: "已返回机巢-可重召唤(隔离模拟)")
}
/// 暂停受理后只转动暂停按钮,中央保留拍摄状态、返航可点,直到匹配的设备确认。
func testAcceptedPauseKeepsBusinessPanelAndReturnEnabledUntilConfirmed() async throws {
let service = try ControlStateViewService(state: "executing")
service.confirmsCommand = false
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .shooting }
let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton)
let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
pause.sendActions(for: .touchUpInside)
pause.sendActions(for: .touchUpInside)
XCTAssertTrue(returnButton.isEnabled)
try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand }
XCTAssertEqual(controller.viewModel.presentation.phase, .shooting)
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机正在拍摄中"))
XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理"))
XCTAssertEqual(pause.accessibilityLabel, "紧急暂停")
XCTAssertEqual(pause.accessibilityValue, "处理中,悬停待命")
XCTAssertFalse(pause.isEnabled)
let spinner = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause.loading") as? UIActivityIndicatorView)
XCTAssertTrue(spinner.isAnimating)
XCTAssertTrue(returnButton.isEnabled)
XCTAssertEqual(returnButton.accessibilityValue, "中断任务")
XCTAssertEqual(service.commands.map(\.command), [.pause])
service.response = try ControlStateViewService.snapshot(state: "paused", version: 2,
pendingCommand: service.progress(for: 0, status: "succeeded"))
try tapNavigationRefresh(controller)
try await settle(window) { controller.viewModel.presentation.phase == .paused && !controller.viewModel.isCommandLoading(.pause) }
XCTAssertFalse(spinner.isAnimating)
XCTAssertEqual(pause.accessibilityLabel, "已暂停")
XCTAssertEqual(pause.accessibilityValue, "悬停待命")
XCTAssertTrue(returnButton.isEnabled)
}
/// 设备确认后立即结束按钮动画,即使紧随其后的 shooting 回查仍挂起;旧权限仍不得重复暂停。
func testConfirmedCommandStopsSpinnerWhileFollowupReadIsPending() async throws {
let service = try ControlStateViewService(state: "executing")
service.holdsReadsAfterCommand = true
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { service.finishReads(); close(window) }
try await settle(window) { controller.viewModel.canSendCommand(.pause) }
let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton)
let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
pause.sendActions(for: .touchUpInside)
try await settle(window) { service.heldReadCount == 1 && !controller.viewModel.isSendingCommand }
XCTAssertEqual(controller.viewModel.commandResponse?.deviceConfirmed, true)
XCTAssertFalse(controller.viewModel.isCommandLoading(.pause))
let spinner = try XCTUnwrap(views(in: controller.view).first {
$0.accessibilityIdentifier == "drone.task.remote.pause.loading"
} as? UIActivityIndicatorView)
XCTAssertFalse(spinner.isAnimating)
XCTAssertTrue(spinner.isHidden)
XCTAssertFalse(pause.isEnabled, "设备确认并不允许利用旧权限重复提交")
XCTAssertTrue(returnButton.isEnabled)
XCTAssertEqual(controller.viewModel.presentation.phase, .shooting)
pause.sendActions(for: .touchUpInside)
XCTAssertEqual(service.commands.map(\.command), [.pause])
service.finishReads()
try await settle(window) { controller.viewModel.presentation.phase == .paused }
XCTAssertFalse(spinner.isAnimating)
}
/// 继续任务待确认时保留暂停面板与独立返航权限,返航可直接提交且不重复发送。
func testPendingResumeLoadsOnlyPrimaryAndKeepsReturnAvailable() async throws {
let service = try ControlStateViewService(state: "paused")
service.confirmsCommand = false
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .paused }
let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton)
let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
primary.sendActions(for: .touchUpInside)
primary.sendActions(for: .touchUpInside)
XCTAssertFalse(primary.isEnabled)
XCTAssertTrue(returnButton.isEnabled)
try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand }
XCTAssertEqual(controller.viewModel.presentation.phase, .paused)
XCTAssertEqual(primary.configuration?.title, "继续任务")
XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary.loading") as? UIActivityIndicatorView).isAnimating)
XCTAssertTrue(returnButton.isEnabled)
XCTAssertEqual(service.commands.map(\.command), [.resume])
service.response = try ControlStateViewService.snapshot(state: "paused", version: 2,
pendingCommand: service.progress(for: 0, status: "pending"))
try tapNavigationRefresh(controller)
try await settle(window) { controller.viewModel.response?.stateVersion == 2 && !controller.viewModel.isLoading }
XCTAssertEqual(controller.viewModel.presentation.phase, .paused)
XCTAssertFalse(primary.isEnabled)
XCTAssertTrue(controller.viewModel.isCommandLoading(.resume))
try assertRenderedForeground(primary, expected: .white)
XCTAssertTrue(returnButton.isEnabled)
capture(window, name: "恢复受理待设备确认-保持暂停(隔离模拟)")
returnButton.sendActions(for: .touchUpInside)
returnButton.sendActions(for: .touchUpInside)
XCTAssertNil(controller.presentedViewController, "恢复待确认不会让返航新增确认弹窗")
XCTAssertFalse(returnButton.isEnabled)
let returnSpinner = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return.loading") as? UIActivityIndicatorView)
XCTAssertTrue(returnSpinner.isAnimating)
try await settle(window) { service.commands.count == 2 && !controller.viewModel.isSendingCommand }
XCTAssertEqual(service.commands.map(\.command), [.resume, .returnHome])
XCTAssertEqual(Set(service.commands.map(\.clientRequestID)).count, 2)
XCTAssertTrue(service.commands.allSatisfy { $0.taskID == 501 })
XCTAssertTrue(controller.viewModel.isCommandLoading(.returnHome))
XCTAssertFalse(controller.viewModel.isCommandLoading(.resume), "后受理返航替代旧的继续意图")
XCTAssertEqual(controller.viewModel.presentation.phase, .paused, "受理本身不替代完整设备快照")
XCTAssertNil(controller.presentedViewController)
service.response = try ControlStateViewService.snapshot(state: "returning", version: 3,
pendingCommand: service.progress(for: 1, status: "succeeded"))
try tapNavigationRefresh(controller)
try await settle(window) { controller.viewModel.presentation.phase == .returning && !controller.viewModel.isCommandLoading(.returnHome) }
XCTAssertFalse(returnSpinner.isAnimating)
XCTAssertFalse(returnButton.isEnabled)
XCTAssertEqual(service.commands.count, 2)
XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理"))
}
/// 返航途中高度证据未知时,明确的 can_pause 仍控制暂停入口,不把 null 当作已落地。
func testReturningWithUnknownAirborneUsesExplicitPausePermission() async throws {
let service = try ControlStateViewService(state: "returning")
service.confirmsCommand = false
service.response = try ControlStateViewService.snapshot(state: "returning", version: 1, airborne: nil)
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .returning }
let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton)
XCTAssertTrue(pause.isEnabled)
XCTAssertFalse(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton).isEnabled)
pause.sendActions(for: .touchUpInside)
try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand }
XCTAssertEqual(service.commands.map(\.command), [.pause])
XCTAssertEqual(controller.viewModel.presentation.phase, .returning)
XCTAssertTrue(controller.viewModel.isCommandLoading(.pause))
}
/// 已回巢但机巢未恢复空闲时显示回巢状态并禁用重召唤,空闲快照到达后再开放。
func testReturnedWaitsForDockIdleBeforeEnablingResummon() async throws {
let service = try ControlStateViewService(state: "returned")
service.response = try ControlStateViewService.snapshot(state: "returned", version: 1, awaitDockIdle: true)
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .returned }
let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton)
XCTAssertEqual(primary.configuration?.title, "重新召唤无人机")
XCTAssertFalse(primary.isEnabled)
try assertRenderedForeground(primary, expected: UIColor(hex: 0x929BAE))
XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion)
XCTAssertFalse(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton).isEnabled)
service.response = try ControlStateViewService.snapshot(state: "returned", version: 2)
try tapNavigationRefresh(controller)
try await settle(window) { primary.isEnabled }
XCTAssertEqual(controller.viewModel.presentation.phase, .returned)
try assertRenderedForeground(primary, expected: .white)
XCTAssertTrue(service.commands.isEmpty)
}
/// 后端返航尚在处理中仍允许紧急暂停,不能因为返航按钮加载把另一按钮禁用。
func testPendingReturnAllowsPauseWithoutReplacingReturningPanel() async throws {
let service = try ControlStateViewService(state: "returning")
service.confirmsCommand = false
service.response = try ControlStateViewService.snapshot(state: "returning", version: 1, pendingCommand: [
"command_id": "remote-return", "client_request_id": "remote-request", "command": "return_home", "status": "pending"])
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .returning }
let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton)
let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
XCTAssertTrue(pause.isEnabled)
XCTAssertFalse(returnButton.isEnabled)
XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return.loading") as? UIActivityIndicatorView).isAnimating)
pause.sendActions(for: .touchUpInside)
try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand }
XCTAssertEqual(service.commands.map(\.command), [.pause])
XCTAssertEqual(controller.viewModel.presentation.phase, .returning)
XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause.loading") as? UIActivityIndicatorView).isAnimating)
XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理"))
}
/// 指令失败或被替代都结束对应按钮的加载,业务面板保留设备已确认的拍摄阶段。
func testTerminalCommandProgressStopsLoadingWithoutReplacingBusinessPanel() async throws {
for status in ["failed", "superseded"] {
let service = try ControlStateViewService(state: "executing")
service.confirmsCommand = false
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.canSendCommand(.pause) }
let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton)
pause.sendActions(for: .touchUpInside)
try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand }
let spinner = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause.loading") as? UIActivityIndicatorView)
XCTAssertTrue(spinner.isAnimating)
service.response = try ControlStateViewService.snapshot(state: "executing", version: 2,
pendingCommand: service.progress(for: 0, status: status))
try tapNavigationRefresh(controller)
try await settle(window) { !controller.viewModel.isCommandLoading(.pause) }
XCTAssertFalse(spinner.isAnimating)
XCTAssertTrue(pause.isEnabled)
XCTAssertEqual(controller.viewModel.presentation.phase, .shooting)
XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton).isEnabled)
}
}
/// 起飞准备即使在巢也展示前往点位,到点自动悬停展示待开拍而非手动暂停。
func testStartingAndArrivalWaitUseTheirBusinessPanels() async throws {
for (state, arrivalWait, expected) in [("starting", false, DroneDockTaskDisplayPhase.navigating),
("executing", true, .ready)] {
let service = try ControlStateViewService(state: state)
service.response = try ControlStateViewService.snapshot(state: state, version: 1, arrivalWait: arrivalWait)
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == expected }
XCTAssertFalse(visibleTexts(in: controller.view).contains("无人机已暂停"))
XCTAssertFalse(visibleTexts(in: controller.view).contains("无人机已返回机巢"))
}
}
/// 中央正常拍完的业务状态不覆盖物理返航、回巢或未知状态,安全控制文案保持设备含义。
func testCompletedRecordingSafetyButtonsFollowPhysicalFlightState() async throws {
let cases = [("returning", "返航中", "返回机巢"),
("returned", "已返航", "已返回机巢"),
("unknown", "立即返航", "暂不可用")]
for (state, title, subtitle) in cases {
let service = try ControlStateViewService(state: state)
service.response = try ControlStateViewService.snapshot(state: state, version: 1, normalCompletion: true)
let controller = try makeController(service: service)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) { controller.viewModel.presentation.phase == .postShootUploading }
let button = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton)
XCTAssertEqual(button.accessibilityLabel, title)
XCTAssertEqual(button.accessibilityValue, subtitle)
XCTAssertFalse(button.isEnabled)
XCTAssertTrue(visibleTexts(in: controller.view).contains("拍摄已完成"))
button.sendActions(for: .touchUpInside)
XCTAssertTrue(service.commands.isEmpty)
}
}
/// 中断返航途中仍可读取图传;首次进入已回巢快照时不请求图传,也不显示拍摄成功。
func testReturnedSnapshotDoesNotStartLiveWhileReturningStillLoads() async throws {
for state in ["returning", "returned"] {
let service = try ControlStateViewService(state: state)
let liveService = ControlStateLiveService()
let controller = try makeController(service: service, liveService: liveService)
let window = makeWindow(root: controller)
defer { close(window) }
try await settle(window) {
controller.viewModel.response != nil && !controller.viewModel.isLoading
&& (state == "returned" || liveService.requests == [501])
}
XCTAssertEqual(liveService.requests, state == "returned" ? [] : [501])
XCTAssertEqual(controller.viewModel.shouldStopLiveReception, state == "returned")
XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion)
XCTAssertFalse(visibleTexts(in: controller.view).contains("拍摄已完成"))
if state == "returned" {
XCTAssertNil(controller.liveViewModel.response)
XCTAssertNil(controller.liveViewModel.playbackSessionID)
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已返回机巢"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("拍摄封面 · 实时图传已结束"))
}
}
}
private func makeController(service: ControlStateViewService,
liveService: (any DroneDockLiveServing)? = nil,
diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics()) throws -> DroneDockShootingTaskViewController {
let context = DroneDockShootingTaskTestData.context()
let model = DroneDockShootingTaskViewModel(context: context, taskID: 501,
order: try DroneDockShootingTaskTestData.order(), service: service,
commandService: service, resummonService: service, diagnostics: diagnostics, currentContext: { context })
let live = DroneDockLiveViewModel(context: context, taskID: 501, service: liveService, currentContext: { context })
return DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live,
simulationRecordsProvider: { "纯内存替身,未联网" },
shootingPollDelay: { _ in try await Task.sleep(for: .seconds(60)) })
}
private func makeWindow(root: UIViewController) -> UIWindow {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
previousKeyWindow = scene?.windows.first { $0.isKeyWindow }
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds
window.overrideUserInterfaceStyle = .light
window.rootViewController = UINavigationController(rootViewController: root)
window.makeKeyAndVisible()
window.layoutIfNeeded()
return window
}
private func close(_ window: UIWindow) {
window.isHidden = true
window.rootViewController = nil
previousKeyWindow?.makeKeyAndVisible()
}
private func settle(_ window: UIWindow, until condition: () -> Bool) async throws {
for _ in 0..<160 {
window.layoutIfNeeded()
if condition() {
try await Task.sleep(for: .milliseconds(80))
window.layoutIfNeeded()
if condition() { return }
}
try await Task.sleep(for: .milliseconds(15))
}
XCTFail("隔离任务控制页面未达到预期状态")
throw NSError(domain: "DroneDockTaskControlStateViewTests", code: 1)
}
private func views(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { views(in: $0) } }
private func hidden(_ view: UIView) -> Bool { view.isHidden || view.alpha < 0.01 || (view.superview.map(hidden) ?? false) }
private func find(in root: UIView, id: String) -> UIView? {
views(in: root).first { $0.accessibilityIdentifier == id && !hidden($0) }
}
private func visibleTexts(in root: UIView) -> [String] {
views(in: root).compactMap { view in
guard let label = view as? UILabel, !hidden(label), !label.bounds.isEmpty else { return nil }
return label.text
}
}
private func assertRenderedForeground(_ button: UIButton, expected: UIColor,
file: StaticString = #filePath, line: UInt = #line) throws {
button.layoutIfNeeded()
let label = try XCTUnwrap(button.titleLabel, file: file, line: line)
XCTAssertFalse(label.bounds.isEmpty, file: file, line: line)
XCTAssertFalse(try XCTUnwrap(label.text, file: file, line: line).isEmpty, file: file, line: line)
let attributedColor = label.attributedText.flatMap { text -> UIColor? in
guard text.length > 0 else { return nil }
return text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor
}
let actual = try XCTUnwrap(attributedColor ?? label.textColor, file: file, line: line)
assertColor(actual, equals: expected, file: file, line: line)
XCTAssertNotNil(button.configuration?.image, file: file, line: line)
let transform = try XCTUnwrap(button.configuration?.imageColorTransformer, file: file, line: line)
assertColor(transform(.black), equals: expected, file: file, line: line)
}
private func assertColor(_ actual: UIColor, equals expected: UIColor,
file: StaticString = #filePath, line: UInt = #line) {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
var er: CGFloat = 0, eg: CGFloat = 0, eb: CGFloat = 0, ea: CGFloat = 0
XCTAssertTrue(actual.getRed(&r, green: &g, blue: &b, alpha: &a), file: file, line: line)
XCTAssertTrue(expected.getRed(&er, green: &eg, blue: &eb, alpha: &ea), file: file, line: line)
for (value, target) in [(r, er), (g, eg), (b, eb), (a, ea)] {
XCTAssertEqual(value, target, accuracy: 0.005, file: file, line: line)
}
}
private func tapNavigationRefresh(_ controller: UIViewController) throws {
let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first)
let action = try XCTUnwrap(item.action)
_ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil)
}
private func capture(_ window: UIWindow, name: String) {
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) }
let attachment = XCTAttachment(image: image)
attachment.name = name
attachment.lifetime = .keepAlways
add(attachment)
}
}
/// 仅把页面诊断 JSON 保存在内存,线程安全且不替换全局控制台。
private final class ControlStateDiagnosticLog: @unchecked Sendable {
private let lock = NSLock()
private var messages: [String] = []
/// 接收一次日志输出,不执行网络或设备操作。
func append(_ message: String) {
lock.lock()
defer { lock.unlock() }
messages.append(message)
}
/// 返回调用时的完整 JSON 事件快照。
var events: [[String: Any]] {
lock.lock()
defer { lock.unlock() }
return messages.compactMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any] }
}
}
/// 只计数并返回内存参数;没有播放地址、RTC 引擎或网络传输能力。
@MainActor
private final class ControlStateLiveService: DroneDockLiveServing {
private(set) var requests: [Int] = []
/// 仅记录同任务的模拟图传读取,不启动设备推流。
func live(taskID: Int) async throws -> DroneDockLiveResponse {
requests.append(taskID)
return try DroneDockLiveTestData.response()
}
}
/// 遵守 flight_control 合同的纯内存读写服务,完全不具备网络或设备能力。
@MainActor
private final class ControlStateViewService: DroneDockShootingServing, DroneDockCommandSending, DroneDockResummonServing {
var response: DroneDockShootingResponse
var confirmsCommand = true
var holdsReadsAfterCommand = false
private(set) var heldReadCount = 0
private var heldReads: [CheckedContinuation<DroneDockShootingResponse, Never>] = []
private(set) var commands: [(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String)] = []
/// 按指定飞控状态初始化同一任务和批次的完整快照。
init(state: String) throws { response = try Self.snapshot(state: state, version: 1) }
/// 只读内存快照,不采集设备电量。
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse {
guard holdsReadsAfterCommand, !commands.isEmpty else { return response }
heldReadCount += 1
return await withCheckedContinuation { heldReads.append($0) }
}
/// 显式释放测试挂起的只读请求,不产生网络或设备操作。
func finishReads() {
let pending = heldReads
heldReads.removeAll()
pending.forEach { $0.resume(returning: response) }
}
/// 模拟同任务指令回执;可保持旧快照验证指令受理与设备状态的分离。
func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse {
commands.append((taskID, command, clientRequestID))
let progress = progress(for: commands.count - 1, status: confirmsCommand ? "succeeded" : "pending")
if confirmsCommand {
let state = command == .resume ? "executing" : command == .returnHome ? "returning" : "paused"
response = try Self.snapshot(state: state, version: 2, pendingCommand: progress)
}
let payload: [String: Any] = ["accepted": true, "device_confirmed": confirmsCommand,
"acceptance": confirmsCommand ? "device_confirmed" : "accepted", "order_flight_task_id": taskID,
"command_id": progress["command_id"]!, "client_request_id": clientRequestID, "pending_command": progress,
"command": command.rawValue, "execution_batch": 9001, "airport_sn": "LOCAL-CONTROL-058"]
return try JSONDecoder().decode(DroneDockCommandResponse.self, from: JSONSerialization.data(withJSONObject: payload))
}
/// 为已提交的指令生成同一身份的后端进度,用于模拟后续完整快照。
func progress(for index: Int, status: String) -> [String: Any] {
let request = commands[index]
return ["command_id": "local-command-\(index)", "client_request_id": request.clientRequestID,
"command": request.command.rawValue, "status": status]
}
/// 本组测试只检查重召唤许可,不应触发真实或模拟重召唤请求。
func resummon(taskID: Int) async throws -> DroneDockShootResponse {
XCTFail("状态展示测试不应触发重召唤")
throw APIError.networkFailed("纯内存替身未配置重召唤")
}
/// 用明确飞控状态、批次和回巢证据创建完整快照,接口展示文案故意与本地文案不同。
static func snapshot(state: String, version: Int, normalCompletion: Bool = false,
pendingCommand: [String: Any]? = nil, arrivalWait: Bool = false,
airborne: Bool? = true, awaitDockIdle: Bool = false) throws -> DroneDockShootingResponse {
let interrupted = !normalCompletion && ["returning", "returned"].contains(state)
let returnReason: Any = normalCompletion ? "normal_complete" : (interrupted ? "manual" as Any : NSNull())
let pauseReason: Any = state == "paused" ? "manual" : (arrivalWait ? "arrival_wait" as Any : NSNull())
let phase = normalCompletion ? "post_shoot_uploading"
: state == "starting" ? "going_to_spot"
: state == "paused" ? "manual_paused"
: arrivalWait ? "arrived_pending_start"
: state == "returning" ? "returning_home"
: state == "returned" ? "failed_restartable" : "shooting"
let task: [String: Any] = ["id": 501, "status": interrupted ? 40 : 20,
"order_number": "TEST-TASK-PAGE-001", "scenic_id": 128, "plane_id": 58,
"wayline_task_id": 9001, "wayline_status": normalCompletion ? 24 : interrupted ? 91 : 20,
"result_code": interrupted ? "return_home" : "", "airport_sn": "LOCAL-CONTROL-058"]
return try DroneDockShootingTaskTestData.response(changes: [
"order_flight_task_id": 501, "execution_batch": 9001, "state_version": version, "snapshot_kind": "full",
"order_flight_task": task, "task": task,
"current_plane": ["id": 58, "sn_number": "LOCAL-CONTROL-058", "work_status": state == "returned" && !awaitDockIdle ? 1 : 2,
"online_status": 1, "battery_percent": 90, "can_fly": state == "returned" && !awaitDockIdle],
"execute_gate": ["can_execute": arrivalWait, "primary_action": arrivalWait ? "start_shoot" : "blocked"],
"restart_gate": ["can_restart": state == "returned" && !normalCompletion && !awaitDockIdle,
"code": awaitDockIdle ? "await_dock_idle" : state == "returned" ? "ok" : "await_returned",
"primary_action": state == "returned" ? "restart_shoot" : "blocked"],
"ui": ["phase": phase,
"title": "接口错误标题", "message": "接口错误文案", "commands": [
["command": "flighttask_pause", "label": "接口错误按钮名称"],
["command": "flighttask_recovery", "label": "接口错误按钮名称"],
["command": "return_home", "label": "接口错误按钮名称"]]],
"flight_control": ["state": state, "resume_phase": interrupted || normalCompletion ? "returning" : arrivalWait ? "arrived_pending_start" : "shooting",
"return_reason": returnReason, "execution_batch": 9001,
"is_airborne": ["returned", "starting"].contains(state) ? false : airborne as Any? ?? NSNull(), "pause_reason": pauseReason,
"pending_command": pendingCommand as Any? ?? NSNull(),
"drone_in_dock": ["returned", "starting"].contains(state) ? "inside" : "outside",
"can_pause": ["executing", "returning"].contains(state), "can_resume": state == "paused",
"can_return_home": !interrupted && !normalCompletion]
])
}
}