feat(training): 新增培训中心学习答题演示及成绩回顾

新增首页和个人页培训入口,支持课程阅读、答题卡、未交卷答案恢复、成绩记录及重考。
对齐小程序的培训首页与成绩页,答案解析默认收起并提供返回对应课程的入口。

开发版使用隔离的本机演示数据,正式培训服务尚未接入。
This commit is contained in:
han xin
2026-10-10 11:36:49 +08:00
parent e1175066b9
commit 74c451c5e5
17 changed files with 2612 additions and 7 deletions
+389
View File
@@ -0,0 +1,389 @@
import Foundation
import Testing
@testable import suixinkan
#if DEBUG
/// 所有状态均为每个测试独立创建的可失败存储。
private final class TrainingMemoryStorage: TrainingDemoStoring, @unchecked Sendable {
private let lock = NSLock()
private var values: [String: Data] = [:]
private var writeFailure = false
/// 模拟持久化失败,不修改原有记录。
func failWrites(_ value: Bool) { lock.lock(); defer { lock.unlock() }; writeFailure = value }
func read(key: String) throws -> Data? { lock.lock(); defer { lock.unlock() }; return values[key] }
func write(_ data: Data, key: String) throws {
lock.lock()
defer { lock.unlock() }
if writeFailure { throw TrainingError.saveFailed }
values[key] = data
}
}
/// 培训功能边界测试,仅 mock 数据源,不发起真实网络或提交成绩。
@Suite("培训中心学习与答题")
@MainActor
struct TrainingFeatureTests {
private let now = Date(timeIntervalSince1970: 1_800_000_000)
private let context = TrainingContext(accountScope: "scenic_user_1001", scenicID: 10, storeID: 3)
private let storage = TrainingMemoryStorage()
private func service(packs: [TrainingDemoPack]? = nil, date: Date? = nil,
context: TrainingContext? = nil) -> TrainingDemoService {
let date = date ?? now
let fixtures = packs ?? TrainingDemoFixtures.makePacks(now: now)
return TrainingDemoService(context: context ?? self.context, storage: storage, now: { date }, seed: { _ in fixtures })
}
private func readCourse(_ service: TrainingDemoService, id: String = "demo-service") async throws {
for _ in 0..<TrainingTask.requiredReadingSeconds { _ = try await service.recordReadingSecond(taskID: id) }
}
private var correctAnswers: TrainingAnswers { ["q1": ["A"], "q2": ["A", "B"], "q3": ["B"], "q4": ["A", "B", "C"]] }
@Test("任务卡入口随学习、草稿、通过和截止状态变化")
func taskCardActions() async throws {
let source = service()
var task = try await source.task(id: "demo-service")
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "去学习")
#expect(TrainingTaskPresentation(task: task, now: now).progressPercent == 0)
try await readCourse(source)
task = try await source.task(id: task.id)
#expect(TrainingTaskPresentation(task: task, now: now).canStartExam)
#expect(TrainingTaskPresentation(task: task, now: now).progressPercent == 100)
try await source.saveDraft(taskID: task.id, answers: ["q1": ["A"]])
task = try await source.task(id: task.id)
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "继续答题")
task.status = .closed
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "查看课程")
#expect(!TrainingTaskPresentation(task: task, now: now).canStartExam)
_ = try await source.submit(taskID: task.id, answers: correctAnswers, submissionID: "passed")
task = try await source.task(id: task.id)
#expect(TrainingTaskPresentation(task: task, now: now).actionTitle == "回顾学习")
#expect(!TrainingTaskPresentation(task: task, now: now).canStartExam)
}
@Test("首页统计、任务搜索与考试记录排序保持同一数据源")
func centerTabsSearchAndRecords() async throws {
let source = service()
let model = TrainingCenterViewModel()
await model.load(service: source)
#expect(model.pendingCount == 3)
#expect(model.completedCount == 0)
#expect(model.latestScore == "—")
model.keyword = "不会匹配"
#expect(model.visibleTasks.count == 3)
model.selectTab(.tasks)
model.keyword = "巩固练习"
#expect(model.visibleTasks.map(\.id) == ["demo-review"])
model.keyword = "景区服务规范与游客沟通"
#expect(model.visibleTasks.count == 3)
try await readCourse(source)
_ = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "passed")
await model.load(service: source)
#expect(model.pendingCount == 2)
#expect(model.completedCount == 1)
model.filter = .completed
#expect(model.visibleTasks.map(\.id) == ["demo-service"])
model.selectTab(.records)
#expect(model.keyword.isEmpty)
#expect(model.records.first?.attempt.id == "passed")
#expect(model.latestScore == "100")
}
@Test("未满20秒禁止考试,阅读完成与草稿可以恢复")
func readingGateAndPersistence() async throws {
let source = service()
for _ in 0..<19 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
await #expect(throws: TrainingError.readingRequired) {
try await source.saveDraft(taskID: "demo-service", answers: ["q1": ["A"]])
}
let finished = try await source.recordReadingSecond(taskID: "demo-service")
#expect(finished.hasFinishedReading)
#expect(finished.learnerStatus == .pendingExam)
try await source.saveDraft(taskID: finished.id, answers: ["q1": ["A"]])
let restored = try await service().task(id: finished.id)
#expect(restored.progress.readingSeconds == 20)
#expect(restored.progress.completedSectionIDs == ["section-1", "section-2"])
#expect(restored.progress.draftAnswers["q1"] == ["A"])
}
@Test("前后台暂停恢复不累计离开的时间,整秒才计时")
func foregroundClock() {
var clock = TrainingReadingClock()
clock.resume(at: 10)
let partial = clock.takeSecond(at: 10.99)
let whole = clock.takeSecond(at: 11)
#expect(!partial)
#expect(whole)
clock.pause()
let background = clock.takeSecond(at: 1000)
#expect(!background)
clock.resume(at: 1000)
let resumedPartial = clock.takeSecond(at: 1000.5)
let resumedWhole = clock.takeSecond(at: 1001)
let delayedTick = clock.takeSecond(at: 2000)
let repeatedTick = clock.takeSecond(at: 2000)
#expect(!resumedPartial)
#expect(resumedWhole)
#expect(delayedTick)
#expect(!repeatedTick)
}
@Test("仅学习任务读满即完成,不允许交卷")
func studyOnlyCompletion() async throws {
let source = service()
try await readCourse(source, id: "demo-study")
let task = try await source.task(id: "demo-study")
#expect(task.learnerStatus == .completed)
#expect(task.progress.attempts.isEmpty)
#expect(task.progress.completedAt == now)
await #expect(throws: TrainingError.self) {
try await source.submit(taskID: task.id, answers: [:], submissionID: "study")
}
}
@Test("多选少选、多选和错选均不得分", arguments: [Set(["A"]), Set(["A", "B", "C"]), Set(["B", "C"])])
func multipleChoiceRequiresExactAnswer(selected: Set<String>) async throws {
let source = service()
try await readCourse(source)
var answers = correctAnswers
answers["q2"] = selected
let attempt = try await source.submit(taskID: "demo-service", answers: answers, submissionID: "attempt")
#expect(attempt.correctCount == 3)
#expect(attempt.scoreText == "75")
#expect(!attempt.passed)
}
@Test("全对100分;交卷幂等,通过后不可再次提交")
func passingAndIdempotency() async throws {
let source = service()
try await readCourse(source)
let first = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "same")
let repeated = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "same")
#expect(first == repeated)
#expect(first.passed)
#expect(first.scoreText == "100")
let task = try await source.task(id: "demo-service")
#expect(task.progress.attempts.count == 1)
#expect(task.progress.draftAnswers.isEmpty)
#expect(task.learnerStatus == .completed)
await #expect(throws: TrainingError.self) {
try await source.submit(taskID: task.id, answers: correctAnswers, submissionID: "new")
}
}
@Test("未通过可不限次重考,保留每次成绩")
func unlimitedRetakesAndHistory() async throws {
let source = service()
try await readCourse(source)
var wrong = correctAnswers
wrong["q1"] = ["B"]
for number in 1...6 {
let result = try await source.submit(taskID: "demo-service", answers: wrong, submissionID: "fail-\(number)")
#expect(!result.passed)
}
let before = try await source.task(id: "demo-service")
#expect(before.learnerStatus == .pendingExam)
#expect(before.progress.attempts.count == 6)
let passed = try await source.submit(taskID: before.id, answers: correctAnswers, submissionID: "pass")
#expect(passed.passed)
let after = try await source.task(id: before.id)
#expect(after.progress.attempts.count == 7)
}
@Test("500题边界不逐题取整,小数舍去且按精确比例判断及格")
func exactPercentageScoring() async throws {
for (count, correct, passScore, score, passed) in [(100, 80, 80, "80", true), (3, 2, 67, "66.66", false), (499, 494, 99, "98.99", false), (500, 500, 100, "100", true)] {
let base = TrainingDemoFixtures.makePacks(now: now)[0].task
let questions = (0..<count).map { TrainingQuestion(id: "q\($0)", type: .single, stem: "题目\($0)", options: [TrainingOption(id: "A", text: "正确"), TrainingOption(id: "B", text: "错误")]) }
let task = TrainingTask(id: "score-\(count)", title: "计分", publisherName: nil, mode: .exam, status: .published,
startAt: base.startAt, endAt: base.endAt, passScore: passScore, scoring: base.scoring,
course: base.course, questions: questions, progress: TrainingProgress())
let solutions = Dictionary(uniqueKeysWithValues: questions.map { ($0.id, TrainingDemoSolution(correctIDs: ["A"], explanation: "解析")) })
let uniqueContext = TrainingContext(accountScope: "test_\(count)", scenicID: 10, storeID: 3)
let source = service(packs: [TrainingDemoPack(task: task, solutions: solutions)], context: uniqueContext)
try await readCourse(source, id: task.id)
let answers = Dictionary(uniqueKeysWithValues: questions.enumerated().map { ($0.element.id, Set([$0.offset < correct ? "A" : "B"])) })
let result = try await source.submit(taskID: task.id, answers: answers, submissionID: "score")
#expect(result.scoreText == score)
#expect(result.passed == passed)
}
}
@Test("开始边界可提交,截止边界不可提交")
func taskTimeBoundaries() async throws {
let source = service()
try await readCourse(source)
let task = try await source.task(id: "demo-service")
#expect(task.submissionBlockReason(now: task.startAt) == nil)
#expect(task.submissionBlockReason(now: task.startAt.addingTimeInterval(-0.01)) != nil)
#expect(task.submissionBlockReason(now: task.endAt.addingTimeInterval(-0.01)) == nil)
#expect(task.submissionBlockReason(now: task.endAt) != nil)
await #expect(throws: TrainingError.self) {
try await service(date: task.endAt).submit(taskID: task.id, answers: correctAnswers, submissionID: "late")
}
}
@Test("已关闭任务不可学习或交卷,历史仍可读取")
func closedTasksAreReadOnly() async throws {
var packs = TrainingDemoFixtures.makePacks(now: now)
packs[0].task.status = .closed
let source = service(packs: packs)
_ = try await source.task(id: "demo-service")
await #expect(throws: TrainingError.self) { try await source.recordReadingSecond(taskID: "demo-service") }
await #expect(throws: TrainingError.self) { try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "closed") }
}
@Test("无效选项、单选多选和漏答禁止交卷")
func rejectsInvalidAnswers() async throws {
let source = service()
try await readCourse(source)
for invalid in [["q1": Set(["unknown"])], ["unknown": Set(["A"])], ["q1": Set(["A", "B"])]] {
await #expect(throws: TrainingError.invalidAnswers) { try await source.saveDraft(taskID: "demo-service", answers: invalid) }
}
await #expect(throws: TrainingError.unanswered(4)) {
try await source.submit(taskID: "demo-service", answers: [:], submissionID: "empty")
}
}
@Test("未知计分版本及重复选项明确拒绝")
func rejectsInvalidPaper() throws {
let base = TrainingDemoFixtures.makePacks(now: now)[0].task
let old = TrainingTask(id: base.id, title: base.title, publisherName: nil, mode: .exam, status: .published,
startAt: base.startAt, endAt: base.endAt, passScore: 100, scoring: "unknown",
course: base.course, questions: base.questions, progress: base.progress)
#expect(throws: TrainingError.invalidPaper) { try TrainingValidation.validatePaper(old) }
let question = TrainingQuestion(id: "q", type: .single, stem: "重复", options: [TrainingOption(id: "A", text: "一"), TrainingOption(id: "A", text: "二")])
let invalid = TrainingTask(id: base.id, title: base.title, publisherName: nil, mode: .exam, status: .published,
startAt: base.startAt, endAt: base.endAt, passScore: 100, scoring: base.scoring,
course: base.course, questions: [question], progress: base.progress)
#expect(throws: TrainingError.invalidPaper) { try TrainingValidation.validatePaper(invalid) }
}
@Test("保存失败不放行阅读、不丢草稿、不新增成绩")
func failedPersistenceDoesNotCompleteOrSubmit() async throws {
let source = service()
for _ in 0..<19 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
storage.failWrites(true)
await #expect(throws: TrainingError.saveFailed) { try await source.recordReadingSecond(taskID: "demo-service") }
let unfinished = try await source.task(id: "demo-service")
#expect(!unfinished.hasFinishedReading)
#expect(unfinished.progress.readingSeconds == 19)
storage.failWrites(false)
_ = try await source.recordReadingSecond(taskID: "demo-service")
try await source.saveDraft(taskID: "demo-service", answers: correctAnswers)
storage.failWrites(true)
await #expect(throws: TrainingError.saveFailed) { try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "retry") }
let unchanged = try await source.task(id: "demo-service")
#expect(unchanged.progress.attempts.isEmpty)
#expect(unchanged.progress.draftAnswers == correctAnswers)
storage.failWrites(false)
_ = try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "retry")
let submitted = try await source.task(id: "demo-service")
#expect(submitted.progress.attempts.count == 1)
}
@Test("账号、景区、店铺分别隔离;身份切换拒绝旧页面操作")
func accountAndScenicIsolation() async throws {
try await readCourse(service())
for other in [TrainingContext(accountScope: "store_user_1001", scenicID: 10, storeID: 3),
TrainingContext(accountScope: context.accountScope, scenicID: 11, storeID: 3),
TrainingContext(accountScope: context.accountScope, scenicID: 10, storeID: 4)] {
let task = try await service(context: other).task(id: "demo-service")
#expect(task.progress.readingSeconds == 0)
}
let denied = TrainingDemoService(context: context, storage: storage, validateContext: { false })
await #expect(throws: TrainingError.identityChanged) { try await denied.listTasks() }
await #expect(throws: TrainingError.identityChanged) { try await denied.saveDraft(taskID: "demo-service", answers: [:]) }
}
@Test("损坏或未知版本数据不被自动重建覆盖")
func corruptDataIsPreserved() async throws {
for data in [Data("broken".utf8), Data(#"{"version":999,"packs":[]}"#.utf8)] {
try storage.write(data, key: context.storageKey)
await #expect(throws: TrainingError.corruptStorage) { try await service().listTasks() }
#expect(try storage.read(key: context.storageKey) == data)
}
}
@Test("首次演示快照保持固定,不随示例更新重置")
func taskSnapshotsRemainFrozen() async throws {
let original = try await service().task(id: "demo-service")
let changed = try await service(packs: [], date: now.addingTimeInterval(30 * 86400)).task(id: "demo-service")
#expect(original == changed)
}
@Test("草稿恢复、单选替换、多选切换、漏答定位和安全跳转")
func examViewModelBehavior() async throws {
let source = service()
try await readCourse(source)
try await source.saveDraft(taskID: "demo-service", answers: ["q1": ["B"]])
let model = TrainingExamViewModel(taskID: "demo-service")
await model.load(service: source, now: now)
#expect(model.answers["q1"] == ["B"])
await model.select(optionID: "A", service: source)
#expect(model.answers["q1"] == ["A"])
model.goToQuestion(1)
await model.select(optionID: "A", service: source)
await model.select(optionID: "B", service: source)
#expect(model.answers["q2"] == ["A", "B"])
await model.select(optionID: "B", service: source)
#expect(model.answers["q2"] == ["A"])
model.goToQuestion(999)
#expect(model.currentIndex == 1)
#expect(await model.submit(service: source) == nil)
#expect(model.currentIndex == 2)
#expect(model.answeredCount == 2)
}
@Test("答案保存失败保留原选择,重考清空草稿")
func examViewModelSaveFailureAndRetake() async throws {
let source = service()
try await readCourse(source)
try await source.saveDraft(taskID: "demo-service", answers: ["q1": ["B"]])
let model = TrainingExamViewModel(taskID: "demo-service")
await model.load(service: source, now: now)
storage.failWrites(true)
await model.select(optionID: "A", service: source)
#expect(model.answers["q1"] == ["B"])
#expect(model.errorMessage != nil)
storage.failWrites(false)
await model.load(service: source, now: now, resetDraft: true)
#expect(model.answers.isEmpty)
let task = try await source.task(id: "demo-service")
#expect(task.progress.draftAnswers.isEmpty)
}
@Test("正式入口无示例任务、不可记录学习或提交成绩")
func productionServiceIsUnconnected() async throws {
let source = TrainingServiceFactory.production()
#expect(!source.isDemo)
await #expect(throws: TrainingError.unavailable) { try await source.listTasks() }
await #expect(throws: TrainingError.unavailable) { try await source.recordReadingSecond(taskID: "demo-service") }
await #expect(throws: TrainingError.unavailable) { try await source.submit(taskID: "demo-service", answers: correctAnswers, submissionID: "real") }
let model = TrainingCenterViewModel()
await model.load(service: source)
#expect(model.tasks.isEmpty)
#expect(model.errorMessage != nil)
}
@Test("首页所有角色都有培训入口,服务端下发时不重复")
func trainingEntryForEveryRole() {
let suite = "TrainingMenuTests-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: suite) else { Issue.record("无法创建独立存储"); return }
defer { defaults.removePersistentDomain(forName: suite) }
let appStore = AppStore(defaults: defaults)
appStore.session.userId = "1001"
appStore.session.accountType = .scenicUser
for role in AppRoleCode.allCases {
appStore.session.roleCode = role.rawValue
appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")])
let model = HomeViewModel(appStore: appStore, commonMenuStore: HomeCommonMenuStore(defaults: defaults))
model.rebuildCommonMenus()
#expect(model.commonMenus.filter { $0.uri == "/training" }.count == 1)
}
#expect(HomeMenuCatalog.item(for: "/training")?.title == "培训中心")
}
}
#endif