import Foundation import Testing import UIKit import WebKit @testable import suixinkan #if DEBUG /// 在连接的 iPhone 真机中渲染任务列表、成绩页和答题卡,附件用于视觉检查。 @Suite("培训中心原生布局", .serialized) @MainActor struct TrainingUIRenderingTests { @Test("原生任务列表与窄屏长文本卡片不裁切") func taskListAndLongTitleLayout() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let source = TrainingDemoService(context: TrainingContext(accountScope: "render", scenicID: 1, storeID: 1), storage: TrainingDemoFileStorage(directory: directory)) let controller = TrainingCenterViewController(service: TrainingDataStub()) controller.loadViewIfNeeded() await controller.reload() let navigation = UINavigationController(rootViewController: controller) let window = try makeWindow(navigation) defer { window.isHidden = true } navigation.view.layoutIfNeeded() Attachment.record(render(navigation.view), named: "培训首页", as: .png) let labels = allViews(controller.view).compactMap { $0 as? UILabel } #expect(labels.contains { $0.text == "一线服务规范学习" }) #expect(labels.contains { $0.text == "学习 + 考试 · 30 题 · 80 分及格" }) #expect(!labels.contains { $0.text?.contains("未同步景区后台") == true }) let original = try await source.task(id: "demo-service") let longTask = TrainingTask(id: original.id, title: String(repeating: "游客沟通与接待服务规范培训", count: 3), publisherName: "景区培训负责人", mode: .exam, status: .published, startAt: original.startAt, endAt: original.endAt, passScore: original.passScore, scoring: original.scoring, course: original.course, questions: original.questions, progress: original.progress) let cell = TrainingTaskCell(style: .default, reuseIdentifier: nil) cell.configure(task: longTask) #expect(allViews(cell.contentView).compactMap { $0 as? UILabel }.contains { $0.text == "学习 + 考试 · \(longTask.questions.count) 题 · \(longTask.passScore) 分及格" }) let width: CGFloat = 320 let shortCell = TrainingTaskCell(style: .default, reuseIdentifier: nil) shortCell.configure(task: original) let shortSize = shortCell.contentView.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel) let size = cell.contentView.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel) cell.frame = CGRect(x: 0, y: 0, width: width, height: size.height) cell.layoutIfNeeded() #expect(size.height > shortSize.height) for label in allViews(cell.contentView).compactMap({ $0 as? UILabel }).filter(isVisible) { let frame = label.convert(label.bounds, to: cell.contentView) #expect(frame.minX >= 0 && frame.maxX <= width + 1) #expect(frame.minY >= 0 && frame.maxY <= size.height + 1) } let cardImage = UIGraphicsImageRenderer(size: cell.bounds.size).image { context in cell.layer.render(in: context.cgContext) } Attachment.record(cardImage, named: "320点长标题任务卡", as: .png) cell.configure(task: try await source.task(id: "demo-study")) #expect(allViews(cell.contentView).compactMap { $0 as? UILabel }.contains { $0.text == "仅学习" }) } @Test("任务页三种筛选独立查询,已结束任务显示回顾入口") func endedFilterAndReadOnlyCard() async throws { let source = TrainingDataStub() await source.configure { $0.tasksHandler = { status, _, _, _ in let state = status ?? .pendingExam return TrainingCursorPage(items: [TrainingRemoteFixtures.task(id: state.apiValue, title: "\(state.title)任务", learnerStatus: state)], nextCursor: nil, hasMore: false, serverTime: nil) } } for width: CGFloat in [320, 390] { let controller = TrainingCenterViewController(service: source) let navigation = UINavigationController(rootViewController: controller) let window = try makeWindow(navigation, width: width) defer { window.isHidden = true } controller.selectTab(.tasks) let buttons = allViews(controller.view).compactMap { $0 as? UIButton } .filter { $0.accessibilityIdentifier?.hasPrefix("training.filter.") == true } #expect(buttons.count == 3) for state in [TrainingLearnerStatus.ended, .completed, .pendingExam, .ended] { let index = try #require(TrainingLearnerStatus.allCases.firstIndex(of: state)) let button = try #require(buttons.first { $0.tag == index }) button.sendActions(for: .touchUpInside) let deadline = ContinuousClock.now.advanced(by: .seconds(5)) while ContinuousClock.now < deadline { navigation.view.layoutIfNeeded() let hasTask = allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == "\(state.title)任务" } if button.accessibilityTraits.contains(.selected), hasTask { break } try await Task.sleep(for: .milliseconds(10)) } #expect(button.accessibilityTraits.contains(.selected)) #expect(buttons.filter { $0.accessibilityTraits.contains(.selected) }.count == 1) #expect(allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == "\(state.title)任务" }) } #expect(buttons.map { $0.configuration?.title } == ["待考试 1", "已完成 0", "已结束"]) for button in buttons { let frame = button.convert(button.bounds, to: controller.view) #expect(frame.minX >= 0 && frame.maxX <= width + 1) #expect(frame.height >= 44) } let labels = allViews(controller.view).compactMap { $0 as? UILabel } #expect(labels.contains { $0.text == "已结束" && $0.textColor == TrainingUI.muted }) #expect(labels.contains { $0.text == "任务已结束,仅可回顾课程内容" }) let action = try #require(allViews(controller.view).compactMap { $0 as? UIButton } .first { $0.accessibilityIdentifier == "training.task.action.ended" }) #expect(action.configuration?.title == "回顾学习") #expect(action.isEnabled) Attachment.record(render(navigation.view), named: "\(Int(width))点-已结束筛选与只读任务", as: .png) } } @Test("课程与考试步骤等宽居中,窄屏和大字体不裁切") func learningAndExamStepLayout() async throws { for width: CGFloat in [320, 390] { let domain = "training_step_layout_\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: domain)) defer { defaults.removePersistentDomain(forName: domain) } let context = TrainingContext(accountScope: domain, scenicID: 1, storeID: 1) let model = TrainingRemoteExamViewModel(taskID: "task_1", context: context, pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { context }) let source = TrainingDataStub() let course = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader()) let exam = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model) for (controller, selectedTitle) in [(course as UIViewController, "1 课程学习"), (exam, "2 在线考试")] { let navigation = UINavigationController(rootViewController: controller) let window = try makeWindow(navigation, width: width) defer { window.isHidden = true } let isReady: () -> Bool = { guard self.allViews(controller.view).contains(where: { $0 is TrainingStepView && !$0.isHidden }) else { return false } if controller === course { return self.allViews(controller.view).compactMap({ $0 as? TrainingDocumentPreviewView }).first?.isReady == true } return model.canEdit } let deadline = ContinuousClock.now.advanced(by: .seconds(15)) while !isReady(), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } #expect(isReady()) let steps = allViews(controller.view).compactMap { $0 as? TrainingStepView } #expect(steps.count == 1) let step = try #require(steps.first) navigation.view.layoutIfNeeded() let labels = allViews(step).compactMap { $0 as? UILabel } #expect(labels.map(\.text) == ["1 课程学习", "2 在线考试"]) let first = try #require(labels.first) let second = try #require(labels.last) #expect(abs(first.bounds.width - second.bounds.width) < 1) #expect(first.convert(first.bounds, to: step).maxX <= second.convert(second.bounds, to: step).minX) #expect(labels.allSatisfy { $0.textAlignment == .center }) #expect(labels.filter { $0.accessibilityTraits.contains(.selected) }.map(\.text) == [selectedTitle]) #expect(labels.first { $0.text == selectedTitle }?.textColor == TrainingUI.primary) #expect(step.bounds.height >= 44) if controller === course { let buttons = allViews(controller.view).compactMap { $0 as? UIButton } #expect(!buttons.contains { $0.accessibilityIdentifier == "training.reading.sections" || $0.accessibilityIdentifier == "training.reading.attachments" }) #expect(!buttons.contains { $0.configuration?.title == "章节目录" || $0.configuration?.title == "课程附件" }) #expect(!buttons.contains { $0.accessibilityIdentifier == "training.reading.documentPicker" }) #expect(!buttons.contains { $0.configuration?.title == "切换附件" || $0.configuration?.title == "培训资料.txt" }) let frame = step.convert(step.bounds, to: controller.view) #expect(abs(frame.minY - controller.view.safeAreaInsets.top - 8) < 1) let preview = try #require(allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first) let scroll = try #require(preview.superview?.superview as? UIScrollView) #expect(abs(scroll.frame.minY - frame.maxY - 8) < 1) let metadataLabels = allViews(controller.view).compactMap { $0 as? UILabel }.filter { ["training.reading.taskTitle", "training.reading.courseName", "training.reading.examInfo", "training.reading.introduction"].contains($0.accessibilityIdentifier ?? "") } #expect(metadataLabels.count == 4) for label in metadataLabels { let labelFrame = label.convert(label.bounds, to: scroll) #expect(labelFrame.minX >= 0 && labelFrame.maxX <= scroll.bounds.width + 1) #expect(label.numberOfLines == 0) } let web = try #require(allViews(preview).compactMap { $0 as? WKWebView }.first) if width == 390 { let webImage = try await web.takeSnapshot(configuration: nil) let image = UIGraphicsImageRenderer(size: navigation.view.bounds.size).image { _ in navigation.view.drawHierarchy(in: navigation.view.bounds, afterScreenUpdates: true) webImage.draw(in: web.convert(web.bounds, to: navigation.view)) } Attachment.record(image, named: "课程页原生信息与附件正文", as: .png) } } Attachment.record(render(step), named: "\(Int(width))点-\(selectedTitle)", as: .png) if width == 320 { navigation.setOverrideTraitCollection(UITraitCollection(preferredContentSizeCategory: .accessibilityExtraExtraExtraLarge), forChild: controller) navigation.view.layoutIfNeeded() #expect(first.font.pointSize > 13) for label in labels { let frame = label.convert(label.bounds, to: step) #expect(frame.minY >= 0 && frame.maxY <= step.bounds.height + 1) #expect(label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height <= label.bounds.height + 1) } Attachment.record(render(step), named: "大字体-\(selectedTitle)", as: .png) } if controller === course { step.configure(mode: .study) #expect(second.text == "完成学习") #expect(first.accessibilityTraits.contains(.selected)) } } } } @Test("未通过成绩可展开解析并返回已有课程,旧失败成绩在通过后不可重考") func resultLearningAndReviewNavigation() async throws { let source = TrainingDataStub() await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: false) } } let attempt = TrainingRemoteFixtures.attempt(passed: false) let center = TrainingCenterViewController(service: source) let course = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader()) let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source, documentLoader: TrainingFixtureDocumentLoader()) let navigation = UINavigationController() navigation.setViewControllers([center, course, result], animated: false) let window = try makeWindow(navigation) defer { window.isHidden = true } result.loadViewIfNeeded() await result.reload() try await settleTransitions(in: navigation) navigation.view.layoutIfNeeded() let learning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" }) let details = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.details" }) let action = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" }) #expect(action.configuration?.title == "再考一次") #expect(!allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem }) Attachment.record(render(navigation.view), named: "未通过成绩默认收起解析", as: .png) details.sendActions(for: .touchUpInside) let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while !allViews(result.view).compactMap({ $0 as? UILabel }).contains(where: { $0.text == TrainingRemoteFixtures.review().stem }), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } navigation.view.layoutIfNeeded() #expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem }) Attachment.record(render(navigation.view), named: "成绩答案解析展开", as: .png) learning.sendActions(for: .touchUpInside) try await waitForNavigation(in: navigation) { $0 === course } try await settleTransitions(in: navigation) #expect(navigation.topViewController === course) navigation.setViewControllers([center, result], animated: false) try await settleTransitions(in: navigation) await result.reload() let newLearning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" }) newLearning.sendActions(for: .touchUpInside) try await waitForNavigation(in: navigation) { ($0 as? TrainingCourseViewController)?.taskID == "task_1" } try await settleTransitions(in: navigation) #expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "task_1") await source.configure { $0.attemptHandler = { _ in TrainingAttemptDetail(attempt: TrainingRemoteFixtures.attempt(passed: false), taskState: TrainingRemoteFixtures.result(passed: true).taskState, serverTime: TrainingRemoteFixtures.now) } } let passed = TrainingRemoteFixtures.attempt(passed: true) navigation.setViewControllers([center, result], animated: false) try await settleTransitions(in: navigation) await result.reload() #expect(action.configuration?.title == "完成,返回培训中心") await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: true) } } let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source, documentLoader: TrainingFixtureDocumentLoader()) navigation.setViewControllers([center, passedResult], animated: false) try await settleTransitions(in: navigation) await passedResult.reload() navigation.view.layoutIfNeeded() Attachment.record(render(navigation.view), named: "通过成绩仍可返回学习", as: .png) let completion = try #require(allViews(passedResult.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" }) completion.sendActions(for: .touchUpInside) try await waitForNavigation(in: navigation) { $0 === center } try await settleTransitions(in: navigation) #expect(navigation.topViewController === center) } private func makeWindow(_ navigation: UINavigationController, width: CGFloat = 390) throws -> UIWindow { let scene = try #require(UIApplication.shared.connectedScenes.first as? UIWindowScene) let window = UIWindow(windowScene: scene) window.frame = CGRect(x: 0, y: 0, width: width, height: 844) window.rootViewController = navigation window.makeKeyAndVisible() navigation.view.layoutIfNeeded() return window } private func render(_ view: UIView) -> UIImage { UIGraphicsImageRenderer(size: view.bounds.size).image { context in view.layer.render(in: context.cgContext) } } @Test("100题答题卡可滚动并保留当前题与已答状态") func largeAnswerCardIsScrollable() async throws { let original = TrainingDemoFixtures.makePacks(now: Date())[0].task let questions = (0..<100).map { TrainingQuestion(id: "q\($0)", type: .single, stem: "题目\($0)", options: original.questions[0].options) } let task = TrainingTask(id: original.id, title: original.title, publisherName: nil, mode: .exam, status: .published, startAt: original.startAt, endAt: original.endAt, passScore: 80, scoring: original.scoring, course: original.course, questions: questions, progress: original.progress) let controller = TrainingAnswerCardViewController(task: task, answers: ["q0": ["A"], "q4": ["B"]], currentIndex: 4) let navigation = UINavigationController(rootViewController: controller) let window = try makeWindow(navigation) defer { window.isHidden = true } let collection = try #require(allViews(controller.view).first { $0 is UICollectionView } as? UICollectionView) let currentCell = try await waitForVisibleCell(at: IndexPath(item: 4, section: 0), in: collection) #expect(collection.numberOfItems(inSection: 0) == 100) #expect(collection.contentSize.height > collection.bounds.height) #expect(currentCell.accessibilityLabel == "第 5 题,已答,当前题") let firstCell = try #require(collection.cellForItem(at: IndexPath(item: 0, section: 0))) let secondRowCell = try #require(collection.cellForItem(at: IndexPath(item: 5, section: 0))) #expect(abs(firstCell.frame.minY - currentCell.frame.minY) < 1) #expect(currentCell.frame.maxX <= collection.bounds.width) #expect(secondRowCell.frame.minY > currentCell.frame.maxY) let image = UIGraphicsImageRenderer(size: controller.view.bounds.size).image { context in controller.view.layer.render(in: context.cgContext) } Attachment.record(image, named: "100题答题卡", as: .png) } /// 等待实际目标页面,避免转场尚未开始时误把 nil coordinator 当作完成。 private func waitForNavigation(in navigation: UINavigationController, matches: (UIViewController?) -> Bool) async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while !matches(navigation.topViewController), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } let reached = matches(navigation.topViewController) try #require(reached) } /// 前一导航动画结束后再执行后续操作,避免测试同时驱动互相冲突的转场。 private func settleTransitions(in navigation: UINavigationController) async throws { await Task.yield() let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while navigation.transitionCoordinator != nil, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } #expect(navigation.transitionCoordinator == nil) } /// 按实际可见状态等待差异化列表动画,超时后让测试明确失败。 private func waitForVisibleCell(at indexPath: IndexPath, in collection: UICollectionView) async throws -> UICollectionViewCell { let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while ContinuousClock.now < deadline { collection.layoutIfNeeded() if let cell = collection.cellForItem(at: indexPath) { return cell } try await Task.sleep(for: .milliseconds(10)) } return try #require(collection.cellForItem(at: indexPath)) } private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap(allViews) } private func isVisible(_ view: UIView) -> Bool { if view.isHidden { return false } return view.superview.map(isVisible) ?? true } } #endif