import Foundation import Testing import UIKit @testable import suixinkan /// 注入一次失败,验证重试仍保持同一请求内容。 private actor TrainingExamFailureCounter { private var value = 0 /// 返回本次调用序号。 func next() -> Int { value += 1; return value } } /// 为当前页失败和恢复测试建立稀疏草稿响应。 private enum TrainingExamDraftFixtures { /// 仅返回请求题位范围内的答案,元信息仍覆盖完整试卷。 static func page(total: Int, revision: Int, answers: [Int: [String]], offset: Int, limit: Int) -> TrainingDraftPage { let orders = answers.filter { !$0.value.isEmpty }.keys.sorted() let end = min(total, offset + limit) let items = limit > 0 ? orders.filter { $0 > offset && $0 <= end }.map { TrainingDraftAnswerItem(questionID: "q\($0)", order: $0, selectedOptionIDs: answers[$0] ?? []) } : [] return TrainingDraftPage(taskID: "task_1", paperSnapshotID: "paper_1", draftRevision: revision, savedAt: TrainingRemoteFixtures.now, lastQuestionOrder: 1, answeredCount: orders.count, answeredQuestionOrders: orders, total: total, offset: offset, nextOffset: limit > 0 && end < total ? end : nil, hasMore: limit > 0 && end < total, items: items) } } /// 可在请求之间切换的业务身份,不依赖 AppStore 单例。 @MainActor private final class TrainingExamTestIdentity { var context: TrainingContext? /// 固定测试开始时的账号范围。 init(_ context: TrainingContext) { self.context = context } } /// 正式分页答题、版本保存及未知交卷恢复测试;全部使用内存网络替身。 @Suite("培训中心正式答题与交卷恢复") @MainActor struct TrainingRemoteExamTests { private let context = TrainingContext(accountScope: "exam_user", scenicID: 10, storeID: 3) private func makeDefaults() throws -> (name: String, defaults: UserDefaults) { let name = "TrainingRemoteExamTests-\(UUID().uuidString)" return (name, try #require(UserDefaults(suiteName: name))) } private func makeModel(defaults: UserDefaults, identity: TrainingExamTestIdentity? = nil) -> TrainingRemoteExamViewModel { let scope = identity?.context ?? context return TrainingRemoteExamViewModel(taskID: "task_1", context: scope, pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { if let identity { return identity.context }; return scope }) } @Test("500题恢复和随机跳题只下载所在页,已答状态来自全局题号") func lazyPagesAndGlobalAnswers() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 500 let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 6, answers: ["q401": ["A"], "q500": ["B"]], lastOrder: 401) let model = makeModel(defaults: domain.defaults) await model.load(service: source) #expect(model.currentIndex == 400) #expect(model.currentQuestion?.id == "q401") #expect(model.currentSelectedIDs == ["A"]) #expect(model.answeredCount == 2) #expect(model.firstUnansweredIndex == 0) await model.goToQuestion(499, service: source) #expect(model.currentSelectedIDs == ["B"]) await model.goToQuestion(400, service: source) await model.goToQuestion(500, service: source) #expect(model.currentIndex == 400) let calls = await source.calls #expect(calls.filter { $0.name == "questions" }.map(\.offset) == [400, 490]) #expect(calls.filter { $0.name == "questions" }.allSatisfy { $0.limit == 10 }) #expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 10]) #expect(model.answeredQuestionOrders == [401, 500]) } @Test("响应按字节预算缩页时,随机目标直接补取而不扫描全卷") func shortPageRandomAccess() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionsHandler = { offset, _ in let end = min(30, offset + 3) return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset, nextOffset: end < 30 ? end : nil, hasMore: end < 30, items: ((offset + 1)...end).map(TrainingRemoteFixtures.question)) } configuration.draftHandler = { offset, limit in let end = limit == 0 ? offset : min(30, offset + 3) let items: [TrainingDraftAnswerItem] = limit > 0 && offset < 19 && end >= 19 ? [TrainingDraftAnswerItem(questionID: "q19", order: 19, selectedOptionIDs: ["B"])] : [] return TrainingDraftPage(taskID: "task_1", paperSnapshotID: "paper_1", draftRevision: 1, savedAt: TrainingRemoteFixtures.now, lastQuestionOrder: 1, answeredCount: 1, answeredQuestionOrders: [19], total: 30, offset: offset, nextOffset: limit > 0 && end < 30 ? end : nil, hasMore: limit > 0 && end < 30, items: items) } configuration.saveHandler = { request in TrainingDraftConfirmation(draftRevision: request.baseRevision, savedAt: TrainingRemoteFixtures.now, answeredCount: 1) } let source = TrainingDataStub(configuration: configuration) let model = makeModel(defaults: domain.defaults) await model.load(service: source) await model.goToQuestion(18, service: source) #expect(model.currentQuestion?.id == "q19") #expect(model.currentSelectedIDs == ["B"]) #expect(model.firstUnansweredIndex == 0) let calls = await source.calls #expect(calls.filter { $0.name == "questions" }.map(\.offset) == [0, 10, 18]) #expect(calls.filter { $0.name == "draft" && $0.limit != 0 }.map(\.offset) == [0, 10, 18]) } @Test("全部已答即使只缓存一页也可交卷,不全量读取或回传草稿") func submitSavedRevisionWithoutReadingWholeDraft() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 500 let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 15, answers: Dictionary(uniqueKeysWithValues: (1...500).map { ("q\($0)", ["A"]) })) let model = makeModel(defaults: domain.defaults) await model.load(service: source) #expect(model.answeredCount == 500) #expect(model.firstUnansweredIndex == nil) #expect(await model.submit(service: source)?.id == "attempt_1") let requests = await source.submissionRequests #expect(requests.count == 1) #expect(requests.first?.draftRevision == 15) #expect(requests.first?.paperSnapshotID == "paper_1") let calls = await source.calls #expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10]) #expect(calls.filter { $0.name == "questions" }.count == 1) #expect(!model.hasPendingSubmission) #expect(model.submittedResult?.attempt.id == "attempt_1") } @Test("选择仅保存一题变化且使用最新确认版本") func incrementalSaveAndRevision() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let source = TrainingDataStub() let model = makeModel(defaults: domain.defaults) await model.load(service: source) await model.select(optionID: "A", service: source) #expect(model.draftRevision == 2) #expect(model.answeredQuestionOrders == [1]) await model.select(optionID: "B", service: source) let requests = await source.savedRequests #expect(requests.map(\.baseRevision) == [1, 2]) #expect(requests.allSatisfy { $0.changes.count == 1 && $0.changes.first?.questionID == "q1" }) #expect(requests.last?.changes.first?.selectedOptionIDs == ["B"]) #expect(requests[0].requestID != requests[1].requestID) #expect(model.currentSelectedIDs == ["B"]) #expect(model.answeredCount == 1) } @Test("多选切换提交规范化集合,取消一项不丢失其它选择") func multipleChoiceIncrementalToggle() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionsHandler = { offset, limit in let end = min(30, offset + limit) let questions = ((offset + 1)...end).map { order -> TrainingQuestionItem in let original = TrainingRemoteFixtures.question(order) return TrainingQuestionItem(id: original.id, order: order, type: order == 1 ? .multiple : .single, stem: original.stem, options: original.options) } return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset, nextOffset: end < 30 ? end : nil, hasMore: end < 30, items: questions) } let source = TrainingDataStub(configuration: configuration) let model = makeModel(defaults: domain.defaults) await model.load(service: source) await model.select(optionID: "A", service: source) await model.select(optionID: "B", service: source) await model.select(optionID: "A", service: source) #expect(model.currentSelectedIDs == ["B"]) #expect((await source.savedRequests).map { $0.changes.first?.selectedOptionIDs } == [["A"], ["A", "B"], ["B"]]) #expect(model.answeredCount == 1) } @Test("保存超时暂停编辑,重试同ID同版本同内容") func saveFailureRetainsOriginalRequest() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let counter = TrainingExamFailureCounter() var configuration = TrainingDataStub.Configuration() configuration.saveHandler = { request in if await counter.next() == 1 { throw URLError(.timedOut) } return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1, savedAt: TrainingRemoteFixtures.now, answeredCount: 1) } let source = TrainingDataStub(configuration: configuration) let model = makeModel(defaults: domain.defaults) await model.load(service: source) await model.select(optionID: "A", service: source) #expect(model.hasPendingMutation) #expect(!model.canEdit) #expect(model.currentSelectedIDs.isEmpty) await model.select(optionID: "B", service: source) #expect(await source.savedRequests.count == 1) await model.retryMutation(service: source) let requests = await source.savedRequests #expect(requests.count == 2) #expect(requests[0] == requests[1]) #expect(model.currentSelectedIDs == ["A"]) #expect(!model.hasPendingMutation) } @Test("版本冲突读取最新元信息与当前页,不覆盖其它设备的新答案") func conflictRefreshesCurrentPage() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let source = TrainingDataStub() let model = makeModel(defaults: domain.defaults) await model.load(service: source) await source.seedDraft(revision: 8, answers: ["q1": ["B"], "q10": ["A"]]) await model.select(optionID: "A", service: source) #expect(model.draftRevision == 8) #expect(model.currentSelectedIDs == ["B"]) #expect(model.answeredCount == 2) #expect(model.errorMessage != nil) #expect(!model.hasPendingMutation) #expect(await source.savedRequests.count == 1) let calls = await source.calls #expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 0, 10]) } @Test("重置超时沿原键恢复,成功响应含新答案时不盲清") func resetRetryUsesCurrentDraftState() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let counter = TrainingExamFailureCounter() var configuration = TrainingDataStub.Configuration() configuration.resetHandler = { _ in if await counter.next() == 1 { throw URLError(.networkConnectionLost) } return TrainingDraftConfirmation(draftRevision: 5, savedAt: TrainingRemoteFixtures.now, answeredCount: 1) } let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 3, answers: ["q1": ["A"]]) let model = makeModel(defaults: domain.defaults) await model.load(service: source, resetDraft: true) #expect(model.hasPendingMutation) await source.seedDraft(revision: 5, answers: ["q1": ["B"]]) await model.retryMutation(service: source) let requests = await source.resetRequests #expect(requests.count == 2) #expect(requests[0] == requests[1]) #expect(model.draftRevision == 5) #expect(model.currentSelectedIDs == ["B"]) #expect(model.answeredQuestionOrders == [1]) #expect(!model.hasPendingMutation) } @Test("未知交卷跨页面重建恢复;查询0条重试原请求,通过后也可找回原成绩") func durableUnknownSubmissionRecovery() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 3 configuration.submitHandler = { _ in throw URLError(.timedOut) } let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 7, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) let first = makeModel(defaults: domain.defaults) await first.load(service: source) #expect(await first.submit(service: source) == nil) #expect(first.hasPendingSubmission) #expect(!first.canEdit) let stored = try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) let saved = try #require(stored) let second = makeModel(defaults: domain.defaults) await second.load(service: source) #expect(second.hasPendingSubmission) let requests = await source.submissionRequests #expect(requests.count == 2) #expect(requests[0] == requests[1]) #expect(requests[1] == saved.request) await source.configure { $0.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) } $0.attemptsHandler = { _, _, _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attempt()], nextCursor: nil, hasMore: false, serverTime: nil) } } let restored = makeModel(defaults: domain.defaults) await restored.load(service: source) #expect(restored.submittedAttempt?.id == "attempt_1") #expect(restored.submittedResult?.taskState.canRetry == false) #expect(!restored.hasPendingSubmission) #expect(await source.submissionRequests.count == 2) #expect(try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) == nil) } @Test("账号景区店铺隔离待确认请求,身份切换不消费旧账号记录") func pendingScopeAndIdentityIsolation() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let store = TrainingPendingSubmissionStore(defaults: domain.defaults) let pending = TrainingPendingSubmission(taskID: "task_1", request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 4), context: context) try store.save(pending) for different in [TrainingContext(accountScope: "other", scenicID: 10, storeID: 3), TrainingContext(accountScope: context.accountScope, scenicID: 11, storeID: 3), TrainingContext(accountScope: context.accountScope, scenicID: 10, storeID: 4)] { #expect(try store.load(taskID: "task_1", context: different) == nil) } let identity = TrainingExamTestIdentity(TrainingContext(accountScope: "other", scenicID: 10, storeID: 3)) let source = TrainingDataStub() await source.seedDraft(revision: 2, answers: ["q1": ["B"]]) let model = makeModel(defaults: domain.defaults, identity: identity) await model.load(service: source) #expect(model.currentQuestion?.id == "q1") #expect(model.currentSelectedIDs == ["B"]) #expect(!model.hasPendingSubmission) #expect(!(await source.calls).contains { $0.name == "attempts" || $0.name == "submit" }) #expect(try store.load(taskID: "task_1", context: context) == pending) identity.context = context await model.validateIdentity() #expect(model.isIdentityInvalid) #expect(model.shouldReturnToCenter) #expect(model.currentQuestion == nil) #expect(model.currentSelectedIDs.isEmpty) #expect(model.task == nil && model.progress == nil && model.paper == nil) #expect(model.answeredQuestionOrders.isEmpty) #expect(!model.canEdit) #expect(try store.load(taskID: "task_1", context: context) == pending) var failedConfiguration = TrainingDataStub.Configuration() failedConfiguration.submitHandler = { _ in throw URLError(.timedOut) } let failed = TrainingDataStub(configuration: failedConfiguration) identity.context = context let original = makeModel(defaults: domain.defaults, identity: identity) await original.load(service: failed) #expect(original.hasPendingSubmission) identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3) _ = await original.submit(service: failed) #expect(original.isIdentityInvalid) #expect(original.shouldReturnToCenter) #expect(original.currentQuestion == nil) #expect(await failed.submissionRequests.count == 1) #expect(try store.load(taskID: "task_1", context: context) == pending) } @Test("同任务页面不能覆盖待确认记录,交卷前优先恢复已有持久化键") func existingPendingRequestCannotBeOverwritten() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 3 configuration.submitHandler = { _ in throw URLError(.timedOut) } let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 9, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) let model = makeModel(defaults: domain.defaults) await model.load(service: source) let store = TrainingPendingSubmissionStore(defaults: domain.defaults) let pending = TrainingPendingSubmission(taskID: "task_1", request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 9), context: context) try store.save(pending) let replacement = TrainingPendingSubmission(taskID: "task_1", request: TrainingSubmissionRequest(submissionID: "replacement", paperSnapshotID: "paper_1", draftRevision: 9), context: context) #expect(throws: TrainingPendingSubmissionError.alreadyPending) { try store.save(replacement) } #expect(await model.submit(service: source) == nil) #expect(await source.submissionRequests == [pending.request]) #expect(try store.load(taskID: "task_1", context: context) == pending) } @Test("服务端已完成资格阻止读取试卷和新的交卷") func completedGatePreventsNewSubmission() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) } let source = TrainingDataStub(configuration: configuration) let model = makeModel(defaults: domain.defaults) await model.load(service: source) #expect(!model.canEdit) #expect(await model.submit(service: source) == nil) #expect(!(await source.calls).contains { $0.name == "paper" || $0.name == "questions" || $0.name == "submit" }) } @Test("明确漏答业务拒绝释放待确认请求,并恢复最新漏答题号") func definiteRejectionReleasesPendingSubmission() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 3 let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 4, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) await source.configure { $0.submitHandler = { request in await source.seedDraft(revision: request.draftRevision, answers: ["q1": ["A"], "q2": ["A"]]) throw TrainingRemoteError.answerIncomplete("第3题尚未作答") } } let model = makeModel(defaults: domain.defaults) await model.load(service: source) #expect(await model.submit(service: source) == nil) #expect(!model.hasPendingSubmission) #expect(model.answeredCount == 2) #expect(model.firstUnansweredIndex == 2) #expect(try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) == nil) } @Test("题目成功而草稿页失败时禁止编辑,多选恢复后保留原B再加入A") func failedDraftPageCannotOverwriteUnloadedAnswers() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let counter = TrainingExamFailureCounter() var configuration = TrainingDataStub.Configuration() configuration.questionCount = 20 configuration.questionsHandler = { offset, limit in let end = min(20, offset + limit) let items = ((offset + 1)...end).map { order -> TrainingQuestionItem in let original = TrainingRemoteFixtures.question(order) return TrainingQuestionItem(id: original.id, order: order, type: order == 11 ? .multiple : .single, stem: original.stem, options: original.options) } return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 20, offset: offset, nextOffset: end < 20 ? end : nil, hasMore: end < 20, items: items) } configuration.draftHandler = { offset, limit in if offset == 10, limit > 0, await counter.next() == 1 { throw URLError(.timedOut) } return TrainingExamDraftFixtures.page(total: 20, revision: 3, answers: [1: ["A"], 11: ["B"]], offset: offset, limit: limit) } let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 3, answers: ["q1": ["A"], "q11": ["B"]]) let model = makeModel(defaults: domain.defaults) await model.load(service: source) await model.goToQuestion(10, service: source) #expect(model.currentQuestion?.id == "q11") #expect(!model.isCurrentPageReady) #expect(!model.canEdit) #expect(model.canRetryCurrentPage) await model.select(optionID: "A", service: source) #expect(await source.savedRequests.isEmpty) await model.retryCurrentPage(service: source) #expect(model.currentSelectedIDs == ["B"]) #expect(model.canEdit) await model.select(optionID: "A", service: source) #expect((await source.savedRequests).last?.changes.first?.selectedOptionIDs == ["A", "B"]) await model.goToQuestion(0, service: source) #expect(model.currentSelectedIDs == ["A"]) #expect((await source.calls).filter { $0.name == "draft" && $0.offset == 0 }.count == 2) } @Test("冲突后元信息刷新断网仍有当前页重试入口,不会永久锁页") func conflictRefreshFailureCanRetryCurrentPage() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let source = TrainingDataStub() let model = makeModel(defaults: domain.defaults) await model.load(service: source) await source.seedDraft(revision: 8, answers: ["q1": ["B"]]) let counter = TrainingExamFailureCounter() await source.configure { $0.draftHandler = { offset, limit in if await counter.next() == 1 { throw URLError(.networkConnectionLost) } return TrainingExamDraftFixtures.page(total: 30, revision: 8, answers: [1: ["B"]], offset: offset, limit: limit) } } await model.select(optionID: "A", service: source) #expect(!model.canEdit) #expect(model.canRetryCurrentPage) #expect(!model.hasPendingMutation) await model.retryCurrentPage(service: source) #expect(model.currentSelectedIDs == ["B"]) #expect(model.draftRevision == 8) #expect(model.canEdit) #expect(await source.savedRequests.count == 1) } @Test("交卷成功时考试页被覆盖,返回后仍直接进入已有成绩") func coveredExamPresentsCompletedResultWhenVisibleAgain() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 3 let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 2, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) let model = makeModel(defaults: domain.defaults) let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model) let navigation = UINavigationController(rootViewController: controller) let window = try makeWindow(navigation) defer { window.isHidden = true } let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while !model.canEdit, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } #expect(model.canEdit) try await settleTransitions(in: navigation) let covering = UIViewController() navigation.pushViewController(covering, animated: false) try await settleTransitions(in: navigation) #expect(await model.submit(service: source)?.id == "attempt_1") #expect(navigation.topViewController === covering) navigation.popViewController(animated: true) let resultDeadline = ContinuousClock.now.advanced(by: .seconds(3)) while !(navigation.topViewController is TrainingResultViewController), ContinuousClock.now < resultDeadline { try await Task.sleep(for: .milliseconds(10)) } try await settleTransitions(in: navigation) #expect(navigation.topViewController is TrainingResultViewController) #expect(!(await source.calls).contains { $0.name == "attempt" }) } @Test("身份切换后返回考试页清理旧数据并退出根页面,保留未知交卷键") func changedIdentityReturnsToRootWithoutConsumingSubmission() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.questionCount = 3 configuration.submitHandler = { _ in throw URLError(.timedOut) } let source = TrainingDataStub(configuration: configuration) await source.seedDraft(revision: 2, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]]) let identity = TrainingExamTestIdentity(context) let model = makeModel(defaults: domain.defaults, identity: identity) let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model) let root = UIViewController() let center = TrainingCenterViewController(service: source) let navigation = UINavigationController() navigation.setViewControllers([root, center, controller], animated: false) let window = try makeWindow(navigation) defer { window.isHidden = true } let deadline = ContinuousClock.now.advanced(by: .seconds(3)) while !model.canEdit, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } #expect(model.canEdit) try await settleTransitions(in: navigation) let covering = UIViewController() navigation.pushViewController(covering, animated: false) try await settleTransitions(in: navigation) #expect(await model.submit(service: source) == nil) let store = TrainingPendingSubmissionStore(defaults: domain.defaults) let stored = try store.load(taskID: "task_1", context: context) let pending = try #require(stored) identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3) navigation.popViewController(animated: true) let exitDeadline = ContinuousClock.now.advanced(by: .seconds(3)) while navigation.topViewController !== root, ContinuousClock.now < exitDeadline { try await Task.sleep(for: .milliseconds(10)) } try await settleTransitions(in: navigation) #expect(navigation.topViewController === root) #expect(model.isIdentityInvalid && model.shouldReturnToCenter) #expect(model.currentQuestion == nil && model.submittedAttempt == nil) #expect(try store.load(taskID: "task_1", context: context) == pending) #expect(await source.submissionRequests.count == 1) } private func makeWindow(_ navigation: UINavigationController) throws -> UIWindow { let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) let window = UIWindow(windowScene: scene) window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) window.rootViewController = navigation navigation.beginAppearanceTransition(true, animated: false) window.isHidden = false navigation.endAppearanceTransition() navigation.view.layoutIfNeeded() return window } private func settleTransitions(in navigation: UINavigationController) async throws { // 非动画栈替换也可能在当前 main loop 中尚未结束。 try await Task.sleep(for: .milliseconds(20)) 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) } @Test("再次加载重考页刷新资格但不重复清稿") func returningExamDoesNotRepeatInitialReset() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } let source = TrainingDataStub() await source.seedDraft(revision: 3, answers: ["q1": ["A"]]) let model = makeModel(defaults: domain.defaults) await model.load(service: source, resetDraft: true) await model.select(optionID: "B", service: source) await model.load(service: source, resetDraft: true) #expect(await source.resetRequests.count == 1) #expect(model.currentSelectedIDs == ["B"]) } @Test("未知交卷恢复遇权限拒绝请求退出考试,但保留原持久化提交键") func forbiddenRecoveryRetainsOriginalSubmission() async throws { let domain = try makeDefaults() defer { domain.defaults.removePersistentDomain(forName: domain.name) } var configuration = TrainingDataStub.Configuration() configuration.submitHandler = { _ in throw TrainingRemoteError.forbidden("任务暂不可访问") } let source = TrainingDataStub(configuration: configuration) let store = TrainingPendingSubmissionStore(defaults: domain.defaults) let pending = TrainingPendingSubmission(taskID: "task_1", request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 3), context: context) try store.save(pending) let model = makeModel(defaults: domain.defaults) await model.load(service: source) #expect(model.shouldReturnToCenter) #expect(model.hasPendingSubmission) #expect(try store.load(taskID: "task_1", context: context) == pending) #expect(await source.submissionRequests == [pending.request]) } }