555 lines
32 KiB
Swift
555 lines
32 KiB
Swift
import UIKit
|
||
import XCTest
|
||
@testable import suixinkan
|
||
|
||
/// 在测试窗口验证正式首页的真实数据、空态、错误显示和演示流程隔离,网络全部使用替身。
|
||
@MainActor
|
||
final class DroneDockRemoteHomeViewTests: XCTestCase {
|
||
private weak var previousKeyWindow: UIWindow?
|
||
|
||
/// 成功空响应显示接口零值,不混入演示设备、订单或演示统计。
|
||
func testSuccessfulEmptyHomeDisplaysZeroStatisticsWithoutDemoData() async throws {
|
||
let (controller, session) = makeController(responses: [emptyEnvelope])
|
||
let window = makeWindow(root: controller)
|
||
defer { close(window) }
|
||
|
||
try await settle(window: window) {
|
||
self.visibleTexts(in: controller.view).contains("¥0.00")
|
||
&& self.visibleTexts(in: controller.view).contains("暂无待拍摄订单")
|
||
}
|
||
|
||
let texts = visibleTexts(in: controller.view)
|
||
XCTAssertEqual(controller.title, "机巢工作台")
|
||
XCTAssertTrue(texts.contains("测试景区 · 测试工作人员"))
|
||
XCTAssertTrue(texts.contains("暂无无人机"))
|
||
XCTAssertTrue(texts.contains("成交订单"))
|
||
XCTAssertTrue(texts.contains("成交金额"))
|
||
XCTAssertTrue(texts.contains("完成拍摄"))
|
||
XCTAssertEqual(texts.filter { $0 == "0" }.count, 2)
|
||
XCTAssertFalse(texts.contains("演示状态 ⌄"))
|
||
XCTAssertFalse(texts.contains("01号无人机"))
|
||
XCTAssertFalse(texts.contains("¥1,896"))
|
||
XCTAssertTrue(controller.viewModel.response?.airports.isEmpty == true)
|
||
XCTAssertTrue(controller.viewModel.response?.orders.isEmpty == true)
|
||
assertOnlyReadHomeRequests(session)
|
||
capture(window, named: "机巢真实首页-成功空态和零值统计")
|
||
}
|
||
|
||
/// 接口失败显示重试信息,不能展示成功空态或虚构零值。
|
||
func testFailedHomeShowsErrorInsteadOfEmptyDataOrZeroStatistics() async throws {
|
||
let errorEnvelope = try TestJSON.errorEnvelope(code: 160001, msg: "机巢首页暂不可用")
|
||
let (controller, session) = makeController(responses: [errorEnvelope])
|
||
let window = makeWindow(root: controller)
|
||
defer { close(window) }
|
||
|
||
try await settle(window: window) {
|
||
self.visibleTexts(in: controller.view).contains("首页加载失败")
|
||
}
|
||
|
||
let texts = visibleTexts(in: controller.view)
|
||
XCTAssertTrue(texts.contains { $0.contains("机巢首页暂不可用") && $0.contains("请下拉重试") })
|
||
XCTAssertFalse(texts.contains("暂无无人机"))
|
||
XCTAssertFalse(texts.contains("暂无待拍摄订单"))
|
||
XCTAssertFalse(texts.contains("¥0.00"))
|
||
XCTAssertFalse(texts.contains("0"))
|
||
XCTAssertEqual(texts.filter { $0 == "—" }.count, 3)
|
||
XCTAssertNil(controller.viewModel.response)
|
||
assertOnlyReadHomeRequests(session)
|
||
}
|
||
|
||
/// 订单入口仍明确未开放,收款入口进入独立真实收款页,二者均不进入演示流程。
|
||
func testOrderAndReceiptEntriesStayOutOfDemoFlows() async throws {
|
||
let (controller, session) = makeController(responses: Array(repeating: emptyEnvelope, count: 4))
|
||
let window = makeWindow(root: controller)
|
||
defer { close(window) }
|
||
|
||
try await settle(window: window) {
|
||
self.visibleTexts(in: controller.view).contains("暂无待拍摄订单")
|
||
&& self.find(in: controller.view, identifier: "drone.home.allOrders") != nil
|
||
}
|
||
|
||
let viewAll = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.allOrders") as? UIButton)
|
||
XCTAssertTrue(viewAll.isEnabled)
|
||
viewAll.sendActions(for: .touchUpInside)
|
||
try await settle(window: window) {
|
||
(controller.presentedViewController as? UIAlertController)?.title == "拍摄订单"
|
||
}
|
||
XCTAssertEqual((controller.presentedViewController as? UIAlertController)?.message, "该功能暂未开放")
|
||
XCTAssertEqual(controller.navigationController?.viewControllers.count, 1)
|
||
XCTAssertTrue(controller.navigationController?.topViewController === controller)
|
||
|
||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||
controller.dismiss(animated: false) { continuation.resume() }
|
||
}
|
||
try await settle(window: window) { controller.presentedViewController == nil }
|
||
|
||
let receipt = try XCTUnwrap(controller.navigationItem.rightBarButtonItem)
|
||
XCTAssertEqual(receipt.accessibilityIdentifier, "drone.home.receipt")
|
||
let action = try XCTUnwrap(receipt.action)
|
||
XCTAssertTrue(UIApplication.shared.sendAction(action, to: receipt.target, from: receipt, for: nil))
|
||
try await settle(window: window) {
|
||
controller.navigationController?.topViewController is DroneDockPaymentViewController
|
||
&& controller.navigationController?.transitionCoordinator == nil
|
||
}
|
||
let payment = try XCTUnwrap(controller.navigationController?.topViewController as? DroneDockPaymentViewController)
|
||
XCTAssertEqual(controller.navigationController?.viewControllers.count, 2)
|
||
XCTAssertNil(controller.presentedViewController)
|
||
XCTAssertEqual(payment.viewModel.context.scenicID, 128)
|
||
XCTAssertNil(payment.viewModel.payCode)
|
||
XCTAssertNotNil(find(in: payment.view, identifier: "drone.payment.projectPicker"))
|
||
assertOnlyReadHomeRequests(session)
|
||
}
|
||
|
||
/// 真实机巢样例按服务端名称、状态展示;尚无遥测时六项读数都保持未知。
|
||
func testRealAirportDisplaysServerNameStatusAndUnknownMetrics() async throws {
|
||
let (controller, session) = makeController(responses: [populatedEnvelope])
|
||
let window = makeWindow(root: controller)
|
||
defer { close(window) }
|
||
|
||
try await settle(window: window) {
|
||
self.find(in: controller.view, identifier: "drone.device.58") != nil
|
||
&& self.metricTexts(in: controller.view).count == 6
|
||
}
|
||
|
||
let card = try XCTUnwrap(find(in: controller.view, identifier: "drone.device.58"))
|
||
let texts = visibleTexts(in: card)
|
||
XCTAssertTrue(texts.contains("测试机巢M4D"))
|
||
XCTAssertTrue(texts.contains("空闲"))
|
||
XCTAssertEqual(metricTexts(in: card), Dictionary(uniqueKeysWithValues: metricKeys.map { ($0, "—") }))
|
||
XCTAssertFalse(visibleTexts(in: controller.view).contains("设备信息暂不可用"))
|
||
XCTAssertFalse(visibleTexts(in: controller.view).contains("暂无无人机"))
|
||
assertOnlyReadHomeRequests(session)
|
||
capture(window, named: "机巢真实首页-设备名称状态与未知读数")
|
||
}
|
||
|
||
/// 同一机巢刷新时保留合法零值,之后读数变未知会清除旧值而不残留在复用卡片里。
|
||
func testDeviceRefreshKeepsZeroValuesAndClearsUnavailableReadings() async throws {
|
||
let nonzero: [String: (Double, String)] = [
|
||
"battery": (88, "88%"), "env_temp": (21.5, "21.5°C"), "wind_speed": (4.2, "4.2m/s"),
|
||
"rainfall": (1, "小雨"), "signal": (4, "良好"), "satellite": (32, "32颗")
|
||
]
|
||
let zero: [String: (Double, String)] = [
|
||
"battery": (0, "0%"), "env_temp": (0, "0°C"), "wind_speed": (0, "0m/s"),
|
||
"rainfall": (0, "0"), "signal": (0, "0"), "satellite": (0, "0颗")
|
||
]
|
||
let responses = try [deviceEnvelope(metricValues: nonzero), deviceEnvelope(metricValues: zero), populatedEnvelope]
|
||
let (controller, session) = makeController(responses: responses)
|
||
let window = makeWindow(root: controller)
|
||
defer { close(window) }
|
||
|
||
try await settle(window: window) { self.metricTexts(in: controller.view) == nonzero.mapValues { $0.1 } }
|
||
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
|
||
let refresh = try XCTUnwrap(collection.refreshControl)
|
||
refresh.sendActions(for: .valueChanged)
|
||
try await settle(window: window) { self.metricTexts(in: controller.view) == zero.mapValues { $0.1 } }
|
||
|
||
XCTAssertEqual(session.requests.count, 2)
|
||
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
|
||
refresh.sendActions(for: .valueChanged)
|
||
let unknown = Dictionary(uniqueKeysWithValues: metricKeys.map { ($0, "—") })
|
||
try await settle(window: window) { self.metricTexts(in: controller.view) == unknown }
|
||
|
||
XCTAssertEqual(session.requests.count, 3)
|
||
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
|
||
XCTAssertNotNil(find(in: controller.view, identifier: "drone.device.58"))
|
||
assertOnlyReadHomeRequests(session)
|
||
}
|
||
|
||
/// 从单机刷新为多机时完整应用设备列表,并切换为能提示横向浏览的卡片宽度。
|
||
func testRefreshingFromOneToTwoAirportsUpdatesCarousel() async throws {
|
||
let (controller, session) = makeController(responses: [populatedEnvelope, try deviceEnvelope(addSecondAirport: true)])
|
||
let window = makeWindow(root: controller)
|
||
defer { close(window) }
|
||
|
||
try await settle(window: window) { self.find(in: controller.view, identifier: "drone.device.58") != nil }
|
||
let collection = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.remote.list") as? UICollectionView)
|
||
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
|
||
let devicePath = IndexPath(item: 0, section: 1)
|
||
let singleWidth = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: devicePath)).frame.width
|
||
|
||
let refresh = try XCTUnwrap(collection.refreshControl)
|
||
refresh.sendActions(for: .valueChanged)
|
||
try await settle(window: window) {
|
||
collection.numberOfItems(inSection: 1) == 2
|
||
&& (collection.collectionViewLayout.layoutAttributesForItem(at: devicePath)?.frame.width ?? singleWidth) < singleWidth
|
||
&& (self.find(in: controller.view, identifier: "drone.home.devicePages") as? UIPageControl)?.numberOfPages == 2
|
||
}
|
||
|
||
let multipleWidth = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: devicePath)).frame.width
|
||
XCTAssertGreaterThan(multipleWidth, 0)
|
||
XCTAssertLessThan(multipleWidth, singleWidth)
|
||
XCTAssertEqual(controller.viewModel.response?.airports.count, 2)
|
||
let pages = try XCTUnwrap(find(in: controller.view, identifier: "drone.home.devicePages") as? UIPageControl)
|
||
XCTAssertEqual(pages.currentPage, 0)
|
||
XCTAssertEqual(session.requests.count, 2)
|
||
assertOnlyReadHomeRequests(session)
|
||
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 testOrderShootingActionOpensRealPreparationForSelectedOrder() async throws {
|
||
var preparationSession: MockURLSession?
|
||
let (controller, session) = makeController(responses: [try orderEnvelope([orderRecord(id: 701)])], preparationControllerFactory: { order, context in
|
||
let result = try! DroneDockPreparationViewFixtures.controller(context: context, order: order)
|
||
preparationSession = result.1
|
||
return result.0
|
||
})
|
||
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.navigationController?.topViewController as? DroneDockRemotePreparationViewController)?.viewModel.response != nil
|
||
&& controller.navigationController?.transitionCoordinator == nil
|
||
}
|
||
let preparation = try XCTUnwrap(controller.navigationController?.topViewController as? DroneDockRemotePreparationViewController)
|
||
XCTAssertEqual(preparation.viewModel.order.orderID, 701)
|
||
XCTAssertEqual(preparation.viewModel.order.orderNumber, "TEST-ORDER-701")
|
||
XCTAssertEqual(preparation.viewModel.context.scenicID, 128)
|
||
XCTAssertEqual(preparation.viewModel.context.storeID, 37)
|
||
XCTAssertEqual(preparation.viewModel.response?.orderNumber, "TEST-ORDER-701")
|
||
XCTAssertEqual(controller.navigationController?.viewControllers.count, 2)
|
||
XCTAssertNil(controller.presentedViewController)
|
||
XCTAssertFalse(try XCTUnwrap(find(in: preparation.view, identifier: "drone.preparation.summon") as? UIButton).isEnabled)
|
||
let request = try XCTUnwrap(preparationSession?.requests.first)
|
||
XCTAssertEqual(preparationSession?.requests.count, 1)
|
||
XCTAssertEqual(request.httpMethod, "GET")
|
||
XCTAssertEqual(request.url?.path, "/api/app/airport/workbench")
|
||
let query = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||
XCTAssertEqual(query.first { $0.name == "order_number" }?.value, "TEST-ORDER-701")
|
||
XCTAssertEqual(query.first { $0.name == "scenic_id" }?.value, "128")
|
||
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"] }
|
||
|
||
/// 按实际 home 响应结构构造替身,设备名称和序列号使用测试值。
|
||
private var populatedEnvelope: Data {
|
||
Data(#"{"code":100000,"msg":"success","data":{"scenic_id":128,"airports":[{"id":58,"name":"测试机巢M4D","sn_number":"test-airport-sn","scenic_area_id":128,"online_status":1,"work_status":1,"work_status_label":"空闲","is_receive_order":1,"task_type":null,"metrics":[{"key":"battery","label":"电池电量","raw":null,"value":"—"},{"key":"env_temp","label":"环境温度","raw":null,"value":"—"},{"key":"wind_speed","label":"风速","raw":null,"value":"—"},{"key":"rainfall","label":"雨量","raw":null,"value":"—"},{"key":"signal","label":"信号状态","raw":null,"value":"—"},{"key":"satellite","label":"搜星状态","raw":null,"value":"—"}]}],"orders":[],"today":{"finished_shoot":0,"order_amount":0,"order_count":0}},"time":"2026-10-27 14:38:58"}"#.utf8)
|
||
}
|
||
|
||
/// 在真实结构中替换遥测或追加设备,构造确定的刷新与多机测试输入。
|
||
private func deviceEnvelope(metricValues: [String: (Double, String)]? = nil, addSecondAirport: Bool = false) throws -> Data {
|
||
var envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: populatedEnvelope) as? [String: Any])
|
||
var data = try XCTUnwrap(envelope["data"] as? [String: Any])
|
||
var airports = try XCTUnwrap(data["airports"] as? [[String: Any]])
|
||
if let metricValues {
|
||
var metrics = try XCTUnwrap(airports[0]["metrics"] as? [[String: Any]])
|
||
for index in metrics.indices {
|
||
let key = try XCTUnwrap(metrics[index]["key"] as? String)
|
||
let value = try XCTUnwrap(metricValues[key])
|
||
metrics[index]["raw"] = value.0
|
||
metrics[index]["value"] = value.1
|
||
}
|
||
airports[0]["metrics"] = metrics
|
||
}
|
||
if addSecondAirport {
|
||
var second = airports[0]
|
||
second["id"] = 59
|
||
second["name"] = "测试二号无人机"
|
||
second["sn_number"] = "ui-test-second-airport"
|
||
airports.append(second)
|
||
}
|
||
data["airports"] = airports
|
||
envelope["data"] = data
|
||
return try JSONSerialization.data(withJSONObject: envelope)
|
||
}
|
||
|
||
/// 从实际设备卡获取已呈现的读数,缺少标签时不会伪造占位值。
|
||
private func metricTexts(in view: UIView) -> [String: String] {
|
||
var values: [String: String] = [:]
|
||
for key in metricKeys {
|
||
guard let label = find(in: view, identifier: "drone.metric.\(key)") as? UILabel,
|
||
!isHiddenByAncestor(label), !label.bounds.isEmpty, let text = label.text else { continue }
|
||
values[key] = text
|
||
}
|
||
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], preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) -> (DroneDockHomeViewController, MockURLSession) {
|
||
let context = DroneDockHomeContext(
|
||
userID: "remote-home-ui-test", accountType: "store_user", scenicID: 128,
|
||
scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "test-token"
|
||
)
|
||
let session = MockURLSession(responses: responses)
|
||
let client = APIClient(environment: .testing, session: session, notificationCenter: NotificationCenter())
|
||
client.bindAuthTokenProvider { "test-token" }
|
||
let viewModel = DroneDockHomeViewModel(context: context, service: DroneDockAPI(client: client), currentContext: { context })
|
||
return (DroneDockHomeViewController(viewModel: viewModel, paymentControllerFactory: {
|
||
// 夹具均为固定合法 JSON,路由测试不使用 NetworkServices 或真机登录信息。
|
||
try! DroneDockPaymentViewFixtures.controller(context: context)
|
||
}, preparationControllerFactory: preparationControllerFactory), 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
|
||
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: root)
|
||
window.makeKeyAndVisible()
|
||
window.layoutIfNeeded()
|
||
return window
|
||
}
|
||
|
||
/// 清理弹层与异步页面任务,不改变原账户及业务窗口。
|
||
private func close(_ window: UIWindow) {
|
||
window.endEditing(true)
|
||
window.rootViewController?.dismiss(animated: false)
|
||
window.isHidden = true
|
||
window.rootViewController = nil
|
||
previousKeyWindow?.makeKeyAndVisible()
|
||
}
|
||
|
||
/// 等待网络替身、Diffable 和实际窗口布局完成,不靠固定长延迟判断结果。
|
||
private func settle(window: UIWindow, until condition: () -> Bool) async throws {
|
||
for _ in 0..<150 {
|
||
window.layoutIfNeeded()
|
||
window.rootViewController?.view.layoutIfNeeded()
|
||
if condition() {
|
||
try await Task.sleep(nanoseconds: 250_000_000)
|
||
window.layoutIfNeeded()
|
||
return
|
||
}
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
XCTFail("真实机巢首页未在预期时间内完成渲染")
|
||
throw NSError(domain: "DroneDockRemoteHomeViewTests", code: 1)
|
||
}
|
||
|
||
/// 从实际可见子视图获取文本,排除被隐藏的复用视图。
|
||
private func visibleTexts(in root: UIView) -> [String] {
|
||
allViews(in: root).compactMap { view in
|
||
guard let label = view as? UILabel, !isHiddenByAncestor(label), !label.bounds.isEmpty else { return nil }
|
||
return label.text
|
||
}
|
||
}
|
||
|
||
/// 枚举测试窗口里的真实视图,避免读取生产代码私有字段。
|
||
private func allViews(in view: UIView) -> [UIView] {
|
||
[view] + view.subviews.flatMap { allViews(in: $0) }
|
||
}
|
||
|
||
/// 按稳定的辅助功能标识定位实际控件。
|
||
private func find(in root: UIView, identifier: String) -> UIView? {
|
||
allViews(in: root).first { $0.accessibilityIdentifier == identifier }
|
||
}
|
||
|
||
/// 排除隐藏祖先和完全透明的控件。
|
||
private func isHiddenByAncestor(_ view: UIView) -> Bool {
|
||
if view.isHidden || view.alpha < 0.01 { return true }
|
||
return view.superview.map { isHiddenByAncestor($0) } ?? false
|
||
}
|
||
|
||
/// 证明页面入口只读取 home,没有发送其他业务或设备控制请求。
|
||
private func assertOnlyReadHomeRequests(_ session: MockURLSession, file: StaticString = #filePath, line: UInt = #line) {
|
||
XCTAssertFalse(session.requests.isEmpty, file: file, line: line)
|
||
XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" && $0.url?.path == "/api/app/airport/home" }, file: file, line: line)
|
||
}
|
||
|
||
/// 保存测试窗口截图到 xcresult,便于核对页面样式。
|
||
private func capture(_ window: UIWindow, named name: String) {
|
||
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)
|
||
}
|
||
}
|