feat(drone-dock): 展示首页真实拍摄订单

This commit is contained in:
2026-10-27 17:58:30 +08:00
parent 2db4ad8e69
commit f7a2a19dee
6 changed files with 552 additions and 42 deletions
@@ -2,7 +2,7 @@ import UIKit
import XCTest
@testable import suixinkan
/// 在真机窗口验证正式首页的真实空态、错误显示和演示流程隔离,网络全部使用替身。
/// 在测试窗口验证正式首页的真实数据、空态、错误显示和演示流程隔离,网络全部使用替身。
@MainActor
final class DroneDockRemoteHomeViewTests: XCTestCase {
private weak var previousKeyWindow: UIWindow?
@@ -186,6 +186,205 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
capture(window, named: "机巢真实首页-多设备横向卡片")
}
/// 首次返回设备和多条订单时仍停留页首,避免 Diffable 将页面锚定到新增订单之后。
func testInitialHomeWithEightOrdersKeepsScenicContextAndDeviceVisible() async throws {
var envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: populatedEnvelope) as? [String: Any])
var data = try XCTUnwrap(envelope["data"] as? [String: Any])
data["orders"] = (701...708).map { orderRecord(id: $0) }
envelope["data"] = data
let (controller, session) = makeController(responses: [try JSONSerialization.data(withJSONObject: envelope)])
let window = makeWindow(root: controller)
defer { close(window) }
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
try await settle(window: window) {
collection.numberOfItems(inSection: 2) == 8
&& !collection.hasUncommittedUpdates
&& abs(collection.contentOffset.y + collection.adjustedContentInset.top) < 1
&& self.find(in: controller.view, identifier: "drone.device.58") != nil
}
XCTAssertEqual(collection.contentOffset.y, -collection.adjustedContentInset.top, accuracy: 1)
XCTAssertEqual(collection.numberOfItems(inSection: 2), 8)
let visibleFrame = collection.bounds.inset(by: collection.adjustedContentInset)
let contextFrame = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))).frame
let deviceFrame = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))).frame
XCTAssertTrue(visibleFrame.contains(contextFrame), "首次加载后景区信息应完整位于可见区域")
XCTAssertTrue(visibleFrame.contains(deviceFrame), "首次加载后设备卡片应完整位于可见区域")
XCTAssertTrue(visibleTexts(in: controller.view).contains("测试景区 · 测试工作人员"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("测试机巢M4D"))
XCTAssertEqual(session.requests.count, 1)
assertOnlyReadHomeRequests(session)
}
/// 首页按服务端顺序呈现每条订单,字段来自响应,不替换成演示游客或套餐。
func testOrdersDisplayServerFieldsAndPreserveServerOrder() async throws {
let orders = [orderRecord(id: 703), orderRecord(id: 701), orderRecord(id: 702)]
let (controller, session) = makeController(responses: [try orderEnvelope(orders)])
let window = makeWindow(root: controller)
defer { close(window) }
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
try await settle(window: window) { collection.numberOfItems(inSection: 2) == 3 }
for (index, id) in [703, 701, 702].enumerated() {
let card = try await orderCard(at: index, id: id, in: collection, window: window)
let texts = visibleTexts(in: card)
XCTAssertTrue(texts.contains("游客 130****0001"))
XCTAssertTrue(texts.contains("订单号 TEST-ORDER-\(id)"))
XCTAssertTrue(texts.contains("测试单次航拍 · 含 1 次拍摄"))
XCTAssertTrue(texts.contains("待拍摄"))
XCTAssertTrue(texts.contains("已拍摄 0/1 次,剩余 1 次"))
XCTAssertTrue(texts.contains("开始拍摄"))
XCTAssertFalse(texts.contains("查看素材 ›"))
assertUnambiguousVisibleLayout(in: card)
}
XCTAssertFalse(visibleTexts(in: controller.view).contains("订单信息暂不可用"))
XCTAssertEqual(session.requests.count, 1)
assertOnlyReadHomeRequests(session)
capture(window, named: "机巢真实首页-订单游客套餐状态与次数")
}
/// 同一订单刷新会更新剩余次数与按钮状态,服务端移除的订单和空列表不会残留旧卡片。
func testOrderRefreshUpdatesExistingCardAndRemovesDeletedOrders() async throws {
var completed = orderRecord(id: 701)
completed["status_label"] = "已完成"
completed["shot_used"] = 1
completed["shot_remain"] = 0
completed["progress_text"] = "已拍摄 1/1 次,剩余 0 次"
completed["primary_action"] = "blocked"
completed["primary_action_label"] = "拍摄次数已用完"
let responses = try [
orderEnvelope([orderRecord(id: 701), orderRecord(id: 702)]),
orderEnvelope([completed]), orderEnvelope([])
]
let (controller, session) = makeController(responses: responses)
let window = makeWindow(root: controller)
defer { close(window) }
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
try await settle(window: window) { collection.numberOfItems(inSection: 2) == 2 }
_ = try await orderCard(at: 0, id: 701, in: collection, window: window)
let refresh = try XCTUnwrap(collection.refreshControl)
refresh.sendActions(for: .valueChanged)
try await settle(window: window) {
collection.numberOfItems(inSection: 2) == 1
&& self.visibleTexts(in: controller.view).contains("已拍摄 1/1 次,剩余 0 次")
}
let card = try await orderCard(at: 0, id: 701, in: collection, window: window)
XCTAssertTrue(visibleTexts(in: card).contains("已完成"))
XCTAssertFalse(visibleTexts(in: card).contains("已拍摄 0/1 次,剩余 1 次"))
let button = try XCTUnwrap(find(in: card, identifier: "drone.home.order.701.primary") as? UIButton)
XCTAssertFalse(button.isEnabled)
XCTAssertEqual(visibleOrderCardIdentifiers(in: collection), ["drone.home.order.701"])
XCTAssertEqual(controller.viewModel.response?.orders.map(\.orderID), [701])
assertUnambiguousVisibleLayout(in: card)
refresh.sendActions(for: .valueChanged)
try await settle(window: window) { self.visibleTexts(in: controller.view).contains("暂无待拍摄订单") }
XCTAssertEqual(collection.numberOfItems(inSection: 2), 1)
XCTAssertTrue(visibleOrderCardIdentifiers(in: collection).isEmpty)
XCTAssertTrue(controller.viewModel.response?.orders.isEmpty == true)
XCTAssertEqual(session.requests.count, 3)
assertOnlyReadHomeRequests(session)
}
/// 真实订单的拍摄按钮只说明待接入流程,不进入演示任务或发送设备控制请求。
func testOrderShootingActionOnlyShowsIntegrationNotice() async throws {
let (controller, session) = makeController(responses: [try orderEnvelope([orderRecord(id: 701)])])
let window = makeWindow(root: controller)
defer { close(window) }
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
try await settle(window: window) { self.find(in: controller.view, identifier: "drone.home.order.701") != nil }
let card = try await orderCard(at: 0, id: 701, in: collection, window: window)
let button = try XCTUnwrap(find(in: card, identifier: "drone.home.order.701.primary") as? UIButton)
XCTAssertTrue(button.isEnabled)
button.sendActions(for: .touchUpInside)
try await settle(window: window) { controller.presentedViewController is UIAlertController }
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
XCTAssertEqual(alert.title, "开始拍摄")
XCTAssertEqual(alert.message, "拍摄流程暂未接入,请稍后再试")
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
XCTAssertEqual(session.requests.count, 1)
assertOnlyReadHomeRequests(session)
}
/// 刷新后的缺失信息清除旧游客、套餐、次数和操作,不将未知拍摄次数伪装为零。
func testMissingOrderFieldsClearPreviousDisplayWithoutInventingCounts() async throws {
let minimal: [String: Any] = ["order_id": 701, "order_number": "TEST-ORDER-701"]
let (controller, session) = makeController(responses: try [
orderEnvelope([orderRecord(id: 701)]), orderEnvelope([minimal])
])
let window = makeWindow(root: controller)
defer { close(window) }
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
try await settle(window: window) { self.find(in: controller.view, identifier: "drone.home.order.701") != nil }
_ = try await orderCard(at: 0, id: 701, in: collection, window: window)
try XCTUnwrap(collection.refreshControl).sendActions(for: .valueChanged)
try await settle(window: window) { self.visibleTexts(in: controller.view).contains("游客信息待确认") }
let card = try await orderCard(at: 0, id: 701, in: collection, window: window)
let texts = visibleTexts(in: card)
XCTAssertTrue(texts.contains("套餐信息待确认"))
XCTAssertTrue(texts.contains("状态待确认"))
XCTAssertTrue(texts.contains { $0.contains("—") })
XCTAssertFalse(texts.contains("游客 130****0001"))
XCTAssertFalse(texts.contains("测试单次航拍 · 含 1 次拍摄"))
XCTAssertFalse(texts.contains { $0.contains("0/1") || $0.contains("0/0") })
if let button = find(in: card, identifier: "drone.home.order.701.primary") {
XCTAssertTrue(isHiddenByAncestor(button))
}
assertUnambiguousVisibleLayout(in: card)
XCTAssertEqual(session.requests.count, 2)
assertOnlyReadHomeRequests(session)
}
/// 与实际 home 订单字段一致的匿名夹具,避免将游客或业务订单信息写入仓库。
private func orderRecord(id: Int) -> [String: Any] {
[
"order_id": id, "order_number": "TEST-ORDER-\(id)", "user_id": 901,
"tourist_label": "游客 130****0001", "tourist_phone_mask": "130****0001",
"package_name": "测试单次航拍 · 含 1 次拍摄", "status_label": "待拍摄",
"shot_total": 1, "shot_used": 0, "shot_remain": 1,
"progress_text": "已拍摄 0/1 次,剩余 1 次", "media_status": "none",
"media_status_label": "", "primary_action": "start_shoot", "primary_action_label": "开始拍摄"
]
}
/// 为订单展示单独构造成功响应,设备为空以便在测试窗口观察卡片。
private func orderEnvelope(_ orders: [[String: Any]]) throws -> Data {
var envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: emptyEnvelope) as? [String: Any])
var data = try XCTUnwrap(envelope["data"] as? [String: Any])
data["orders"] = orders
envelope["data"] = data
return try JSONSerialization.data(withJSONObject: envelope)
}
/// 滚动到指定服务端顺序的订单,等待实际复用卡片出现再检查内容。
private func orderCard(at index: Int, id: Int, in collection: UICollectionView, window: UIWindow) async throws -> UICollectionViewCell {
let path = IndexPath(item: index, section: 2)
collection.scrollToItem(at: path, at: .centeredVertically, animated: false)
try await settle(window: window) {
collection.cellForItem(at: path)?.accessibilityIdentifier == "drone.home.order.\(id)"
}
return try XCTUnwrap(collection.cellForItem(at: path))
}
/// 只读取当前可见索引对应的订单卡,排除集合视图复用池中暂存的已删除单元格。
private func visibleOrderCardIdentifiers(in collection: UICollectionView) -> [String] {
collection.indexPathsForVisibleItems.filter { $0.section == 2 }.sorted().compactMap { path in
guard let cell = collection.cellForItem(at: path), !isHiddenByAncestor(cell),
let identifier = cell.accessibilityIdentifier, identifier.hasPrefix("drone.home.order.") else { return nil }
return identifier
}
}
/// 检查实际展示的卡片内容约束,隐藏素材栏和按钮不参与可见布局检查。
private func assertUnambiguousVisibleLayout(in card: UIView, file: StaticString = #filePath, line: UInt = #line) {
let ambiguous = allViews(in: card).filter { !isHiddenByAncestor($0) && $0.hasAmbiguousLayout }
XCTAssertTrue(ambiguous.isEmpty, "订单卡片存在布局歧义:\(ambiguous.map { String(describing: type(of: $0)) })", file: file, line: line)
}
/// 服务端确定的六项读数键,按标识查找而不依赖数组排序。
private var metricKeys: [String] { ["battery", "env_temp", "wind_speed", "rainfall", "signal", "satellite"] }
@@ -232,12 +431,12 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
return values
}
/// 与实际控制台响应结构一致的成功空数据,不依赖当前真机账户。
/// 与实际控制台响应结构一致的成功空数据,不依赖当前登录账户。
private var emptyEnvelope: Data {
Data(#"{"code":100000,"msg":"success","data":{"scenic_id":128,"airports":[],"orders":[],"today":{"finished_shoot":0,"order_amount":0,"order_count":0}}}"#.utf8)
}
/// 创建只接替身网络的正式首页,不读取或修改真机登录状态。
/// 创建只接替身网络的正式首页,不读取或修改当前登录状态。
private func makeController(responses: [Data]) -> (DroneDockHomeViewController, MockURLSession) {
let context = DroneDockHomeContext(
userID: "remote-home-ui-test", accountType: "store_user", scenicID: 128,
@@ -253,7 +452,7 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
}), session)
}
/// 创建临时真机窗口,结束后恢复原窗口。
/// 创建临时测试窗口,结束后恢复原窗口。
private func makeWindow(root: UIViewController) -> UIWindow {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
@@ -322,7 +521,7 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" && $0.url?.path == "/api/app/airport/home" }, file: file, line: line)
}
/// 保存测试窗口截图到真机 xcresult,便于核对空态样式。
/// 保存测试窗口截图到 xcresult,便于核对页面样式。
private func capture(_ window: UIWindow, named name: String) {
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)