Files
suixinkan_uikit/suixinkanTests/DroneDockTaskFixedLayoutTests.swift
T
lujiuyin e3979e9e32 feat: 完善机巢任务安全控制与状态诊断
同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。
2026-11-04 17:34:28 +08:00

598 lines
36 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 DroneDockTaskFixedLayoutTests: XCTestCase {
private let compactSize = CGSize(width: 375, height: 146)
private let regularSize = CGSize(width: 402, height: 220)
private let phases: [DroneDockTaskDisplayPhase] = [
.loading, .navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning,
.returned, .completed, .failed, .blocked, .unknown, .readError
]
/// 紧凑屏逐一显示全部业务阶段,控件始终留在固定中间区域内。
func testAllPhasesFitCompactStatusArea() throws {
let status = makeStatus(size: compactSize)
for phase in phases {
apply(presentation(phase), to: status)
XCTAssertTrue(status.usesCompactLayout, "\(phase)")
XCTAssertEqual(status.bounds.size, compactSize)
try assertReadableContainedContent(in: status)
}
}
/// 常规屏支持全部阶段,失败态用独立原因区替代通用设备摘要。
func testAllPhasesFitRegularStatusArea() throws {
let status = makeStatus(size: regularSize)
for phase in phases {
apply(presentation(phase), to: status)
XCTAssertFalse(status.usesCompactLayout, "\(phase)")
XCTAssertEqual(status.bounds.size, regularSize)
let device = try XCTUnwrap(find(in: status, suffix: "deviceStatus") as? UILabel)
if phase == .failed {
XCTAssertTrue(isHidden(device))
let note = try XCTUnwrap(find(in: status, suffix: "failureNote") as? UILabel)
XCTAssertFalse(isHidden(note))
XCTAssertEqual(note.text, "无人机离线,暂不可召唤")
} else if [.shooting, .postShootUploading, .completed, .paused, .returning, .returned].contains(phase) {
XCTAssertTrue(isHidden(device))
} else {
XCTAssertFalse(isHidden(device))
XCTAssertEqual(device.text, "空闲 · 电量 93%")
}
try assertReadableContainedContent(in: status)
}
}
/// 任一阶段的超长后端文案不会挤出容器、压缩点击区域或依赖整体 transform。
func testLongCopyAcrossAllPhasesKeepsControlsReadableAndContained() throws {
for size in [compactSize, regularSize] {
let status = makeStatus(size: size)
for phase in phases {
let value = presentation(phase, longCopy: true)
apply(value, to: status)
XCTAssertEqual(status.bounds.size, size)
XCTAssertEqual(status.transform, .identity)
let title = try XCTUnwrap(find(in: status, suffix: phase == .failed ? "failureTitle" : "statusTitle") as? UILabel)
let message = try XCTUnwrap(find(in: status, suffix: phase == .failed ? "failureReason" : "statusMessage") as? UILabel)
XCTAssertFalse(isHidden(title))
XCTAssertFalse(isHidden(message))
XCTAssertEqual(title.text, value.title, "视觉截断不能丢弃原始详情")
XCTAssertEqual(message.text, phase == .failed ? "失败原因:\(value.message)" : value.message)
try assertReadableContainedContent(in: status)
}
}
}
/// 移除通用详情后,长错误保留完整文本与可点击的整行刷新入口。
func testCompactLongErrorHasNoDetailsAndKeepsFullWidthRefresh() throws {
let status = makeStatus(size: compactSize)
let value = presentation(.readError, longCopy: true)
apply(value, to: status)
var actionCalls = 0
var detailsCalls = 0
status.onPrimaryAction = { actionCalls += 1 }
status.onDetails = { detailsCalls += 1 }
XCTAssertNil(find(in: status, suffix: "details"))
XCTAssertEqual((find(in: status, suffix: "statusMessage") as? UILabel)?.text, value.message)
let refresh = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton)
XCTAssertTrue(refresh.isEnabled)
XCTAssertFalse(isHidden(refresh))
XCTAssertGreaterThanOrEqual(refresh.bounds.height, 44)
XCTAssertEqual(refresh.bounds.width, compactSize.width - 32, accuracy: 0.5)
let center = refresh.convert(CGPoint(x: refresh.bounds.midX, y: refresh.bounds.midY), to: status)
let hit = status.hitTest(center, with: nil)
XCTAssertTrue(hit === refresh || hit?.isDescendant(of: refresh) == true)
refresh.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 1)
XCTAssertEqual(detailsCalls, 0)
try assertReadableContainedContent(in: status)
}
/// 拍摄中按原型显示左侧视频状态、右侧两行说明与整行禁用指示,不提供详情或刷新动作。
func testShootingPanelMatchesPrototypeAndCannotTriggerActions() async throws {
let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
let previous = scene?.windows.first { $0.isKeyWindow }
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
let host = UIViewController()
window.rootViewController = host
window.makeKeyAndVisible()
defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() }
for size in [compactSize, regularSize, CGSize(width: 375, height: 95)] {
let status = makeStatus(size: size)
host.view.addSubview(status)
defer { status.removeFromSuperview() }
var actionCalls = 0
var detailsCalls = 0
status.onPrimaryAction = { actionCalls += 1 }
status.onDetails = { detailsCalls += 1 }
apply(presentation(.shooting), to: status)
window.layoutIfNeeded()
try await Task.sleep(for: .milliseconds(50))
layoutHierarchy(status)
let shooting = try XCTUnwrap(find(in: status, suffix: "shooting"))
let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel)
let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel)
let indicator = try XCTUnwrap(find(in: status, suffix: "shootingIndicator") as? UIButton)
XCTAssertFalse(isHidden(shooting))
XCTAssertEqual(title.text, "无人机正在拍摄中")
XCTAssertEqual(message.text, "请关注现场及实时画面。\n请勿关闭本页或息屏。")
if size.height >= 120 {
XCTAssertFalse(isHidden(message))
XCTAssertEqual(title.convert(title.bounds, to: status).minX, message.convert(message.bounds, to: status).minX, accuracy: 0.5)
}
XCTAssertFalse(indicator.isEnabled)
XCTAssertEqual(indicator.configuration?.title, "拍摄中")
XCTAssertNotNil(indicator.configuration?.image)
XCTAssertEqual(indicator.configuration?.background.backgroundColor, UIColor(hex: 0xD7E7FF))
XCTAssertEqual(indicator.configuration?.baseForegroundColor, UIColor(hex: 0x4D91FF))
XCTAssertEqual(indicator.bounds.width, size.width - 36, accuracy: 0.5)
XCTAssertGreaterThanOrEqual(indicator.bounds.height, 44)
XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "deviceStatus"))))
XCTAssertNil(find(in: status, suffix: "details"))
if let refresh = find(in: status, suffix: "refresh") { XCTAssertTrue(isHidden(refresh)) }
indicator.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 0)
XCTAssertEqual(detailsCalls, 0)
try assertReadableContainedContent(in: status)
if size.height >= 120 { capture(status, name: "拍摄中-原型布局-\(Int(size.width))x\(Int(size.height))") }
}
}
/// 从到达到拍摄中再进入错误/完成状态时,独立面板和通用操作互不留下旧入口。
func testShootingPanelTransitionsClearOldCountdownAndRestoreAllowedAction() throws {
let status = makeStatus(size: regularSize)
var actionCalls = 0
status.onPrimaryAction = { actionCalls += 1 }
apply(presentation(.ready, countdownSeconds: 12), to: status)
let start = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
XCTAssertEqual(start.title(for: .normal), "开始拍摄(12s)")
XCTAssertNil(find(in: status, suffix: "countdown"))
apply(presentation(.shooting), to: status)
let indicator = try XCTUnwrap(find(in: status, suffix: "shootingIndicator") as? UIButton)
XCTAssertFalse(isHidden(indicator))
status.updateCountdown(seconds: 5)
layoutHierarchy(status)
XCTAssertNil(find(in: status, suffix: "countdown"))
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden")
XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "拍摄中")
XCTAssertFalse(start.currentTitle?.contains("s)") == true)
indicator.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 0)
apply(presentation(.readError), to: status)
XCTAssertTrue(isHidden(indicator))
let refresh = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton)
XCTAssertFalse(isHidden(refresh))
XCTAssertTrue(refresh.isEnabled)
XCTAssertEqual(refresh.bounds.width, regularSize.width - 32, accuracy: 0.5)
refresh.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 1)
apply(presentation(.completed), to: status)
XCTAssertTrue(isHidden(indicator))
let materials = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
XCTAssertFalse(isHidden(materials))
XCTAssertTrue(materials.isEnabled)
materials.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 2)
XCTAssertNil(find(in: status, suffix: "details"))
try assertReadableContainedContent(in: status)
}
/// 倒计时在固定小屏内保持可见,数字更新不重建按钮、不扩大现有动作许可。
func testArrivalCountdownFitsFixedAreasAndUpdatesOnlyDisplay() throws {
for size in [compactSize, regularSize] {
for longCopy in [false, true] {
let status = makeStatus(size: size)
apply(presentation(.ready, longCopy: longCopy, countdownSeconds: 30), to: status)
let primary = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel)
let initialTitle = title.text
let initialFrame = primary.convert(primary.bounds, to: status)
var actionCalls = 0
status.onPrimaryAction = { actionCalls += 1 }
XCTAssertNil(find(in: status, suffix: "countdown"))
try assertFullButtonTitle("开始拍摄(30s)", button: primary)
XCTAssertFalse(primary.isEnabled)
try assertReadableContainedContent(in: status)
if !longCopy { capture(status, name: "到达倒计时30秒-\(Int(size.width))x\(Int(size.height))") }
for seconds in [29, 12, 1, 0, -1] {
status.updateCountdown(seconds: seconds)
layoutHierarchy(status)
XCTAssertNil(find(in: status, suffix: "countdown"))
XCTAssertTrue(find(in: status, suffix: "primary") === primary)
try assertFullButtonTitle("开始拍摄(\(max(0, seconds))s)", button: primary)
assertEqual(primary.convert(primary.bounds, to: status), initialFrame, message: "每秒文字刷新保持完整点击区域")
XCTAssertEqual(title.text, initialTitle)
XCTAssertFalse(primary.isEnabled, "倒数到零也不能放开开拍动作")
XCTAssertEqual(actionCalls, 0, "数字更新不能触发开拍或其他主动作")
XCTAssertEqual(status.bounds.size, size)
try assertReadableContainedContent(in: status)
}
if !longCopy { capture(status, name: "到达倒计时0秒-仍待接口更新-\(Int(size.width))x\(Int(size.height))") }
status.updateCountdown(seconds: nil)
layoutHierarchy(status)
XCTAssertNil(find(in: status, suffix: "countdown"))
try assertFullButtonTitle("开始拍摄", button: primary)
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden")
assertEqual(primary.convert(primary.bounds, to: status), initialFrame, message: "清除计时不改变按钮布局")
XCTAssertEqual(actionCalls, 0)
try assertReadableContainedContent(in: status)
}
}
}
/// 未到达及后端切换到其他阶段时清除数字,迟到的界面计时更新也不能重新显示。
func testCountdownOnlyAppearsForReadyAndClearsAfterPhaseChange() throws {
let status = makeStatus(size: compactSize)
apply(presentation(.ready, countdownSeconds: 30), to: status)
XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "开始拍摄(30s)")
XCTAssertNil(find(in: status, suffix: "countdown"))
for phase in phases where phase != .ready {
apply(presentation(phase, countdownSeconds: 30), to: status)
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden", "\(phase)")
XCTAssertFalse((status.diagnosticFields["action_title"] as? String)?.contains("s)") == true)
let actionTitle = status.diagnosticFields["action_title"] as? String
status.updateCountdown(seconds: 12)
layoutHierarchy(status)
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden", "迟到计时不得覆盖 \(phase)")
XCTAssertEqual(status.diagnosticFields["action_title"] as? String, actionTitle)
XCTAssertNil(find(in: status, suffix: "countdown"))
}
apply(presentation(.ready), to: status)
XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "开始拍摄")
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden")
XCTAssertNil(find(in: status, suffix: "countdown"))
let refresh = DroneDockTaskPresentation(phase: .ready, title: "无人机已到达", message: "核对状态",
deviceStatus: "", action: .refresh, actionTitle: "刷新任务状态", isActionEnabled: true, countdownSeconds: 30)
apply(refresh, to: status)
status.updateCountdown(seconds: 12)
layoutHierarchy(status)
XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "刷新任务状态")
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden", "ready 的其他动作不能带开拍倒计时")
}
/// 完成态的说明与标题左对齐,素材按钮全宽;刷新或阶段变化不能绕过操作门禁。
func testCompletionPanelMatchesPrototypeAndKeepsActionGate() async throws {
let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
let previous = scene?.windows.first { $0.isKeyWindow }
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
let host = UIViewController()
window.rootViewController = host
window.makeKeyAndVisible()
defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() }
for size in [compactSize, regularSize] {
let status = makeStatus(size: size)
host.view.addSubview(status)
defer { status.removeFromSuperview() }
let value = DroneDockTaskPresentation(phase: .postShootUploading, title: "拍摄已完成",
message: "本次拍摄已结束,可前往查看素材。\n素材处理中,可在素材库查看进度。",
deviceStatus: "拍摄中 · 电量 90%", action: .materials, actionTitle: "查看素材", isActionEnabled: true)
apply(value, to: status)
window.layoutIfNeeded()
try await Task.sleep(for: .milliseconds(50))
layoutHierarchy(status)
let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel)
let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel)
let button = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
XCTAssertEqual(title.convert(title.bounds, to: status).minX, message.convert(message.bounds, to: status).minX, accuracy: 0.5)
XCTAssertEqual(button.bounds.width, size.width - 32, accuracy: 0.5)
XCTAssertNotNil(button.configuration?.image)
let text = try XCTUnwrap(button.titleLabel)
let image = try XCTUnwrap(button.imageView)
let contentFrame = text.convert(text.bounds, to: button).union(image.convert(image.bounds, to: button))
XCTAssertEqual(contentFrame.midX, button.bounds.midX, accuracy: 1, "素材图标与文字整体居中")
XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "deviceStatus"))))
var calls = 0
status.onPrimaryAction = { calls += 1 }
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, 1)
capture(status, name: "拍摄完成-原型布局-\(Int(size.width))x\(Int(size.height))")
status.apply(value, isRefreshing: true)
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, 1)
XCTAssertFalse(button.isEnabled)
apply(presentation(.failed), to: status)
XCTAssertTrue(isHidden(button), "上传失败必须显示失败状态,不能保留完成操作面板")
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, 1)
XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "completed"))))
try assertReadableContainedContent(in: status)
}
}
/// 失败长原因在固定小屏与真实剩余高度内可展开,主按钮保持全宽且不能触发召唤。
func testFailureReasonDetailsAndDisabledRetryFitFixedAreas() throws {
for size in [compactSize, regularSize, CGSize(width: 402, height: 207.875)] {
let status = makeStatus(size: size)
let value = presentation(.failed, longCopy: true)
apply(value, to: status)
var detailsCalls = 0
var actionCalls = 0
status.onDetails = { detailsCalls += 1 }
status.onPrimaryAction = { actionCalls += 1 }
let details = try XCTUnwrap(find(in: status, suffix: "failureDetails") as? UIButton)
let retry = try XCTUnwrap(find(in: status, suffix: "failureRetry") as? UIButton)
let reason = try XCTUnwrap(find(in: status, suffix: "failureReason") as? UILabel)
XCTAssertEqual(reason.text, "失败原因:\(value.message)")
XCTAssertTrue(details.accessibilityLabel?.contains(value.message) == true)
XCTAssertFalse(isHidden(details))
XCTAssertGreaterThanOrEqual(details.bounds.height, 44)
let center = details.convert(CGPoint(x: details.bounds.midX, y: details.bounds.midY), to: status)
let hit = status.hitTest(center, with: nil)
XCTAssertTrue(hit === details || hit?.isDescendant(of: details) == true)
details.sendActions(for: .touchUpInside)
XCTAssertEqual(detailsCalls, 1)
XCTAssertEqual(retry.configuration?.title, "重新召唤无人机")
XCTAssertFalse(retry.isEnabled)
XCTAssertEqual(retry.bounds.width, details.bounds.width, accuracy: 0.5)
retry.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 0)
XCTAssertNil(find(in: status, suffix: "details"))
try assertReadableContainedContent(in: status)
}
}
/// 状态区只转发已允许的主操作,未接通的开始拍摄按钮不能借布局切换被启用。
func testActionAvailabilitySurvivesLayoutChanges() throws {
let status = makeStatus(size: compactSize)
var actionCalls = 0
status.onPrimaryAction = { actionCalls += 1 }
apply(presentation(.ready), to: status)
let start = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
XCTAssertFalse(start.isEnabled)
start.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 0)
status.frame.size = regularSize
apply(presentation(.readError), to: status)
let refresh = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton)
XCTAssertTrue(refresh.isEnabled)
refresh.sendActions(for: .touchUpInside)
XCTAssertEqual(actionCalls, 1)
try assertReadableContainedContent(in: status)
}
/// 以扣除系统栏后的内容尺寸切换状态,验证真实剩余中间高度及三区稳定性。
func testPageRegionsRemainFixedAcrossStatesAndStaleTelemetry() throws {
// 离线视图没有系统 safe area:小屏扣除状态栏 20 + 导航栏 44,大屏扣除顶部 106 + 底部 34。
let viewports: [(size: CGSize, expectedStatusHeight: CGFloat, screen: String)] = [
(CGSize(width: 375, height: 603), 146.0625, "375x667"),
(CGSize(width: 402, height: 734), 207.875, "402x874")
]
for viewport in viewports {
let size = viewport.size
let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.response()))
let controller = try makeController(service: service, size: size)
let root = try XCTUnwrap(controller.view)
let top = try XCTUnwrap(find(in: root, suffix: "top"))
let status = try XCTUnwrap(find(in: root, suffix: "stateContainer") as? DroneDockTaskStatusView)
let footer = try XCTUnwrap(find(in: root, suffix: "safety"))
let telemetry = try XCTUnwrap(find(in: root, suffix: "telemetry") as? DroneShootingTaskTelemetryView)
let feed = try XCTUnwrap(find(in: root, suffix: "feedPlaceholder"))
XCTAssertTrue(top.superview === root)
XCTAssertTrue(status.superview === root)
XCTAssertTrue(footer.superview === root)
XCTAssertTrue(allViews(in: root).allSatisfy { !($0 is UIScrollView) })
let stableIDs = ["top", "summary", "feedPlaceholder", "telemetry", "stateContainer", "safety"]
let initial = try regionFrames(in: root, suffixes: stableIDs)
XCTAssertEqual(status.bounds.height, viewport.expectedStatusHeight, accuracy: 0.5)
XCTAssertEqual(top.frame.maxY, status.frame.minY, accuracy: 0.5)
XCTAssertEqual(status.frame.maxY, footer.frame.minY, accuracy: 0.5)
XCTAssertEqual(feed.bounds.height, feed.bounds.width * 9 / 16, accuracy: 0.5)
assertContained(top, in: root)
assertContained(status, in: root)
assertContained(footer, in: root)
for suffix in ["summary", "feedPlaceholder", "telemetry"] {
assertContained(try XCTUnwrap(find(in: root, suffix: suffix)), in: top)
}
for suffix in ["pause", "return"] {
let button = try XCTUnwrap(find(in: footer, suffix: suffix) as? UIButton)
XCTAssertFalse(button.isEnabled)
XCTAssertGreaterThanOrEqual(button.bounds.height, 44)
XCTAssertGreaterThanOrEqual(button.bounds.width, 44)
assertContained(button, in: footer)
}
for phase in phases {
apply(presentation(phase, longCopy: phase == .readError), to: status)
UIView.performWithoutAnimation {
telemetry.apply(values: ["93%", "10.3℃", "0m/s", "无雨", "信号良好", "32颗"],
isStale: phase == .loading || phase == .readError,
accessibilityPrefix: "drone.task.remote.metric")
layoutHierarchy(root)
}
let current = try regionFrames(in: root, suffixes: stableIDs)
for suffix in stableIDs {
assertEqual(try XCTUnwrap(current[suffix]), try XCTUnwrap(initial[suffix]),
message: "\(Int(size.width))×\(Int(size.height)) \(phase) \(suffix)")
}
try assertReadableContainedContent(in: status)
}
XCTAssertTrue(service.requests.isEmpty, "仅布局测试不得触发网络读取")
capture(root, name: "任务固定三区-内容\(Int(size.width))x\(Int(size.height))-屏幕\(viewport.screen)-长错误文案")
}
}
/// 将常规、紧凑及长错误文案保存为 XCTest 图片附件供模拟器视觉复核。
func testCaptureRegularCompactAndLongErrorAttachments() throws {
let samples: [(CGSize, DroneDockTaskPresentation, String)] = [
(regularSize, presentation(.ready), "状态区-常规402x220-准备就绪"),
(compactSize, presentation(.shooting), "状态区-紧凑375x146-拍摄中"),
(compactSize, presentation(.readError, longCopy: true), "状态区-紧凑375x146-超长错误"),
(regularSize, presentation(.failed), "状态区-常规402x220-任务执行失败"),
(compactSize, presentation(.failed, longCopy: true), "状态区-紧凑375x146-失败长原因"),
(CGSize(width: 402, height: 207.875), presentation(.failed), "状态区-实际402x208-任务执行失败")
]
for (size, value, name) in samples {
let status = makeStatus(size: size)
apply(value, to: status)
try assertReadableContainedContent(in: status)
capture(status, name: name)
}
}
private func makeStatus(size: CGSize) -> DroneDockTaskStatusView {
let status = DroneDockTaskStatusView(frame: CGRect(origin: .zero, size: size))
status.overrideUserInterfaceStyle = .light
return status
}
private func apply(_ presentation: DroneDockTaskPresentation, to status: DroneDockTaskStatusView) {
UIView.performWithoutAnimation {
status.apply(presentation)
layoutHierarchy(status)
}
}
private func presentation(_ phase: DroneDockTaskDisplayPhase, longCopy: Bool = false,
countdownSeconds: Int? = nil) -> DroneDockTaskPresentation {
let title: String
let action: DroneDockTaskDisplayAction
let actionTitle: String?
let enabled: Bool
switch phase {
case .loading: (title, action, actionTitle, enabled) = ("正在获取任务状态", .none, nil, false)
case .navigating: (title, action, actionTitle, enabled) = ("无人机正在前往点位", .refresh, "刷新任务状态", true)
case .ready: (title, action, actionTitle, enabled) = ("无人机已到达", .start, "开始拍摄", false)
case .shooting: (title, action, actionTitle, enabled) = ("无人机正在拍摄中", .none, "拍摄中", false)
case .postShootUploading: (title, action, actionTitle, enabled) = ("拍摄已完成", .materials, "查看素材", true)
case .postShootUploadFailed: (title, action, actionTitle, enabled) = ("素材上传失败", .materials, "查看素材", true)
case .paused: (title, action, actionTitle, enabled) = ("无人机已暂停", .resume, "继续任务", true)
case .returning: (title, action, actionTitle, enabled) = ("无人机正在返航", .none, "拍摄已中断", false)
case .returned: (title, action, actionTitle, enabled) = ("本次拍摄已中断", .retry, "重新召唤无人机", true)
case .completed: (title, action, actionTitle, enabled) = ("本次拍摄已完成", .materials, "查看素材", true)
case .failed: (title, action, actionTitle, enabled) = ("任务执行失败", .retry, "重新召唤无人机", false)
case .blocked: (title, action, actionTitle, enabled) = ("当前无法继续拍摄", .refresh, "刷新任务状态", true)
case .unknown: (title, action, actionTitle, enabled) = ("状态待确认", .refresh, "刷新任务状态", true)
case .readError: (title, action, actionTitle, enabled) = ("任务状态读取失败", .refresh, "重新加载", true)
}
let longTitle = String(repeating: "航线任务状态需要确认,", count: 8)
let longMessage = String(repeating: "服务端返回的完整错误说明需要保留供工作人员查看,请检查任务和设备状态。", count: 12)
return DroneDockTaskPresentation(phase: phase, title: longCopy && phase != .failed ? longTitle : title,
message: longCopy ? longMessage : phase == .failed ? "拍摄指令执行失败"
: phase == .shooting ? "请关注现场及实时画面。\n请勿关闭本页或息屏。" : "请确认当前状态后继续操作。",
deviceStatus: "空闲 · 电量 93%", action: action, actionTitle: actionTitle, isActionEnabled: enabled,
actionNote: phase == .failed ? "无人机离线,暂不可召唤" : nil,
countdownSeconds: countdownSeconds)
}
private func makeController(service: any DroneDockShootingServing, size: CGSize) throws -> DroneDockShootingTaskViewController {
let context = DroneDockShootingTaskTestData.context()
let model = DroneDockShootingTaskViewModel(context: context, taskID: 501,
order: try DroneDockShootingTaskTestData.order(), service: service, currentContext: { context })
let controller = DroneDockShootingTaskViewController(viewModel: model)
UIView.performWithoutAnimation {
controller.loadViewIfNeeded()
controller.view.frame = CGRect(origin: .zero, size: size)
layoutHierarchy(controller.view)
controller.viewDidLayoutSubviews()
layoutHierarchy(controller.view)
}
return controller
}
private func assertReadableContainedContent(in status: DroneDockTaskStatusView,
file: StaticString = #filePath, line: UInt = #line) throws {
XCTAssertEqual(status.transform, .identity, file: file, line: line)
XCTAssertGreaterThanOrEqual(status.effectiveScale, 0.8, file: file, line: line)
XCTAssertLessThanOrEqual(status.effectiveScale, 1, file: file, line: line)
XCTAssertTrue(allViews(in: status).allSatisfy { !($0 is UIScrollView) }, file: file, line: line)
for view in allViews(in: status) where view !== status && !isHidden(view) && !view.bounds.isEmpty {
assertContained(view, in: status, file: file, line: line)
if let label = view as? UILabel {
XCTAssertGreaterThanOrEqual(label.font.pointSize, 12, file: file, line: line)
if label.adjustsFontSizeToFitWidth {
XCTAssertGreaterThanOrEqual(label.font.pointSize * label.minimumScaleFactor, 12, file: file, line: line)
}
}
if let button = view as? UIButton {
XCTAssertGreaterThanOrEqual(button.bounds.height, 44, file: file, line: line)
XCTAssertGreaterThanOrEqual(button.bounds.width, 44, file: file, line: line)
if let title = button.currentTitle, !title.isEmpty {
let label = try XCTUnwrap(button.titleLabel, file: file, line: line)
XCTAssertEqual(label.text, title, file: file, line: line)
XCTAssertFalse(label.bounds.isEmpty, file: file, line: line)
XCTAssertFalse(isHidden(label), file: file, line: line)
}
}
}
XCTAssertNil(find(in: status, suffix: "details"), file: file, line: line)
let failure = try XCTUnwrap(find(in: status, suffix: "failure"), file: file, line: line)
if !isHidden(failure) {
let details = try XCTUnwrap(find(in: status, suffix: "failureDetails") as? UIButton, file: file, line: line)
XCTAssertFalse(isHidden(details), file: file, line: line)
}
}
private func assertContained(_ view: UIView, in container: UIView,
file: StaticString = #filePath, line: UInt = #line) {
let frame = view.convert(view.bounds, to: container)
XCTAssertTrue(container.bounds.insetBy(dx: -0.5, dy: -0.5).contains(frame),
"\(view.accessibilityIdentifier ?? String(describing: type(of: view))) 越界:\(frame),容器:\(container.bounds)",
file: file, line: line)
}
/// 同时核对模型标题和 UILabel 的实际内容、文字宽度,避免秒数被尾部裁切。
private func assertFullButtonTitle(_ expected: String, button: UIButton,
file: StaticString = #filePath, line: UInt = #line) throws {
XCTAssertEqual(button.title(for: .normal), expected, file: file, line: line)
let label = try XCTUnwrap(button.titleLabel, file: file, line: line)
XCTAssertEqual(label.text, expected, file: file, line: line)
let size = (expected as NSString).size(withAttributes: [.font: label.font as Any])
XCTAssertGreaterThanOrEqual(label.bounds.width + 1, ceil(size.width), "按钮标题不能裁切秒数", file: file, line: line)
XCTAssertGreaterThanOrEqual(button.bounds.height, 44, file: file, line: line)
}
private func assertEqual(_ lhs: CGRect, _ rhs: CGRect, message: String,
file: StaticString = #filePath, line: UInt = #line) {
XCTAssertEqual(lhs.origin.x, rhs.origin.x, accuracy: 0.5, message, file: file, line: line)
XCTAssertEqual(lhs.origin.y, rhs.origin.y, accuracy: 0.5, message, file: file, line: line)
XCTAssertEqual(lhs.size.width, rhs.size.width, accuracy: 0.5, message, file: file, line: line)
XCTAssertEqual(lhs.size.height, rhs.size.height, accuracy: 0.5, message, file: file, line: line)
}
private func regionFrames(in root: UIView, suffixes: [String]) throws -> [String: CGRect] {
var frames: [String: CGRect] = [:]
for suffix in suffixes {
let view = try XCTUnwrap(find(in: root, suffix: suffix), "缺少固定区域 \(suffix)")
frames[suffix] = view.convert(view.bounds, to: root)
}
return frames
}
private func allViews(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews(in: $0) } }
private func isHidden(_ view: UIView) -> Bool { view.isHidden || view.alpha < 0.01 || (view.superview.map(isHidden) ?? false) }
private func find(in root: UIView, suffix: String) -> UIView? {
allViews(in: root).first { $0.accessibilityIdentifier == "drone.task.remote.\(suffix)" }
}
/// 离线布局完成后显式刷新按钮标题图层,避免截图落在标题切换的过渡帧。
private func layoutHierarchy(_ view: UIView) {
view.setNeedsLayout()
view.layoutIfNeeded()
for child in view.subviews { layoutHierarchy(child) }
if let button = view as? UIButton {
button.layoutIfNeeded()
button.titleLabel?.setNeedsLayout()
button.titleLabel?.layoutIfNeeded()
button.titleLabel?.layer.setNeedsDisplay()
button.titleLabel?.layer.displayIfNeeded()
}
}
private func capture(_ view: UIView, name: String) {
UIView.performWithoutAnimation { layoutHierarchy(view) }
let image = UIGraphicsImageRenderer(bounds: view.bounds).image { context in
view.layer.render(in: context.cgContext)
}
let attachment = XCTAttachment(image: image)
attachment.name = name
attachment.lifetime = .keepAlways
add(attachment)
}
}