Files
suixinkan_uikit/suixinkanTests/TrainingUIRenderingTests.swift
T
lujiuyin 8862ae5401 feat(training): 同步培训中心学习答题功能
新增首页和个人页入口,支持课程阅读、答题卡、草稿恢复、成绩解析、历史记录与重考。保留独立的 Debug 本地演示数据源及后端接入协议,并对齐列表动画和答题卡布局约定。

来源:xh_test 的 74c451c。验证:iPhone 11 真机 59 项相关测试全部通过;全量测试中的 8 个既有失败已在同步前版本复现。
2026-10-13 15:54:31 +08:00

170 lines
11 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: source)
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 resultLearningAndReviewNavigation() async throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: directory) }
let source = TrainingDemoService(context: TrainingContext(accountScope: "result-render", scenicID: 1, storeID: 1), storage: TrainingDemoFileStorage(directory: directory))
for _ in 0..<20 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
let wrong: TrainingAnswers = ["q1": ["B"], "q2": ["C"], "q3": ["A"], "q4": ["D"]]
let attempt = try await source.submit(taskID: "demo-service", answers: wrong, submissionID: "failed")
let center = TrainingCenterViewController(service: source)
let course = TrainingCourseViewController(taskID: "demo-service", service: source)
let result = TrainingResultViewController(taskID: "demo-service", 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()
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 == attempt.reviews.first?.question.stem })
Attachment.record(render(navigation.view), named: "未通过成绩默认收起解析", as: .png)
details.sendActions(for: .touchUpInside)
navigation.view.layoutIfNeeded()
#expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem })
Attachment.record(render(navigation.view), named: "成绩答案解析展开", as: .png)
learning.sendActions(for: .touchUpInside)
#expect(navigation.topViewController === course)
navigation.setViewControllers([center, result], animated: false)
await result.reload()
let newLearning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" })
newLearning.sendActions(for: .touchUpInside)
#expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "demo-service")
let passed = try await source.submit(taskID: "demo-service", answers: ["q1": ["A"], "q2": ["A", "B"], "q3": ["B"], "q4": ["A", "B", "C"]], submissionID: "passed")
navigation.setViewControllers([center, result], animated: false)
await result.reload()
#expect(action.configuration?.title == "完成,返回培训中心")
let passedResult = TrainingResultViewController(taskID: "demo-service", attemptID: passed.id, service: source)
navigation.setViewControllers([center, passedResult], animated: false)
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)
#expect(navigation.topViewController === center)
}
private func makeWindow(_ navigation: UINavigationController) 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: 390, 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)
}
/// 按实际可见状态等待差异化列表动画,超时后让测试明确失败。
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