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) 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.presentedViewController as? UIAlertController)?.title == "套餐收款" } XCTAssertEqual((controller.presentedViewController as? UIAlertController)?.message, "该功能暂未开放") XCTAssertEqual(controller.navigationController?.viewControllers.count, 1) XCTAssertTrue(controller.navigationController?.topViewController === controller) 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: "机巢真实首页-多设备横向卡片") } /// 服务端确定的六项读数键,按标识查找而不依赖数组排序。 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]) -> (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), 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) } }