增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
471 lines
29 KiB
Swift
471 lines
29 KiB
Swift
import UIKit
|
|
import XCTest
|
|
@testable import suixinkan
|
|
|
|
#if DEBUG
|
|
/// 在隔离窗口验证独立空镜库的布局、筛选、预览与本地下载流程。
|
|
@MainActor
|
|
final class ScenicMaterialsFlowViewTests: XCTestCase {
|
|
private weak var previousKeyWindow: UIWindow?
|
|
|
|
/// 独立入口不创建工作台;首段和双列可点,整组选中包括折叠的第六段。
|
|
func testIndependentEntryAndSixClipGroupSelectionAcrossExpandedLayout() async throws {
|
|
XCTAssertNil(ScenicMaterialsPreview.navigationController(arguments: []))
|
|
let navigation = try XCTUnwrap(ScenicMaterialsPreview.navigationController(arguments: ["--scenic-materials-preview"]))
|
|
XCTAssertEqual(navigation.viewControllers.count, 1)
|
|
let controller = try XCTUnwrap(navigation.topViewController as? ScenicMaterialsViewController)
|
|
let window = makeWindow(root: navigation)
|
|
defer { close(window) }
|
|
let model = controller.viewModel
|
|
let list = try await waitForLibrary(controller, window: window)
|
|
let firstGroup = try XCTUnwrap(model.filteredGroups.first)
|
|
let hero = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 0, section: 1)))
|
|
let left = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 1, section: 1)))
|
|
let right = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 2, section: 1)))
|
|
XCTAssertGreaterThan(hero.bounds.width, left.bounds.width * 1.8)
|
|
XCTAssertGreaterThan(hero.bounds.height, 100)
|
|
XCTAssertEqual(left.frame.minY, right.frame.minY, accuracy: 1)
|
|
XCTAssertLessThan(left.frame.maxX, right.frame.minX)
|
|
capture(window, named: "空镜库-常态首段与双列")
|
|
let heroSelect = try button(in: controller.view, identifier: "scenic.materials.select.\(firstGroup.clips[0].id)")
|
|
assertReachable(heroSelect, window: window)
|
|
heroSelect.sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.selectedIDs, [firstGroup.clips[0].id])
|
|
let tileSelect = try button(in: controller.view, identifier: "scenic.materials.select.\(firstGroup.clips[1].id)")
|
|
assertReachable(tileSelect, window: window)
|
|
tileSelect.sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.selectedCount, 2)
|
|
assertLayout(in: controller.view)
|
|
capture(window, named: "空镜库-双列片段选择")
|
|
|
|
model.toggleSelection(id: firstGroup.clips[0].id)
|
|
model.toggleSelection(id: firstGroup.clips[1].id)
|
|
controller.refreshDisplay(animated: false)
|
|
let groupIndex = try XCTUnwrap(model.filteredGroups.firstIndex { $0.clips.count == 6 })
|
|
let group = model.filteredGroups[groupIndex]
|
|
let section = groupIndex + 1
|
|
try await showGroupHeader(section: section, list: list, window: window)
|
|
let groupSelect = try button(in: controller.view, identifier: "scenic.materials.group.\(group.id)")
|
|
assertReachable(groupSelect, window: window)
|
|
groupSelect.sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.selectedIDs, Set(group.clips.map(\.id)))
|
|
XCTAssertEqual(model.visibleClips(in: group).count, 5)
|
|
XCTAssertEqual(list.numberOfItems(inSection: section), 6)
|
|
try await settle(window) {
|
|
self.find(in: controller.view, identifier: "scenic.materials.group.\(group.id)")?.accessibilityTraits.contains(.selected) == true
|
|
}
|
|
capture(window, named: "空镜库-整组六段含折叠选择")
|
|
list.scrollToItem(at: IndexPath(item: 5, section: section), at: .centeredVertically, animated: false)
|
|
try await settle(window) { self.find(in: controller.view, identifier: "scenic.materials.expand.\(group.id)") != nil }
|
|
let expand = try button(in: controller.view, identifier: "scenic.materials.expand.\(group.id)")
|
|
assertReachable(expand, window: window)
|
|
expand.sendActions(for: .touchUpInside)
|
|
try await settle(window) { list.numberOfItems(inSection: section) == 7 }
|
|
XCTAssertEqual(model.visibleClips(in: group).count, 6)
|
|
XCTAssertEqual(model.selectedIDs, Set(group.clips.map(\.id)))
|
|
list.scrollToItem(at: IndexPath(item: 5, section: section), at: .centeredVertically, animated: false)
|
|
try await settle(window) { self.find(in: controller.view, identifier: "scenic.materials.clip.\(group.clips[5].id)") != nil }
|
|
let sixth = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 5, section: section)))
|
|
let collapse = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 6, section: section)))
|
|
let groupHero = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 0, section: section)))
|
|
XCTAssertGreaterThan(collapse.frame.minY, sixth.frame.maxY, "收起按钮必须独占第六段下方一行")
|
|
XCTAssertEqual(collapse.frame.width, groupHero.frame.width, accuracy: 1, "收起按钮应与首段卡片等宽")
|
|
XCTAssertEqual(collapse.frame.minX, groupHero.frame.minX, accuracy: 1)
|
|
assertLayout(in: controller.view)
|
|
capture(window, named: "空镜库-展开第六段")
|
|
}
|
|
|
|
/// 航线无结果可重置;日期面板的实际控件只在确定后应用按日筛选。
|
|
func testRouteAndDateSheetCallbacksFilterResultsAndResetEmptyRoute() async throws {
|
|
let controller = ScenicMaterialsViewController()
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
let model = controller.viewModel
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let originalCount = model.filteredGroups.count
|
|
try button(in: controller.view, identifier: "scenic.materials.routeFilter").sendActions(for: .touchUpInside)
|
|
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialRouteFilterViewController.self) }
|
|
let routeSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialRouteFilterViewController)
|
|
let table = try XCTUnwrap(find(in: routeSheet.view, identifier: "scenic.materials.route.list") as? UITableView)
|
|
let path = IndexPath(row: 3, section: 0)
|
|
let row = try XCTUnwrap(table.cellForRow(at: path))
|
|
assertReachable(row, window: window)
|
|
capture(window, named: "空镜库-航线筛选")
|
|
table.delegate?.tableView?(table, didSelectRowAt: path)
|
|
try await settle(window) { controller.presentedViewController == nil && model.filteredGroups.isEmpty }
|
|
XCTAssertEqual(model.selectedRouteID, model.routes[2].id)
|
|
let reset = try button(in: controller.view, identifier: "scenic.materials.resetFilters")
|
|
assertReachable(reset, window: window)
|
|
capture(window, named: "空镜库-航线无结果")
|
|
reset.sendActions(for: .touchUpInside)
|
|
try await settle(window) { model.filteredGroups.count == originalCount }
|
|
XCTAssertNil(model.selectedRouteID)
|
|
|
|
let day = try XCTUnwrap(model.filteredGroups.first?.capturedAt)
|
|
let expected = model.filteredGroups.filter { model.calendar.isDate($0.capturedAt, inSameDayAs: day) }
|
|
let hiddenID = try XCTUnwrap(model.filteredGroups.first { !model.calendar.isDate($0.capturedAt, inSameDayAs: day) }?.clips.first?.id)
|
|
model.toggleSelection(id: hiddenID)
|
|
controller.refreshDisplay(animated: false)
|
|
try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside)
|
|
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) }
|
|
let dateSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController)
|
|
let picker = try XCTUnwrap(find(in: dateSheet.view, identifier: "scenic.materials.date.picker") as? UIPickerView)
|
|
XCTAssertEqual(picker.numberOfComponents, 2, "日期筛选只展示月、日两列")
|
|
let start = try button(in: dateSheet.view, identifier: "scenic.materials.date.start")
|
|
assertReachable(start, window: window)
|
|
start.sendActions(for: .touchUpInside)
|
|
try selectDate(day, in: picker, minimumDate: model.minimumDate, calendar: model.calendar)
|
|
let end = try button(in: dateSheet.view, identifier: "scenic.materials.date.end")
|
|
end.sendActions(for: .touchUpInside)
|
|
try selectDate(day, in: picker, minimumDate: model.minimumDate, calendar: model.calendar)
|
|
let formatter = DateFormatter()
|
|
formatter.calendar = model.calendar
|
|
formatter.timeZone = model.calendar.timeZone
|
|
formatter.locale = Locale(identifier: "zh_CN")
|
|
formatter.dateFormat = "M月d日"
|
|
let selectedDay = formatter.string(from: day)
|
|
try await settle(window) {
|
|
self.visibleLabel(in: start, text: "开始日期") != nil && self.visibleLabel(in: start, text: selectedDay) != nil
|
|
&& self.visibleLabel(in: end, text: "结束日期") != nil && self.visibleLabel(in: end, text: selectedDay) != nil
|
|
}
|
|
for (endpoint, title) in [(start, "开始日期"), (end, "结束日期")] {
|
|
assertReachable(endpoint, window: window)
|
|
for text in [title, selectedDay] {
|
|
let label = try XCTUnwrap(visibleLabel(in: endpoint, text: text), "日期端点文字未渲染:\(text)")
|
|
XCTAssertGreaterThan(label.bounds.width, 0)
|
|
XCTAssertGreaterThan(label.bounds.height, 0)
|
|
XCTAssertTrue(endpoint.bounds.contains(label.convert(label.bounds, to: endpoint)), "日期端点文字超出按钮:\(text)")
|
|
}
|
|
}
|
|
XCTAssertNil(model.dateRange)
|
|
XCTAssertEqual(model.selectedIDs, [hiddenID])
|
|
assertLayout(in: dateSheet.view)
|
|
capture(window, named: "空镜库-起止日期筛选")
|
|
let confirm = try button(in: dateSheet.view, identifier: "scenic.materials.date.confirm")
|
|
assertReachable(confirm, window: window)
|
|
confirm.sendActions(for: .touchUpInside)
|
|
try await settle(window) { controller.presentedViewController == nil && model.dateRange != nil }
|
|
XCTAssertEqual(model.filteredGroups.map(\.id), expected.map(\.id))
|
|
XCTAssertEqual(model.dateRange?.start, model.calendar.startOfDay(for: day))
|
|
XCTAssertEqual(model.dateRange?.end, model.calendar.startOfDay(for: day))
|
|
XCTAssertTrue(model.selectedIDs.isEmpty)
|
|
capture(window, named: "空镜库-日期筛选结果")
|
|
}
|
|
|
|
/// 月日滚轮编辑与全部时间都是草稿;取消不提交,确定才清除已有日期筛选。
|
|
func testDateDraftCancellationAndAllDatesRequireConfirmation() async throws {
|
|
let controller = ScenicMaterialsViewController()
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
let model = controller.viewModel
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let day = try XCTUnwrap(model.filteredGroups.first?.capturedAt)
|
|
XCTAssertTrue(model.setDateRange(start: day, end: day))
|
|
let originalRange = model.dateRange
|
|
controller.refreshDisplay(animated: false)
|
|
|
|
try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside)
|
|
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) }
|
|
let cancelledSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController)
|
|
let picker = try XCTUnwrap(find(in: cancelledSheet.view, identifier: "scenic.materials.date.picker") as? UIPickerView)
|
|
try selectDate(model.minimumDate, in: picker, minimumDate: model.minimumDate, calendar: model.calendar)
|
|
XCTAssertEqual(model.dateRange, originalRange)
|
|
try button(in: cancelledSheet.view, identifier: "scenic.materials.date.cancel").sendActions(for: .touchUpInside)
|
|
try await settle(window) { controller.presentedViewController == nil }
|
|
XCTAssertEqual(model.dateRange, originalRange)
|
|
|
|
try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside)
|
|
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) }
|
|
let allDatesSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController)
|
|
try button(in: allDatesSheet.view, identifier: "scenic.materials.date.all").sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.dateRange, originalRange)
|
|
try button(in: allDatesSheet.view, identifier: "scenic.materials.date.confirm").sendActions(for: .touchUpInside)
|
|
try await settle(window) { controller.presentedViewController == nil && model.dateRange == nil }
|
|
XCTAssertEqual(model.dateFilterTitle, "全部时间")
|
|
}
|
|
|
|
/// 预览从真实卡片打开并关闭,暂停中的选择和下载批次不受 Sheet 生命周期影响。
|
|
func testPreviewOpenAndClosePreservesPausedBatchAndSelection() async throws {
|
|
let model = ScenicMaterialsViewModel()
|
|
model.applyScenario(.paused)
|
|
let controller = ScenicMaterialsViewController(viewModel: model)
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let clipID = try XCTUnwrap(model.filteredGroups.first?.clips.first?.id)
|
|
let selected = model.selectedIDs
|
|
let token = model.batchID
|
|
let completed = model.completedIDs
|
|
let preview = try button(in: controller.view, identifier: "scenic.materials.preview.\(clipID)")
|
|
assertReachable(preview, window: window)
|
|
preview.sendActions(for: .touchUpInside)
|
|
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialPreviewViewController.self) }
|
|
let sheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialPreviewViewController)
|
|
assertLayout(in: sheet.view)
|
|
capture(window, named: "空镜库-视频预览")
|
|
let play = try button(in: sheet.view, identifier: "scenic.materials.preview.play")
|
|
assertReachable(play, window: window)
|
|
play.sendActions(for: .touchUpInside)
|
|
try await settle(window) {
|
|
self.allViews(in: sheet.view).compactMap { $0 as? UILabel }.contains { $0.text?.hasPrefix("正在播放 3 秒本地演示") == true }
|
|
}
|
|
XCTAssertEqual(model.batchID, token)
|
|
XCTAssertEqual(model.phase, .paused)
|
|
let closeButton = try button(in: sheet.view, identifier: "scenic.materials.preview.done")
|
|
assertReachable(closeButton, window: window)
|
|
closeButton.sendActions(for: .touchUpInside)
|
|
try await settle(window) { controller.presentedViewController == nil && controller.navigationController?.transitionCoordinator == nil }
|
|
XCTAssertEqual(model.selectedIDs, selected)
|
|
XCTAssertEqual(model.batchID, token)
|
|
XCTAssertEqual(model.completedIDs, completed)
|
|
XCTAssertEqual(model.phase, .paused)
|
|
}
|
|
|
|
/// 实际下载按钮驱动单段演示到完成,继续选择后保留成功状态且不重复下载。
|
|
func testDownloadButtonCompletesLocalDemoAndKeepsSuccessfulClipUnavailable() async throws {
|
|
let controller = ScenicMaterialsViewController()
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
let model = controller.viewModel
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let clipID = try XCTUnwrap(model.filteredGroups.first?.clips.first?.id)
|
|
try button(in: controller.view, identifier: "scenic.materials.select.\(clipID)").sendActions(for: .touchUpInside)
|
|
try await settle(window) { model.selectedCount == 1 }
|
|
let download = try button(in: controller.view, identifier: "scenic.materials.primary")
|
|
assertReachable(download, window: window)
|
|
XCTAssertTrue(download.isEnabled)
|
|
download.sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.phase, .downloading)
|
|
XCTAssertEqual(model.batchItemIDs, [clipID])
|
|
XCTAssertTrue(model.isSelectionLocked)
|
|
capture(window, named: "空镜库-本地下载演示")
|
|
try await settle(window, timeout: 6) { model.phase == .completed }
|
|
XCTAssertEqual(model.completedIDs, [clipID])
|
|
XCTAssertEqual(model.completedCount, 1)
|
|
XCTAssertTrue(allViews(in: controller.view).compactMap { $0 as? UILabel }.contains { $0.text?.contains("未写入系统相册") == true })
|
|
assertLayout(in: controller.view)
|
|
capture(window, named: "空镜库-下载演示完成")
|
|
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.phase, .idle)
|
|
XCTAssertNil(model.batchID)
|
|
XCTAssertEqual(model.completedIDs, [clipID])
|
|
XCTAssertFalse(model.canSelect(id: clipID))
|
|
}
|
|
|
|
/// 后台作废旧下载令牌,回前台保持暂停,手动继续仅处理剩余素材。
|
|
func testBackgroundPausesRejectsStaleCallbacksAndRequiresManualResume() async throws {
|
|
let model = ScenicMaterialsViewModel()
|
|
model.applyScenario(.paused)
|
|
let controller = ScenicMaterialsViewController(viewModel: model)
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let completed = model.completedIDs
|
|
let pending = try XCTUnwrap(model.pendingIDs.first)
|
|
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
|
let oldToken = try XCTUnwrap(model.batchID)
|
|
XCTAssertEqual(model.phase, .downloading)
|
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
|
let pausedToken = try XCTUnwrap(model.batchID)
|
|
XCTAssertNotEqual(oldToken, pausedToken)
|
|
XCTAssertEqual(model.phase, .paused)
|
|
model.receive(.completed, clipID: pending, batchID: oldToken)
|
|
XCTAssertEqual(model.completedIDs, completed)
|
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
|
try await Task.sleep(nanoseconds: 450_000_000)
|
|
XCTAssertEqual(model.phase, .paused)
|
|
XCTAssertEqual(model.batchID, pausedToken)
|
|
XCTAssertEqual(model.completedIDs, completed)
|
|
capture(window, named: "空镜库-后台暂停待继续")
|
|
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
|
XCTAssertNotEqual(model.batchID, pausedToken)
|
|
XCTAssertEqual(model.pendingIDs, [pending])
|
|
XCTAssertEqual(model.completedIDs, completed)
|
|
try await settle(window, timeout: 6) { model.phase == .completed }
|
|
XCTAssertEqual(model.completedIDs, completed.union([pending]))
|
|
}
|
|
|
|
/// 部分失败重试仅恢复失败段,已有成功段及批次顺序保持不变。
|
|
func testRetryFailureOnlyRunsFailedClipAndPreservesSuccessfulDownloads() async throws {
|
|
let model = ScenicMaterialsViewModel()
|
|
model.applyScenario(.partialFailure)
|
|
let controller = ScenicMaterialsViewController(viewModel: model)
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let completed = model.completedIDs
|
|
let failed = model.failedIDs
|
|
let originalItems = model.batchItemIDs
|
|
XCTAssertEqual(completed.count, 1)
|
|
XCTAssertEqual(failed.count, 1)
|
|
capture(window, named: "空镜库-部分失败可重试")
|
|
let retry = try button(in: controller.view, identifier: "scenic.materials.primary")
|
|
assertReachable(retry, window: window)
|
|
retry.sendActions(for: .touchUpInside)
|
|
XCTAssertEqual(model.phase, .downloading)
|
|
XCTAssertEqual(Set(model.pendingIDs), failed)
|
|
XCTAssertEqual(model.batchItemIDs, originalItems)
|
|
XCTAssertEqual(model.completedIDs, completed)
|
|
XCTAssertTrue(model.failedIDs.isEmpty)
|
|
XCTAssertTrue(model.isSelectionLocked)
|
|
try await settle(window, timeout: 6) { model.phase == .completed }
|
|
XCTAssertEqual(model.completedIDs, completed.union(failed))
|
|
XCTAssertEqual(model.completedCount, originalItems.count)
|
|
capture(window, named: "空镜库-失败重试完成")
|
|
}
|
|
|
|
/// 演示权限不足时下载按钮只显示本地说明,不创建批次或触碰系统相册权限。
|
|
func testDeniedDemoPermissionShowsExplanationWithoutStartingBatch() async throws {
|
|
let controller = ScenicMaterialsViewController(isDemoPhotoPermissionAllowed: false)
|
|
let window = makeWindow(root: controller)
|
|
defer { close(window) }
|
|
let model = controller.viewModel
|
|
_ = try await waitForLibrary(controller, window: window)
|
|
let clipID = try XCTUnwrap(model.filteredGroups.first?.clips.first?.id)
|
|
try button(in: controller.view, identifier: "scenic.materials.select.\(clipID)").sendActions(for: .touchUpInside)
|
|
try await settle(window) { model.selectedCount == 1 }
|
|
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
|
try await settle(window) { self.isPresentationSettled(controller, type: UIAlertController.self) }
|
|
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
|
|
XCTAssertEqual(alert.title, "需要相册保存权限")
|
|
XCTAssertTrue(alert.message?.contains("演示") == true)
|
|
XCTAssertEqual(alert.actions.count, 2)
|
|
XCTAssertNil(model.batchID)
|
|
XCTAssertEqual(model.phase, .idle)
|
|
XCTAssertEqual(model.selectedIDs, [clipID])
|
|
capture(window, named: "空镜库-相册权限演示说明")
|
|
alert.dismiss(animated: false)
|
|
try await settle(window) { controller.presentedViewController == nil }
|
|
XCTAssertNil(model.batchID)
|
|
}
|
|
|
|
private func makeWindow(root 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 = controller is UINavigationController ? controller : UINavigationController(rootViewController: controller)
|
|
window.makeKeyAndVisible()
|
|
window.layoutIfNeeded()
|
|
return window
|
|
}
|
|
|
|
/// 通过两列滚轮的真实 delegate 路径选择日期,覆盖月份重载和按日提交。
|
|
private func selectDate(_ date: Date, in picker: UIPickerView, minimumDate: Date, calendar: Calendar) throws {
|
|
let firstMonth = try XCTUnwrap(calendar.dateInterval(of: .month, for: minimumDate)?.start)
|
|
let desiredMonth = try XCTUnwrap(calendar.dateInterval(of: .month, for: date)?.start)
|
|
let monthRow = try XCTUnwrap(calendar.dateComponents([.month], from: firstMonth, to: desiredMonth).month)
|
|
picker.selectRow(monthRow, inComponent: 0, animated: false)
|
|
picker.delegate?.pickerView?(picker, didSelectRow: monthRow, inComponent: 0)
|
|
let firstDay = monthRow == 0 ? calendar.component(.day, from: minimumDate) : 1
|
|
let dayRow = calendar.component(.day, from: date) - firstDay
|
|
XCTAssertGreaterThanOrEqual(dayRow, 0)
|
|
XCTAssertLessThan(dayRow, picker.numberOfRows(inComponent: 1))
|
|
picker.selectRow(dayRow, inComponent: 1, animated: false)
|
|
picker.delegate?.pickerView?(picker, didSelectRow: dayRow, inComponent: 1)
|
|
}
|
|
|
|
private func close(_ window: UIWindow) {
|
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
|
window.endEditing(true)
|
|
window.rootViewController?.dismiss(animated: false)
|
|
window.isHidden = true
|
|
window.rootViewController = nil
|
|
previousKeyWindow?.makeKeyAndVisible()
|
|
}
|
|
|
|
private func waitForLibrary(_ controller: ScenicMaterialsViewController, window: UIWindow) async throws -> UICollectionView {
|
|
let list = try XCTUnwrap(find(in: controller.view, identifier: "scenic.materials.list") as? UICollectionView)
|
|
try await settle(window) { list.numberOfSections > 2 && list.cellForItem(at: IndexPath(item: 0, section: 1)) != nil }
|
|
return list
|
|
}
|
|
|
|
private func showGroupHeader(section: Int, list: UICollectionView, window: UIWindow) async throws {
|
|
let path = IndexPath(item: 0, section: section)
|
|
let attributes = try XCTUnwrap(list.collectionViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: path))
|
|
list.setContentOffset(CGPoint(x: 0, y: max(-list.adjustedContentInset.top, attributes.frame.minY - 4)), animated: false)
|
|
try await settle(window) { list.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: path) != nil }
|
|
}
|
|
|
|
private func isPresentationSettled<T: UIViewController>(_ presenter: UIViewController, type: T.Type) -> Bool {
|
|
guard let presented = presenter.presentedViewController as? T else { return false }
|
|
return !presented.isBeingPresented && presented.transitionCoordinator == nil && presented.view.window != nil
|
|
}
|
|
|
|
private func settle(_ window: UIWindow, timeout: TimeInterval = 4, condition: () -> Bool) async throws {
|
|
let deadline = Date().addingTimeInterval(timeout)
|
|
while Date() < deadline {
|
|
window.layoutIfNeeded()
|
|
window.rootViewController?.view.layoutIfNeeded()
|
|
if condition() {
|
|
try await Task.sleep(nanoseconds: 300_000_000)
|
|
window.layoutIfNeeded()
|
|
return
|
|
}
|
|
try await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
XCTFail("空镜库 UI 未在限定时间内进入预期状态")
|
|
}
|
|
|
|
private func allViews(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews(in: $0) } }
|
|
|
|
private func find(in root: UIView, identifier: String) -> UIView? {
|
|
allViews(in: root).first { $0.accessibilityIdentifier == identifier }
|
|
}
|
|
|
|
private func button(in root: UIView, identifier: String) throws -> UIButton {
|
|
try XCTUnwrap(find(in: root, identifier: identifier) as? UIButton, "缺少按钮 \(identifier)")
|
|
}
|
|
|
|
private func isHiddenByAncestor(_ view: UIView) -> Bool {
|
|
view.isHidden || view.alpha < 0.01 || (view.superview.map { isHiddenByAncestor($0) } ?? false)
|
|
}
|
|
|
|
private func visibleLabel(in root: UIView, text: String) -> UILabel? {
|
|
allViews(in: root).compactMap { $0 as? UILabel }.first {
|
|
($0.text ?? $0.attributedText?.string) == text && !isHiddenByAncestor($0)
|
|
&& !$0.bounds.isEmpty && $0.convert($0.bounds, to: root).intersects(root.bounds)
|
|
}
|
|
}
|
|
|
|
private func assertReachable(_ view: UIView, window: UIWindow, file: StaticString = #filePath, line: UInt = #line) {
|
|
XCTAssertFalse(view.bounds.isEmpty, file: file, line: line)
|
|
XCTAssertFalse(isHiddenByAncestor(view), file: file, line: line)
|
|
let center = view.convert(CGPoint(x: view.bounds.midX, y: view.bounds.midY), to: window)
|
|
XCTAssertTrue(window.bounds.contains(center), "控件超出窗口:\(view.accessibilityIdentifier ?? "")", file: file, line: line)
|
|
let hit = window.hitTest(center, with: nil)
|
|
XCTAssertTrue(hit === view || hit?.isDescendant(of: view) == true,
|
|
"控件被遮挡:\(view.accessibilityIdentifier ?? "")", file: file, line: line)
|
|
}
|
|
|
|
private func assertLayout(in root: UIView, file: StaticString = #filePath, line: UInt = #line) {
|
|
let ambiguous = allViews(in: root).filter {
|
|
!isHiddenByAncestor($0) && !$0.bounds.isEmpty && $0.convert($0.bounds, to: root).intersects(root.bounds)
|
|
&& !$0.translatesAutoresizingMaskIntoConstraints && !String(describing: type(of: $0)).hasPrefix("_") && $0.hasAmbiguousLayout
|
|
}
|
|
XCTAssertTrue(ambiguous.isEmpty, "布局歧义:\(ambiguous.map { String(describing: type(of: $0)) + " " + ($0.accessibilityIdentifier ?? "") })", file: file, line: line)
|
|
}
|
|
|
|
/// 截图保存在 xcresult 及应用临时目录,便于导出视觉证据。
|
|
private func capture(_ window: UIWindow, named name: String) {
|
|
window.layoutIfNeeded()
|
|
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)
|
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("scenic-materials-ui-proof", isDirectory: true)
|
|
do {
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
try image.pngData()?.write(to: directory.appendingPathComponent(name + ".png"), options: .atomic)
|
|
} catch {
|
|
XCTFail("空镜库截图临时文件写入失败:\(error)")
|
|
}
|
|
}
|
|
}
|
|
#endif
|