Files
suixinkan_uikit/suixinkanTests/DroneDockCommandViewTests.swift
T
lujiuyin 20877b425c feat(drone-dock): 添加安全控制接口本地模拟调试
接入 command 请求合同与底部暂停、继续、返航、取消返航交互;支持同任务单次回查、防重复提交及未知结果锁。保留真实指令禁飞拦截,补充隔离测试、模拟回执与截图。
2026-10-30 10:32:31 +08:00

265 lines
14 KiB
Swift

import UIKit
import XCTest
@testable import suixinkan
/// 使用隔离的内存模拟入口检查任务页安全按钮,不连接后端或真实无人机。
@MainActor
final class DroneDockCommandViewTests: XCTestCase {
private weak var previousKeyWindow: UIWindow?
/// 暂停和继续均使用同一任务,连点仅提交一次,刷新期间保留旧数据与固定区域。
func testPauseAndResumeUseSameTaskWithoutDuplicateRequestsOrLayoutChanges() async throws {
let controller = try makeController(result: "success")
let window = makeWindow(controller)
defer { close(window) }
let model = controller.viewModel
try await settle(window) { model.canSendCommand(.pause) }
XCTAssertEqual(controller.title, "拍摄任务 · 本地模拟")
let pause = try button(controller, suffix: "pause")
let returnHome = try button(controller, suffix: "return")
let fixedIDs = ["top", "stateContainer", "safety"]
let frames = try fixedIDs.map { try XCTUnwrap(find(controller.view, suffix: $0)).frame }
let oldTitle = model.presentation.title
let oldBattery = find(controller.view, suffix: "metric.battery")?.accessibilityValue
pause.sendActions(for: .touchUpInside)
pause.sendActions(for: .touchUpInside)
XCTAssertFalse(pause.isEnabled)
XCTAssertFalse(returnHome.isEnabled)
XCTAssertEqual(model.presentation.title, oldTitle)
XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery)
try await settle(window) {
model.canSendCommand(.resume) && !model.isSendingCommand
&& (pause.accessibilityLabel?.contains("继续") == true)
}
XCTAssertEqual(model.presentation.phase, .paused)
XCTAssertEqual(model.commandResponse?.command, "flighttask_pause")
assertFrames(controller, suffixes: fixedIDs, frames: frames)
capture(window, name: "安全控制-暂停成功-本地模拟")
pause.sendActions(for: .touchUpInside)
pause.sendActions(for: .touchUpInside)
try await settle(window) {
model.canSendCommand(.pause) && !model.isSendingCommand
&& (pause.accessibilityLabel?.contains("暂停") == true)
}
XCTAssertEqual(model.presentation.phase, .shooting)
XCTAssertEqual(model.commandResponse?.command, "flighttask_recovery")
assertFrames(controller, suffixes: fixedIDs, frames: frames)
capture(window, name: "安全控制-继续拍摄-本地模拟")
let transcript = try await records(controller, window: window)
let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]])
XCTAssertEqual(transcript["network_sent"] as? Bool, false)
XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "GET", "POST", "GET"])
let posts = entries.filter { $0["method"] as? String == "POST" }
XCTAssertEqual(posts.compactMap { $0["path"] as? String }, Array(repeating: "/api/app/airport/command", count: 2))
let bodies = posts.compactMap { $0["request_body"] as? [String: Any] }
XCTAssertEqual(bodies.compactMap { $0["id"] as? Int }, [901, 901])
XCTAssertEqual(bodies.compactMap { $0["command"] as? String }, ["flighttask_pause", "flighttask_recovery"])
for body in bodies { XCTAssertEqual(Set(body.keys), ["id", "command"]) }
}
/// 返航必须先显示模拟确认,关闭确认不会产生任何指令请求。
func testReturnConfirmationCanBeCancelledWithoutSendingCommand() async throws {
let controller = try makeController(result: "success")
let window = makeWindow(controller)
defer { close(window) }
try await settle(window) { controller.viewModel.canSendCommand(.returnHome) }
let returnHome = try button(controller, suffix: "return")
returnHome.sendActions(for: .touchUpInside)
returnHome.sendActions(for: .touchUpInside)
try await settle(window) {
controller.presentedViewController is UIAlertController
&& controller.presentedViewController?.transitionCoordinator == nil
}
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
XCTAssertEqual(alert.title, "立即返航(本地模拟)")
XCTAssertEqual(alert.actions.compactMap(\.title), ["取消", "模拟返航"])
XCTAssertFalse(controller.viewModel.isSendingCommand)
XCTAssertNil(controller.viewModel.commandResponse)
capture(window, name: "安全控制-返航确认-本地模拟")
alert.dismiss(animated: false)
try await settle(window) { controller.presentedViewController == nil }
let transcript = try await records(controller, window: window)
let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]])
XCTAssertFalse(entries.contains { $0["method"] as? String == "POST" })
XCTAssertEqual(transcript["network_sent"] as? Bool, false)
}
/// 明确拒绝保留原任务状态,只在用户再次点击后重发,不创建或召唤新任务。
func testBusinessFailurePreservesSnapshotAndAllowsExplicitRetry() async throws {
let controller = try makeController(result: "business-failure")
let window = makeWindow(controller)
defer { close(window) }
let model = controller.viewModel
try await settle(window) { model.canSendCommand(.pause) }
let original = model.response
let pause = try button(controller, suffix: "pause")
pause.sendActions(for: .touchUpInside)
try await settle(window) { model.commandErrorMessage != nil && model.canSendCommand(.pause) && pause.isEnabled }
XCTAssertEqual(model.response, original)
XCTAssertFalse(model.commandOutcomeUnknown)
XCTAssertNil(model.commandResponse)
pause.sendActions(for: .touchUpInside)
try await settle(window) { model.commandErrorMessage != nil && model.canSendCommand(.pause) && pause.isEnabled }
let transcript = try await records(controller, window: window)
let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]])
XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "POST"])
XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.compactMap { $0["path"] as? String },
Array(repeating: "/api/app/airport/command", count: 2))
XCTAssertEqual(transcript["network_sent"] as? Bool, false)
}
/// 超时保留旧数据并锁定所有安全动作,手动读取及回执查看仍可使用,不能自动重发。
func testTimeoutLocksSafetyButtonsWhileReadRefreshAndReceiptsRemainAvailable() async throws {
let controller = try makeController(result: "timeout")
let window = makeWindow(controller)
defer { close(window) }
let model = controller.viewModel
try await settle(window) { model.canSendCommand(.pause) }
let original = model.response
let pause = try button(controller, suffix: "pause")
let returnHome = try button(controller, suffix: "return")
pause.sendActions(for: .touchUpInside)
try await settle(window) { model.commandOutcomeUnknown && !model.isSendingCommand }
XCTAssertEqual(model.response, original)
XCTAssertFalse(pause.isEnabled)
XCTAssertFalse(returnHome.isEnabled)
XCTAssertFalse(model.canStartShooting)
XCTAssertFalse(model.canSendCommand(.pause))
let refresh = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first {
$0.accessibilityIdentifier == "drone.task.remote.navigationRefresh"
})
XCTAssertTrue(refresh.isEnabled)
send(refresh)
try await settle(window) { !model.isLoading && refresh.isEnabled }
XCTAssertTrue(model.commandOutcomeUnknown)
XCTAssertFalse(pause.isEnabled)
XCTAssertFalse(returnHome.isEnabled)
capture(window, name: "安全控制-结果待核对-本地模拟")
let transcript = try await records(controller, window: window)
let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]])
XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.count, 1)
XCTAssertEqual(entries.filter { $0["method"] as? String == "GET" }.count, 2)
XCTAssertEqual(transcript["network_sent"] as? Bool, false)
}
/// 普通入口即使读到可用指令,也因未注入模拟指令服务而保持安全按钮禁用。
func testReadOnlyEntryKeepsSafetyButtonsDisabledWhenSnapshotOffersCommands() async throws {
let context = DroneDockShootingTaskTestData.context()
let response = try DroneDockShootingTaskTestData.response(changes: [
"ui": ["phase": "shooting", "title": "拍摄中", "commands": [
["command": "flighttask_pause", "label": "紧急暂停"],
["command": "return_home", "label": "立即返航"]
]]
])
let service = DroneDockShootingTaskTestService(result: .success(response))
let model = DroneDockShootingTaskViewModel(context: context, taskID: 501,
order: try DroneDockShootingTaskTestData.order(), service: service, currentContext: { context })
let controller = DroneDockShootingTaskViewController(viewModel: model)
let window = makeWindow(controller)
defer { close(window) }
try await settle(window) { model.response != nil && !model.isLoading }
let pause = try button(controller, suffix: "pause")
let returnHome = try button(controller, suffix: "return")
XCTAssertFalse(pause.isEnabled)
XCTAssertFalse(returnHome.isEnabled)
pause.sendActions(for: .touchUpInside)
returnHome.sendActions(for: .touchUpInside)
XCTAssertNil(controller.presentedViewController)
XCTAssertFalse(model.isSendingCommand)
XCTAssertNil(model.commandResponse)
XCTAssertEqual(service.requests.count, 1)
}
private func makeController(result: String) throws -> DroneDockShootingTaskViewController {
try XCTUnwrap(DroneDockStartShootSimulation.makeController(arguments: [
"--dock-command-mock", "--dock-command-result=\(result)"
]) as? DroneDockShootingTaskViewController)
}
private func button(_ controller: UIViewController, suffix: String) throws -> UIButton {
try XCTUnwrap(find(controller.view, suffix: suffix) as? UIButton)
}
private func records(_ controller: UIViewController, window: UIWindow) async throws -> [String: Any] {
let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first {
$0.accessibilityIdentifier == "drone.task.mock.recordsButton"
})
XCTAssertTrue(item.isEnabled)
send(item)
try await settle(window) { controller.presentedViewController != nil }
let sheet = try XCTUnwrap(controller.presentedViewController)
let text = try XCTUnwrap(allViews(sheet.view).first {
$0.accessibilityIdentifier == "drone.task.mock.records"
} as? UITextView)
let attachment = XCTAttachment(data: Data(text.text.utf8), uniformTypeIdentifier: "public.json")
attachment.name = "安全控制模拟回执"
attachment.lifetime = .keepAlways
add(attachment)
return try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.text.utf8)) as? [String: Any])
}
private func assertFrames(_ controller: UIViewController, suffixes: [String], frames: [CGRect]) {
for (suffix, frame) in zip(suffixes, frames) { XCTAssertEqual(find(controller.view, suffix: suffix)?.frame, frame) }
}
private func capture(_ window: UIWindow, name: String) {
window.layoutIfNeeded()
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)
}
private func send(_ item: UIBarButtonItem) {
guard let action = item.action else { return XCTFail("缺少导航操作") }
_ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil)
}
private func makeWindow(_ controller: 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: controller)
window.makeKeyAndVisible()
return window
}
private func close(_ window: UIWindow) {
window.rootViewController?.dismiss(animated: false)
window.isHidden = true
window.rootViewController = nil
previousKeyWindow?.makeKeyAndVisible()
}
private func settle(_ window: UIWindow, until condition: () -> Bool) async throws {
for _ in 0..<250 {
window.layoutIfNeeded()
if condition() {
try await Task.sleep(nanoseconds: 100_000_000)
window.layoutIfNeeded()
if condition() { return }
}
try await Task.sleep(nanoseconds: 20_000_000)
}
XCTFail("本地安全指令页面未在预期时间内完成状态更新")
throw NSError(domain: "DroneDockCommandViewTests", code: 1)
}
private func find(_ root: UIView, suffix: String) -> UIView? {
allViews(root).first { $0.accessibilityIdentifier == "drone.task.remote.\(suffix)" }
}
private func allViews(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews($0) } }
}