import UIKit import XCTest @testable import suixinkan /// 通过独立内存传输驱动真实任务页,验证开始按钮与接口流程,不连接任何后端。 @MainActor final class DroneDockStartShootViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? /// 双击只提交一次,回执后读同一任务并显示拍摄中,固定区域和旧读数不闪空。 func testLocalSuccessRefreshesSameTaskAndRejectsDoubleTap() async throws { let controller = try makeController(result: "success") let window = makeWindow(controller) defer { close(window) } try await settle(window) { controller.viewModel.canStartShooting } XCTAssertEqual(controller.title, "拍摄任务 · 本地模拟") let fixedIDs = ["top", "stateContainer", "safety"] let frames = try fixedIDs.map { try XCTUnwrap(find(controller.view, suffix: $0)).frame } let oldTitle = controller.viewModel.presentation.title let oldBattery = find(controller.view, suffix: "metric.battery")?.accessibilityValue let button = try XCTUnwrap(find(controller.view, suffix: "primary") as? UIButton) button.sendActions(for: .touchUpInside) button.sendActions(for: .touchUpInside) XCTAssertFalse(button.isEnabled) XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery) XCTAssertEqual(controller.viewModel.presentation.title, oldTitle) try await settle(window) { controller.viewModel.hasSubmittedStart && controller.viewModel.presentation.phase == .shooting } XCTAssertFalse(controller.viewModel.canStartShooting) for (index, suffix) in fixedIDs.enumerated() { XCTAssertEqual(try XCTUnwrap(find(controller.view, suffix: suffix)).frame, frames[index]) } 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.map { $0["method"] as? String }, ["GET", "POST", "GET"]) XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.count, 1) } /// 明确业务拒绝保留旧页面,只有再次点击才再次提交;不偷偷创建或召唤。 func testLocalBusinessFailureAllowsOnlyExplicitRetry() async throws { let controller = try makeController(result: "business-failure") let window = makeWindow(controller) defer { close(window) } try await settle(window) { controller.viewModel.canStartShooting } let button = try XCTUnwrap(find(controller.view, suffix: "primary") as? UIButton) button.sendActions(for: .touchUpInside) try await settle(window) { controller.viewModel.startErrorMessage != nil && !controller.viewModel.isStartingShooting } XCTAssertFalse(controller.viewModel.startOutcomeUnknown) XCTAssertFalse(controller.viewModel.hasSubmittedStart) XCTAssertTrue(controller.viewModel.canStartShooting) XCTAssertTrue(button.isEnabled) button.sendActions(for: .touchUpInside) try await settle(window) { controller.viewModel.startErrorMessage != nil && !controller.viewModel.isStartingShooting } let transcript = try await records(controller, window: window) let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) XCTAssertEqual(entries.map { $0["method"] as? String }, ["GET", "POST", "POST"]) XCTAssertFalse(entries.contains { ($0["path"] as? String)?.contains("/tasks/create") == true }) XCTAssertFalse(entries.contains { $0["path"] as? String == "/api/app/airport/shoot" }) } /// 超时结果未知时即使读回旧的可开始状态,也不能重发开始请求。 func testLocalTimeoutLocksStartWhileReadRefreshRemainsAvailable() async throws { let controller = try makeController(result: "timeout") let window = makeWindow(controller) defer { close(window) } try await settle(window) { controller.viewModel.canStartShooting } let button = try XCTUnwrap(find(controller.view, suffix: "primary") as? UIButton) button.sendActions(for: .touchUpInside) try await settle(window) { controller.viewModel.startOutcomeUnknown && !controller.viewModel.isStartingShooting } XCTAssertFalse(controller.viewModel.canStartShooting) let refresh = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { $0.accessibilityIdentifier == "drone.task.remote.navigationRefresh" }) XCTAssertTrue(refresh.isEnabled) send(refresh) try await settle(window) { !controller.viewModel.isLoading } XCTAssertFalse(controller.viewModel.canStartShooting) 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(transcript["network_sent"] as? Bool, false) } private func makeController(result: String) throws -> DroneDockShootingTaskViewController { try XCTUnwrap(DroneDockStartShootSimulation.makeController( arguments: ["--dock-start-shoot-mock", "--dock-start-shoot-result=\(result)"]) as? DroneDockShootingTaskViewController) } 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) return try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.text.utf8)) as? [String: Any]) } 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..<200 { window.layoutIfNeeded() if condition() { try await Task.sleep(nanoseconds: 80_000_000) window.layoutIfNeeded() if condition() { return } } try await Task.sleep(nanoseconds: 15_000_000) } XCTFail("模拟开拍页面未在预期时间内完成状态更新") throw NSError(domain: "DroneDockStartShootViewTests", 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) } } }