Files
suixinkan_uikit/suixinkanTests/TrainingUIRenderingTests.swift
T

262 lines
16 KiB
Swift

import Foundation
import Testing
import UIKit
@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?.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)
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)
}
@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)
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 deadline = ContinuousClock.now.advanced(by: .seconds(5))
while (!allViews(controller.view).contains { $0 is TrainingStepView }
|| (controller === exam && !model.canEdit)), ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
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)
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)
let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source)
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)
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