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) XCTAssertTrue(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 == "已暂停" } XCTAssertEqual(model.presentation.phase, .paused) XCTAssertFalse(pause.isEnabled) XCTAssertEqual(pause.accessibilityValue, "悬停待命") XCTAssertEqual(returnHome.accessibilityLabel, "立即返航") XCTAssertTrue(returnHome.isEnabled) XCTAssertEqual(model.commandResponse?.command, "flighttask_pause") assertFrames(controller, suffixes: fixedIDs, frames: frames) capture(window, name: "安全控制-暂停成功-本地模拟") let resume = try button(controller, suffix: "primary") XCTAssertEqual(resume.configuration?.title, "继续任务") XCTAssertTrue(resume.isEnabled) resume.sendActions(for: .touchUpInside) resume.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", "client_request_id"]) XCTAssertFalse(try XCTUnwrap(body["client_request_id"] as? String).isEmpty) } XCTAssertEqual(Set(bodies.compactMap { $0["client_request_id"] as? String }).count, 2) } /// 返航必须先显示模拟确认,关闭确认不会产生任何指令请求。 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 testTimeoutLocksOnlyAffectedSafetyButtonWhileReadRefreshRemainsAvailable() 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) XCTAssertTrue(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) XCTAssertTrue(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: [ "order_flight_task": ["id": 501, "status": 20, "wayline_task_id": 9001], "task": ["id": 501, "status": 20, "wayline_task_id": 9001], "execution_batch": 9001, "state_version": 1, "flight_control": ["state": "executing", "execution_batch": 9001, "is_airborne": true, "drone_in_dock": "outside", "can_pause": true, "can_resume": false, "can_return_home": true], "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) } } }