perf(training): 优化答题自动保存与培训页面交互
This commit is contained in:
@@ -0,0 +1,150 @@
|
|||||||
|
import Foundation
|
||||||
|
import CryptoKit
|
||||||
|
|
||||||
|
/// 一题尚未确认的本机选择,题号用于离线恢复答题卡。
|
||||||
|
struct TrainingDraftLocalAnswer: Codable, Equatable, Sendable {
|
||||||
|
let questionID: String
|
||||||
|
let order: Int
|
||||||
|
let selectedOptionIDs: [String]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 持久保存本机意图和已冻结的请求;账号范围中不保存登录凭证。
|
||||||
|
struct TrainingDraftRecord: Codable, Equatable, Sendable {
|
||||||
|
var generation: String = UUID().uuidString
|
||||||
|
let taskID: String
|
||||||
|
let paperSnapshotID: String
|
||||||
|
let accountScope: String
|
||||||
|
let scenicID: Int
|
||||||
|
let storeID: Int
|
||||||
|
var revision: Int
|
||||||
|
var answers: [TrainingDraftLocalAnswer]
|
||||||
|
var lastQuestionOrder: Int?
|
||||||
|
var pendingSave: TrainingDraftSaveRequest?
|
||||||
|
var pendingReset: TrainingDraftResetRequest?
|
||||||
|
var hasConflict: Bool
|
||||||
|
|
||||||
|
/// 用固定的业务身份建立草稿日志。
|
||||||
|
init(taskID: String, paperSnapshotID: String, context: TrainingContext, revision: Int,
|
||||||
|
answers: [TrainingDraftLocalAnswer] = [], lastQuestionOrder: Int? = nil,
|
||||||
|
pendingSave: TrainingDraftSaveRequest? = nil, pendingReset: TrainingDraftResetRequest? = nil,
|
||||||
|
hasConflict: Bool = false) {
|
||||||
|
self.taskID = taskID
|
||||||
|
self.paperSnapshotID = paperSnapshotID
|
||||||
|
accountScope = context.accountScope
|
||||||
|
scenicID = context.scenicID
|
||||||
|
storeID = context.storeID
|
||||||
|
self.revision = revision
|
||||||
|
self.answers = answers
|
||||||
|
self.lastQuestionOrder = lastQuestionOrder
|
||||||
|
self.pendingSave = pendingSave
|
||||||
|
self.pendingReset = pendingReset
|
||||||
|
self.hasConflict = hasConflict
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 草稿所属的账号、景区和店铺。
|
||||||
|
var context: TrainingContext { TrainingContext(accountScope: accountScope, scenicID: scenicID, storeID: storeID) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 损坏日志或其它页面接管日志时,禁止继续覆盖未确认答案。
|
||||||
|
enum TrainingDraftStorageError: Error, LocalizedError, Equatable {
|
||||||
|
case invalidRecord, replaced, unavailable
|
||||||
|
|
||||||
|
/// 可呈现给用户的草稿恢复错误。
|
||||||
|
var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .invalidRecord: "本机未保存答案暂无法恢复,请保留当前页面并重试"
|
||||||
|
case .replaced: "此任务已在另一答题页面打开,请返回后重新进入"
|
||||||
|
case .unavailable: "未能保存本机答案,请检查可用空间后重试"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按账号、景区、店铺、任务和试卷隔离草稿,以代次比较防止迟到回调覆盖新页面。
|
||||||
|
final class TrainingDraftStore {
|
||||||
|
private static let lock = NSRecursiveLock()
|
||||||
|
private let defaults: UserDefaults
|
||||||
|
private let directoryURL: URL?
|
||||||
|
|
||||||
|
/// 正式日志使用原子文件;测试可注入目录或独立 defaults 替身,不读取正式用户日志。
|
||||||
|
init(defaults: UserDefaults = .standard, directoryURL: URL? = nil) {
|
||||||
|
self.defaults = defaults
|
||||||
|
if let directoryURL { self.directoryURL = directoryURL }
|
||||||
|
else if defaults === UserDefaults.standard {
|
||||||
|
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||||
|
?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support")
|
||||||
|
self.directoryURL = support.appendingPathComponent("TrainingDrafts", isDirectory: true)
|
||||||
|
} else { self.directoryURL = nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 恢复日志;损坏记录不可当成无本机答案而自动覆盖。
|
||||||
|
func load(taskID: String, paperSnapshotID: String, context: TrainingContext) throws -> TrainingDraftRecord? {
|
||||||
|
Self.lock.lock()
|
||||||
|
defer { Self.lock.unlock() }
|
||||||
|
let storageKey = key(taskID, paperSnapshotID, context)
|
||||||
|
let data: Data?
|
||||||
|
if let fileURL = fileURL(storageKey), FileManager.default.fileExists(atPath: fileURL.path) {
|
||||||
|
do { data = try Data(contentsOf: fileURL) }
|
||||||
|
catch { throw TrainingDraftStorageError.unavailable }
|
||||||
|
} else { data = defaults.data(forKey: storageKey) }
|
||||||
|
guard let data else { return nil }
|
||||||
|
guard let record = try? JSONDecoder().decode(TrainingDraftRecord.self, from: data),
|
||||||
|
record.taskID == taskID, record.paperSnapshotID == paperSnapshotID, record.context == context,
|
||||||
|
isValid(record) else { throw TrainingDraftStorageError.invalidRecord }
|
||||||
|
return record
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 比较旧代次后原子更新日志,返回新代次;即使已保存也保留轻量代次防止旧页面复写。
|
||||||
|
@discardableResult
|
||||||
|
func save(_ value: TrainingDraftRecord, replacing generation: String?) throws -> String {
|
||||||
|
Self.lock.lock()
|
||||||
|
defer { Self.lock.unlock() }
|
||||||
|
guard isValid(value) else { throw TrainingDraftStorageError.invalidRecord }
|
||||||
|
let existing = try load(taskID: value.taskID, paperSnapshotID: value.paperSnapshotID, context: value.context)
|
||||||
|
guard existing?.generation == generation else { throw TrainingDraftStorageError.replaced }
|
||||||
|
var updated = value
|
||||||
|
updated.generation = UUID().uuidString
|
||||||
|
let data = try JSONEncoder().encode(updated)
|
||||||
|
let storageKey = key(value.taskID, value.paperSnapshotID, value.context)
|
||||||
|
if let fileURL = fileURL(storageKey), let directoryURL {
|
||||||
|
do {
|
||||||
|
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||||
|
// 原子替换完成才允许调用方发起 RPC;不依赖 UserDefaults 的异步磁盘刷新。
|
||||||
|
try data.write(to: fileURL, options: .atomic)
|
||||||
|
} catch { throw TrainingDraftStorageError.unavailable }
|
||||||
|
} else { defaults.set(data, forKey: storageKey) }
|
||||||
|
return updated.generation
|
||||||
|
}
|
||||||
|
|
||||||
|
private func fileURL(_ storageKey: String) -> URL? {
|
||||||
|
let name = SHA256.hash(data: Data(storageKey.utf8)).map { String(format: "%02x", $0) }.joined()
|
||||||
|
return directoryURL?.appendingPathComponent(name + ".json")
|
||||||
|
}
|
||||||
|
|
||||||
|
private func isValid(_ record: TrainingDraftRecord) -> Bool {
|
||||||
|
func validOptions(_ values: [String]) -> Bool {
|
||||||
|
values.count <= 6 && values.allSatisfy { !$0.isEmpty } && Set(values).count == values.count
|
||||||
|
}
|
||||||
|
func validPosition(_ value: Int?) -> Bool { value == nil || (1...500).contains(value!) }
|
||||||
|
guard !record.generation.isEmpty, !record.taskID.isEmpty, !record.paperSnapshotID.isEmpty,
|
||||||
|
!record.accountScope.isEmpty, record.revision > 0, validPosition(record.lastQuestionOrder),
|
||||||
|
record.answers.count <= 500, Set(record.answers.map(\.questionID)).count == record.answers.count,
|
||||||
|
Set(record.answers.map(\.order)).count == record.answers.count,
|
||||||
|
record.answers.allSatisfy({ !$0.questionID.isEmpty && (1...500).contains($0.order) && validOptions($0.selectedOptionIDs) }),
|
||||||
|
record.pendingSave == nil || record.pendingReset == nil else { return false }
|
||||||
|
if let request = record.pendingSave {
|
||||||
|
guard request.paperSnapshotID == record.paperSnapshotID, !request.requestID.isEmpty,
|
||||||
|
request.baseRevision > 0, validPosition(request.lastQuestionOrder), request.changes.count <= 20,
|
||||||
|
Set(request.changes.map(\.questionID)).count == request.changes.count,
|
||||||
|
request.changes.allSatisfy({ !$0.questionID.isEmpty && validOptions($0.selectedOptionIDs) }) else { return false }
|
||||||
|
}
|
||||||
|
if let request = record.pendingReset {
|
||||||
|
guard request.paperSnapshotID == record.paperSnapshotID, !request.requestID.isEmpty, request.baseRevision > 0 else { return false }
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private func key(_ task: String, _ paper: String, _ context: TrainingContext) -> String {
|
||||||
|
let components = [context.accountScope, String(context.scenicID), String(context.storeID), task, paper]
|
||||||
|
return "training-draft:v1:" + components.map { Data($0.utf8).base64EncodedString() }.joined(separator: ":")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -44,6 +44,9 @@ final class TrainingPendingSubmissionStore {
|
|||||||
/// 使用指定的持久化域保存不含凭证的交卷请求。
|
/// 使用指定的持久化域保存不含凭证的交卷请求。
|
||||||
init(defaults: UserDefaults = .standard) { self.defaults = defaults }
|
init(defaults: UserDefaults = .standard) { self.defaults = defaults }
|
||||||
|
|
||||||
|
/// 草稿与交卷使用同一注入域,但以独立的键和数据格式保存。
|
||||||
|
func makeDraftStore() -> TrainingDraftStore { TrainingDraftStore(defaults: defaults) }
|
||||||
|
|
||||||
/// 当前店铺登录身份;与正式数据源一致,不要求景区 ID 大于零。
|
/// 当前店铺登录身份;与正式数据源一致,不要求景区 ID 大于零。
|
||||||
@MainActor static func currentContext() -> TrainingContext? {
|
@MainActor static func currentContext() -> TrainingContext? {
|
||||||
let session = AppStore.shared.session
|
let session = AppStore.shared.session
|
||||||
|
|||||||
@@ -12,11 +12,19 @@ final class TrainingRemoteExamViewModel {
|
|||||||
private(set) var paper: TrainingPaperInfo?
|
private(set) var paper: TrainingPaperInfo?
|
||||||
/// 当前展示题位,使用从零开始的索引。
|
/// 当前展示题位,使用从零开始的索引。
|
||||||
private(set) var currentIndex = 0
|
private(set) var currentIndex = 0
|
||||||
/// 服务端确认的全部已答题号,题号从一开始。
|
/// 服务端已答题号叠加本机期望选择,题号从一开始。
|
||||||
private(set) var answeredQuestionOrders: Set<Int> = []
|
var answeredQuestionOrders: Set<Int> {
|
||||||
|
var orders = confirmedAnsweredOrders
|
||||||
|
for answer in desiredAnswers.values {
|
||||||
|
if answer.selectedOptionIDs.isEmpty { orders.remove(answer.order) }
|
||||||
|
else { orders.insert(answer.order) }
|
||||||
|
}
|
||||||
|
return orders
|
||||||
|
}
|
||||||
|
private var confirmedAnsweredOrders: Set<Int> = []
|
||||||
/// 最近确认的草稿版本,未加载前为零。
|
/// 最近确认的草稿版本,未加载前为零。
|
||||||
private(set) var draftRevision = 0
|
private(set) var draftRevision = 0
|
||||||
/// 当前操作期间阻止并发写入。
|
/// 前台加载或交卷期间暂停编辑;后台草稿写入独立协调。
|
||||||
private(set) var isBusy = false
|
private(set) var isBusy = false
|
||||||
/// 最近失败的展示文案,业务分支不依赖文案。
|
/// 最近失败的展示文案,业务分支不依赖文案。
|
||||||
private(set) var errorMessage: String?
|
private(set) var errorMessage: String?
|
||||||
@@ -29,6 +37,31 @@ final class TrainingRemoteExamViewModel {
|
|||||||
|
|
||||||
private let pageSize: Int
|
private let pageSize: Int
|
||||||
private let pendingStore: TrainingPendingSubmissionStore
|
private let pendingStore: TrainingPendingSubmissionStore
|
||||||
|
private let draftStore: TrainingDraftStore
|
||||||
|
private let debounceNanoseconds: UInt64
|
||||||
|
private var desiredAnswers: [String: TrainingDraftLocalAnswer] = [:]
|
||||||
|
private var desiredPosition: Int?
|
||||||
|
private var draftGeneration: String?
|
||||||
|
private var restoredPaperID: String?
|
||||||
|
private var debounceTask: Task<Void, Never>?
|
||||||
|
private var writerTask: Task<Bool, Never>?
|
||||||
|
private var isReadingDraft = false
|
||||||
|
private var draftReadWaiters: [CheckedContinuation<Void, Never>] = []
|
||||||
|
private var saveFailure: String?
|
||||||
|
/// 后台草稿请求状态变化;页面主动读取快照,不承担前台导航操作。
|
||||||
|
var onDraftSaveStateChange: (@MainActor () -> Void)?
|
||||||
|
/// 后台请求不锁住已加载题目的编辑。
|
||||||
|
private(set) var isSaving = false
|
||||||
|
/// 版本冲突必须由用户明确确认,不能悄悄覆盖其它设备的答案。
|
||||||
|
private(set) var hasDraftConflict = false
|
||||||
|
/// 有待提交的本机意图或尚未确认的原请求。
|
||||||
|
var hasUnsavedChanges: Bool { !desiredAnswers.isEmpty || desiredPosition != nil || pendingMutation != nil }
|
||||||
|
/// 底部轻量保存状态,不使用全局遮罩。
|
||||||
|
var draftSaveMessage: String {
|
||||||
|
if hasDraftConflict { return "答案已在其他设备变更,重试保存将应用本机未保存选择" }
|
||||||
|
if let saveFailure { return "保存失败,本机选择已保留:" + saveFailure }
|
||||||
|
return isSaving || hasUnsavedChanges ? "正在保存答案…" : "答案已保存,可稍后继续"
|
||||||
|
}
|
||||||
private let currentContext: @MainActor @Sendable () -> TrainingContext?
|
private let currentContext: @MainActor @Sendable () -> TrainingContext?
|
||||||
private var context: TrainingContext?
|
private var context: TrainingContext?
|
||||||
private var questionCache: [Int: TrainingQuestionItem] = [:]
|
private var questionCache: [Int: TrainingQuestionItem] = [:]
|
||||||
@@ -50,22 +83,27 @@ final class TrainingRemoteExamViewModel {
|
|||||||
/// 注入身份与持久化域,测试不访问全局登录态或网络。
|
/// 注入身份与持久化域,测试不访问全局登录态或网络。
|
||||||
init(taskID: String, context: TrainingContext? = nil, pageSize: Int = 10,
|
init(taskID: String, context: TrainingContext? = nil, pageSize: Int = 10,
|
||||||
pendingStore: TrainingPendingSubmissionStore = TrainingPendingSubmissionStore(),
|
pendingStore: TrainingPendingSubmissionStore = TrainingPendingSubmissionStore(),
|
||||||
|
draftStore: TrainingDraftStore? = nil, debounceNanoseconds: UInt64 = 300_000_000,
|
||||||
currentContext: @escaping @MainActor @Sendable () -> TrainingContext? = { TrainingPendingSubmissionStore.currentContext() }) {
|
currentContext: @escaping @MainActor @Sendable () -> TrainingContext? = { TrainingPendingSubmissionStore.currentContext() }) {
|
||||||
self.taskID = taskID
|
self.taskID = taskID
|
||||||
self.context = context
|
self.context = context
|
||||||
self.pageSize = min(20, max(1, pageSize))
|
self.pageSize = min(20, max(1, pageSize))
|
||||||
self.pendingStore = pendingStore
|
self.pendingStore = pendingStore
|
||||||
|
self.draftStore = draftStore ?? pendingStore.makeDraftStore()
|
||||||
|
self.debounceNanoseconds = debounceNanoseconds
|
||||||
self.currentContext = currentContext
|
self.currentContext = currentContext
|
||||||
}
|
}
|
||||||
|
|
||||||
|
deinit { debounceTask?.cancel() }
|
||||||
|
|
||||||
/// 已知总题数,无需获取全部题目正文。
|
/// 已知总题数,无需获取全部题目正文。
|
||||||
var questionCount: Int { paper?.questionCount ?? 0 }
|
var questionCount: Int { paper?.questionCount ?? 0 }
|
||||||
/// 全局已答数量,不把未下载的答案当成漏答。
|
/// 全局已答数量,不把未下载的答案当成漏答。
|
||||||
var answeredCount: Int { answeredQuestionOrders.count }
|
var answeredCount: Int { answeredQuestionOrders.count }
|
||||||
/// 当前已加载的题目。
|
/// 当前已加载的题目。
|
||||||
var currentQuestion: TrainingQuestionItem? { questionCache[currentIndex] }
|
var currentQuestion: TrainingQuestionItem? { questionCache[currentIndex] }
|
||||||
/// 当前题已确认保存的选择。
|
/// 当前题的本机期望选择,未修改时使用已确认答案。
|
||||||
var currentSelectedIDs: Set<String> { currentQuestion.flatMap { answerCache[$0.id] } ?? [] }
|
var currentSelectedIDs: Set<String> { currentQuestion.map { Set(desiredAnswers[$0.id]?.selectedOptionIDs ?? Array(answerCache[$0.id] ?? [])) } ?? [] }
|
||||||
/// 第一处真正漏答的题位。
|
/// 第一处真正漏答的题位。
|
||||||
var firstUnansweredIndex: Int? {
|
var firstUnansweredIndex: Int? {
|
||||||
guard questionCount > 0 else { return nil }
|
guard questionCount > 0 else { return nil }
|
||||||
@@ -75,19 +113,20 @@ final class TrainingRemoteExamViewModel {
|
|||||||
var hasPendingSubmission: Bool { pendingSubmission != nil }
|
var hasPendingSubmission: Bool { pendingSubmission != nil }
|
||||||
/// 页面所属账号、景区或店铺已变化,不能继续显示原身份的数据。
|
/// 页面所属账号、景区或店铺已变化,不能继续显示原身份的数据。
|
||||||
var isIdentityInvalid: Bool { !identityIsValid }
|
var isIdentityInvalid: Bool { !identityIsValid }
|
||||||
/// 草稿请求失败后只允许重试原操作。
|
/// 存在需要用户明确重试或确认的草稿操作。
|
||||||
var hasPendingMutation: Bool { pendingMutation != nil }
|
var hasPendingMutation: Bool { saveFailure != nil || hasDraftConflict || isResetPending }
|
||||||
|
private var isResetPending: Bool { if case .reset? = pendingMutation { return true }; return false }
|
||||||
/// 当前题正文和对应草稿范围均成功读取后,才可展示为可编辑答案。
|
/// 当前题正文和对应草稿范围均成功读取后,才可展示为可编辑答案。
|
||||||
var isCurrentPageReady: Bool { currentQuestion != nil && loadedDraftIndices.contains(currentIndex) && !needsDraftRefresh }
|
var isCurrentPageReady: Bool { currentQuestion != nil && loadedDraftIndices.contains(currentIndex) && !needsDraftRefresh }
|
||||||
/// 页读取或冲突后的恢复失败时,沿当前题位重试读取,保留其它页缓存。
|
/// 页读取或冲突后的恢复失败时,沿当前题位重试读取,保留其它页缓存。
|
||||||
var canRetryCurrentPage: Bool {
|
var canRetryCurrentPage: Bool {
|
||||||
!isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !recoveryStorageFailed
|
!isBusy && identityIsValid && !hasPendingSubmission && !isResetPending && !recoveryStorageFailed
|
||||||
&& !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady
|
&& !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady
|
||||||
&& progress?.canStartExam == true && progress?.learnerStatus != .completed
|
&& progress?.canStartExam == true && progress?.learnerStatus != .completed
|
||||||
}
|
}
|
||||||
/// 只有权威资格允许且所有写入均确认后才能修改答案。
|
/// 权威资格及当前页就绪时可编辑,后台保存不会阻断本机选择。
|
||||||
var canEdit: Bool {
|
var canEdit: Bool {
|
||||||
!isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !needsDraftRefresh && !recoveryStorageFailed
|
!isBusy && identityIsValid && !hasPendingSubmission && !isResetPending && !needsDraftRefresh && !recoveryStorageFailed
|
||||||
&& submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus != .completed
|
&& submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus != .completed
|
||||||
&& !shouldReturnToCenter && paper != nil && isCurrentPageReady
|
&& !shouldReturnToCenter && paper != nil && isCurrentPageReady
|
||||||
}
|
}
|
||||||
@@ -102,8 +141,14 @@ final class TrainingRemoteExamViewModel {
|
|||||||
func load(service: any TrainingDataServing, resetDraft: Bool = false) async {
|
func load(service: any TrainingDataServing, resetDraft: Bool = false) async {
|
||||||
guard !isBusy else { return }
|
guard !isBusy else { return }
|
||||||
isBusy = true
|
isBusy = true
|
||||||
|
isReadingDraft = true
|
||||||
|
debounceTask?.cancel()
|
||||||
|
debounceTask = nil
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
defer { isBusy = false }
|
defer {
|
||||||
|
isBusy = false
|
||||||
|
finishDraftRead(service: service)
|
||||||
|
}
|
||||||
do {
|
do {
|
||||||
try await authorize()
|
try await authorize()
|
||||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||||
@@ -118,10 +163,7 @@ final class TrainingRemoteExamViewModel {
|
|||||||
_ = try await recoverSubmission(service: service)
|
_ = try await recoverSubmission(service: service)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if pendingMutation != nil {
|
if let writerTask { _ = await writerTask.value }
|
||||||
try await performMutation(service: service)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
let detail = try await service.task(id: taskID)
|
let detail = try await service.task(id: taskID)
|
||||||
try await authorize()
|
try await authorize()
|
||||||
let latestProgress = try await service.progress(taskID: taskID)
|
let latestProgress = try await service.progress(taskID: taskID)
|
||||||
@@ -136,81 +178,173 @@ final class TrainingRemoteExamViewModel {
|
|||||||
loadedPaper.scoring == TrainingTask.equalPercentageScoring else { throw TrainingError.invalidPaper }
|
loadedPaper.scoring == TrainingTask.equalPercentageScoring else { throw TrainingError.invalidPaper }
|
||||||
if paper?.id != loadedPaper.id { questionCache = [:]; answerCache = [:]; loadedDraftIndices = [] }
|
if paper?.id != loadedPaper.id { questionCache = [:]; answerCache = [:]; loadedDraftIndices = [] }
|
||||||
paper = loadedPaper
|
paper = loadedPaper
|
||||||
|
try restoreDraftIfNeeded()
|
||||||
|
// 已冻结请求先沿原键确认;明确重考也不能越过未知写入。
|
||||||
|
if pendingMutation != nil, !hasDraftConflict {
|
||||||
|
saveFailure = nil
|
||||||
|
_ = await flushDraftNow(service: service)
|
||||||
|
guard identityIsValid, !shouldReturnToCenter, !isResetPending else { return }
|
||||||
|
}
|
||||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||||
try await authorize()
|
try await authorize()
|
||||||
try applyMetadata(metadata)
|
try applyMetadata(metadata)
|
||||||
currentIndex = (1...questionCount).contains(metadata.lastQuestionOrder) ? metadata.lastQuestionOrder - 1 : 0
|
let position = desiredPosition ?? metadata.lastQuestionOrder
|
||||||
|
currentIndex = (1...questionCount).contains(position) ? position - 1 : 0
|
||||||
if resetDraft, !initialResetRequested {
|
if resetDraft, !initialResetRequested {
|
||||||
|
guard !hasUnsavedChanges, !hasDraftConflict else {
|
||||||
|
saveFailure = "请先确认上次未保存答案,再重新发起重考"
|
||||||
|
notifyDraftState()
|
||||||
|
return
|
||||||
|
}
|
||||||
initialResetRequested = true
|
initialResetRequested = true
|
||||||
pendingMutation = .reset(TrainingDraftResetRequest(requestID: UUID().uuidString, paperSnapshotID: paperID, baseRevision: draftRevision))
|
pendingMutation = .reset(TrainingDraftResetRequest(requestID: UUID().uuidString, paperSnapshotID: paperID, baseRevision: draftRevision))
|
||||||
try await performMutation(service: service)
|
try persistDraft()
|
||||||
|
guard await flushDraftNow(service: service) else { return }
|
||||||
} else {
|
} else {
|
||||||
try await loadCurrentPage(service: service)
|
try await loadCurrentPage(service: service)
|
||||||
}
|
}
|
||||||
} catch { report(error) }
|
try persistDraft()
|
||||||
|
if hasUnsavedChanges, !hasDraftConflict, saveFailure == nil { scheduleSave(service: service) }
|
||||||
|
} catch {
|
||||||
|
if error is TrainingDraftStorageError { reportSaveFailure(error) }
|
||||||
|
else { report(error) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 随机跳题直接获取所在页,并保存浏览位置;不遍历前面的题目页。
|
/// 已缓存题目立即切换;位置变更并入后台串行草稿,不等待 ACK。
|
||||||
|
@discardableResult
|
||||||
|
func goToCachedQuestion(_ index: Int, service: any TrainingDataServing) -> Bool {
|
||||||
|
guard canEdit, (0..<questionCount).contains(index), questionCache[index] != nil,
|
||||||
|
loadedDraftIndices.contains(index) else { return false }
|
||||||
|
currentIndex = index
|
||||||
|
desiredPosition = index + 1
|
||||||
|
queueDraft(service: service)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 未缓存题按需加载,读取完成后继续本机选择;后台保存不会锁住缓存导航。
|
||||||
func goToQuestion(_ index: Int, service: any TrainingDataServing) async {
|
func goToQuestion(_ index: Int, service: any TrainingDataServing) async {
|
||||||
guard canEdit, (0..<questionCount).contains(index) else { return }
|
guard canEdit, (0..<questionCount).contains(index) else { return }
|
||||||
|
if goToCachedQuestion(index, service: service) { return }
|
||||||
isBusy = true
|
isBusy = true
|
||||||
|
isReadingDraft = true
|
||||||
|
debounceTask?.cancel()
|
||||||
|
debounceTask = nil
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
defer { isBusy = false }
|
defer {
|
||||||
|
isBusy = false
|
||||||
|
finishDraftRead(service: service)
|
||||||
|
}
|
||||||
do {
|
do {
|
||||||
try await authorize()
|
try await authorize()
|
||||||
|
if let writerTask { _ = await writerTask.value }
|
||||||
currentIndex = index
|
currentIndex = index
|
||||||
try await loadCurrentPage(service: service)
|
try await loadCurrentPage(service: service)
|
||||||
guard let paper else { throw TrainingError.invalidPaper }
|
desiredPosition = index + 1
|
||||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
queueDraft(service: service)
|
||||||
baseRevision: draftRevision, lastQuestionOrder: index + 1, changes: []))
|
|
||||||
try await performMutation(service: service)
|
|
||||||
} catch { report(error) }
|
} catch { report(error) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 计算本次点击的展示选择,不提前修改已确认答案或草稿版本。
|
/// 计算即时选择;重复单选是无操作,不创建请求或重置防抖。
|
||||||
func selectionPreview(optionID: String) -> Set<String>? {
|
func selectionPreview(optionID: String) -> Set<String>? {
|
||||||
guard canEdit, let question = currentQuestion,
|
guard canEdit, let question = currentQuestion,
|
||||||
question.options.contains(where: { $0.id == optionID }) else { return nil }
|
question.options.contains(where: { $0.id == optionID }) else { return nil }
|
||||||
var selected = currentSelectedIDs
|
var selected = currentSelectedIDs
|
||||||
if question.type == .single { selected = [optionID] }
|
if question.type == .single {
|
||||||
else if selected.contains(optionID) { selected.remove(optionID) }
|
guard selected != [optionID] else { return nil }
|
||||||
|
selected = [optionID]
|
||||||
|
} else if selected.contains(optionID) { selected.remove(optionID) }
|
||||||
else { selected.insert(optionID) }
|
else { selected.insert(optionID) }
|
||||||
return selected
|
return selected
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 增量保存当前一题,网络结果未知时保留原 ID 和完整请求供重试。
|
/// 同步更新并持久保存期望选择,允许上一请求未返回时继续改选。
|
||||||
func select(optionID: String, service: any TrainingDataServing) async {
|
@discardableResult
|
||||||
guard let selected = selectionPreview(optionID: optionID), let question = currentQuestion, let paper else { return }
|
func selectLocally(optionID: String, service: any TrainingDataServing) -> Bool {
|
||||||
isBusy = true
|
guard let selected = selectionPreview(optionID: optionID), let question = currentQuestion else { return false }
|
||||||
|
desiredAnswers[question.id] = TrainingDraftLocalAnswer(questionID: question.id, order: question.order,
|
||||||
|
selectedOptionIDs: selected.sorted())
|
||||||
|
desiredPosition = question.order
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
defer { isBusy = false }
|
// 尚未发出且已回到 ACK 选择的变化无需发送。
|
||||||
do {
|
if pendingMutation == nil, selected == (answerCache[question.id] ?? []) { desiredAnswers.removeValue(forKey: question.id) }
|
||||||
try await authorize()
|
queueDraft(service: service)
|
||||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
return true
|
||||||
baseRevision: draftRevision, lastQuestionOrder: question.order,
|
|
||||||
changes: [TrainingDraftChange(questionID: question.id, selectedOptionIDs: selected.sorted())]))
|
|
||||||
try await performMutation(service: service)
|
|
||||||
} catch { report(error) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 沿用失败草稿写入的原请求,不生成新的幂等键。
|
/// 兼容调用方的异步入口,仅排入本机草稿;需要确认保存时显式 flushDraft。
|
||||||
|
func select(optionID: String, service: any TrainingDataServing) async {
|
||||||
|
_ = selectLocally(optionID: optionID, service: service)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 立即排空所有草稿,等待在飞请求后使用最新 ACK 版本,不并发提交同一版本。
|
||||||
|
@discardableResult
|
||||||
|
func flushDraft(service: any TrainingDataServing) async -> Bool {
|
||||||
|
if isReadingDraft {
|
||||||
|
await withCheckedContinuation { draftReadWaiters.append($0) }
|
||||||
|
}
|
||||||
|
return await flushDraftNow(service: service)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func flushDraftNow(service: any TrainingDataServing) async -> Bool {
|
||||||
|
debounceTask?.cancel()
|
||||||
|
debounceTask = nil
|
||||||
|
while true {
|
||||||
|
if let writerTask {
|
||||||
|
guard await writerTask.value else { return false }
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
guard !hasDraftConflict, saveFailure == nil, !recoveryStorageFailed else { return false }
|
||||||
|
guard hasUnsavedChanges else { return true }
|
||||||
|
let task = Task { @MainActor in await self.drainDraft(service: service) }
|
||||||
|
writerTask = task
|
||||||
|
guard await task.value else { return false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保存失败后明确重试冻结的原请求,不能更换原幂等键和 payload。
|
||||||
func retryMutation(service: any TrainingDataServing) async {
|
func retryMutation(service: any TrainingDataServing) async {
|
||||||
guard !isBusy, pendingMutation != nil, !hasPendingSubmission else { return }
|
guard !isBusy, !hasPendingSubmission, !hasDraftConflict else { return }
|
||||||
isBusy = true
|
if recoveryStorageFailed {
|
||||||
|
do { try persistDraft(); recoveryStorageFailed = false }
|
||||||
|
catch { reportSaveFailure(error); notifyDraftState(); return }
|
||||||
|
}
|
||||||
|
saveFailure = nil
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
defer { isBusy = false }
|
if await flushDraft(service: service), currentQuestion == nil { await load(service: service) }
|
||||||
do { try await authorize(); try await performMutation(service: service) }
|
}
|
||||||
catch { report(error) }
|
|
||||||
|
/// 用户明确选择本机或服务端答案后才结束版本冲突暂停。
|
||||||
|
func resolveDraftConflict(useLocalAnswers: Bool, service: any TrainingDataServing) async {
|
||||||
|
guard !isBusy, hasDraftConflict, !hasPendingSubmission else { return }
|
||||||
|
do {
|
||||||
|
try await authorize()
|
||||||
|
try await refreshDraft(service: service)
|
||||||
|
if !useLocalAnswers { desiredAnswers = [:]; desiredPosition = nil }
|
||||||
|
hasDraftConflict = false
|
||||||
|
saveFailure = nil
|
||||||
|
errorMessage = nil
|
||||||
|
try persistDraft()
|
||||||
|
_ = await flushDraft(service: service)
|
||||||
|
} catch { reportSaveFailure(error) }
|
||||||
|
notifyDraftState()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 仅重读当前未就绪题位;已确认的其它页不会因一次网络失败被清空。
|
/// 仅重读当前未就绪题位;已确认的其它页不会因一次网络失败被清空。
|
||||||
func retryCurrentPage(service: any TrainingDataServing) async {
|
func retryCurrentPage(service: any TrainingDataServing) async {
|
||||||
guard canRetryCurrentPage else { return }
|
guard canRetryCurrentPage else { return }
|
||||||
isBusy = true
|
isBusy = true
|
||||||
|
isReadingDraft = true
|
||||||
|
debounceTask?.cancel()
|
||||||
|
debounceTask = nil
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
defer { isBusy = false }
|
defer {
|
||||||
|
isBusy = false
|
||||||
|
finishDraftRead(service: service)
|
||||||
|
}
|
||||||
do {
|
do {
|
||||||
try await authorize()
|
try await authorize()
|
||||||
|
if let writerTask { _ = await writerTask.value }
|
||||||
if needsDraftRefresh { try await refreshDraft(service: service) }
|
if needsDraftRefresh { try await refreshDraft(service: service) }
|
||||||
else { try await loadCurrentPage(service: service) }
|
else { try await loadCurrentPage(service: service) }
|
||||||
} catch { report(error) }
|
} catch { report(error) }
|
||||||
@@ -218,7 +352,7 @@ final class TrainingRemoteExamViewModel {
|
|||||||
|
|
||||||
/// 持久保存交卷请求后提交;未知结果先查原键,再重试原版本。
|
/// 持久保存交卷请求后提交;未知结果先查原键,再重试原版本。
|
||||||
func submit(service: any TrainingDataServing) async -> TrainingAttemptSummary? {
|
func submit(service: any TrainingDataServing) async -> TrainingAttemptSummary? {
|
||||||
guard !isBusy, !hasPendingMutation, !recoveryStorageFailed else { return nil }
|
guard !isBusy, !isResetPending, !recoveryStorageFailed else { return nil }
|
||||||
let wasEditable = canEdit
|
let wasEditable = canEdit
|
||||||
isBusy = true
|
isBusy = true
|
||||||
errorMessage = nil
|
errorMessage = nil
|
||||||
@@ -236,6 +370,8 @@ final class TrainingRemoteExamViewModel {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
try requireExamAllowed()
|
try requireExamAllowed()
|
||||||
|
guard await flushDraft(service: service), !hasUnsavedChanges else { return nil }
|
||||||
|
try await authorize()
|
||||||
guard let paper else { throw TrainingError.invalidPaper }
|
guard let paper else { throw TrainingError.invalidPaper }
|
||||||
let request = TrainingSubmissionRequest(submissionID: UUID().uuidString, paperSnapshotID: paper.id, draftRevision: draftRevision)
|
let request = TrainingSubmissionRequest(submissionID: UUID().uuidString, paperSnapshotID: paper.id, draftRevision: draftRevision)
|
||||||
let pending = TrainingPendingSubmission(taskID: taskID, request: request, context: context)
|
let pending = TrainingPendingSubmission(taskID: taskID, request: request, context: context)
|
||||||
@@ -261,7 +397,10 @@ final class TrainingRemoteExamViewModel {
|
|||||||
questionCache = [:]
|
questionCache = [:]
|
||||||
answerCache = [:]
|
answerCache = [:]
|
||||||
loadedDraftIndices = []
|
loadedDraftIndices = []
|
||||||
answeredQuestionOrders = []
|
confirmedAnsweredOrders = []
|
||||||
|
desiredAnswers = [:]
|
||||||
|
desiredPosition = nil
|
||||||
|
debounceTask?.cancel()
|
||||||
draftRevision = 0
|
draftRevision = 0
|
||||||
currentIndex = 0
|
currentIndex = 0
|
||||||
submittedAttempt = nil
|
submittedAttempt = nil
|
||||||
@@ -293,9 +432,14 @@ final class TrainingRemoteExamViewModel {
|
|||||||
guard value.taskID == taskID, value.paperSnapshotID == paper?.id, value.total == questionCount,
|
guard value.taskID == taskID, value.paperSnapshotID == paper?.id, value.total == questionCount,
|
||||||
value.draftRevision > 0, orders.count == value.answeredCount,
|
value.draftRevision > 0, orders.count == value.answeredCount,
|
||||||
orders.allSatisfy({ (1...questionCount).contains($0) }) else { throw TrainingError.invalidAnswers }
|
orders.allSatisfy({ (1...questionCount).contains($0) }) else { throw TrainingError.invalidAnswers }
|
||||||
|
// 迟到 GET 不回退已确认版本;本机 overlay 与服务端缓存分别管理。
|
||||||
|
guard value.draftRevision >= draftRevision else { return }
|
||||||
|
if value.draftRevision > draftRevision, !desiredAnswers.isEmpty, pendingMutation == nil {
|
||||||
|
hasDraftConflict = true
|
||||||
|
}
|
||||||
if value.draftRevision != draftRevision { answerCache = [:]; loadedDraftIndices = [] }
|
if value.draftRevision != draftRevision { answerCache = [:]; loadedDraftIndices = [] }
|
||||||
draftRevision = value.draftRevision
|
draftRevision = value.draftRevision
|
||||||
answeredQuestionOrders = orders
|
confirmedAnsweredOrders = orders
|
||||||
}
|
}
|
||||||
|
|
||||||
private func loadCurrentPage(service: any TrainingDataServing) async throws {
|
private func loadCurrentPage(service: any TrainingDataServing) async throws {
|
||||||
@@ -317,7 +461,7 @@ final class TrainingRemoteExamViewModel {
|
|||||||
guard loadedDraftIndices.contains(currentIndex) else { throw TrainingError.invalidAnswers }
|
guard loadedDraftIndices.contains(currentIndex) else { throw TrainingError.invalidAnswers }
|
||||||
}
|
}
|
||||||
if let question = currentQuestion {
|
if let question = currentQuestion {
|
||||||
let selected = answerCache[question.id] ?? []
|
let selected = Set(desiredAnswers[question.id]?.selectedOptionIDs ?? Array(answerCache[question.id] ?? []))
|
||||||
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
||||||
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||||
}
|
}
|
||||||
@@ -343,8 +487,13 @@ final class TrainingRemoteExamViewModel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func fetchDraft(offset: Int, service: any TrainingDataServing) async throws {
|
private func fetchDraft(offset: Int, service: any TrainingDataServing) async throws {
|
||||||
let page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
var page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
||||||
try await authorize()
|
try await authorize()
|
||||||
|
if page.draftRevision < draftRevision {
|
||||||
|
page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
||||||
|
try await authorize()
|
||||||
|
}
|
||||||
|
guard page.draftRevision >= draftRevision else { throw TrainingError.invalidAnswers }
|
||||||
try applyMetadata(page)
|
try applyMetadata(page)
|
||||||
let requestedEnd = min(questionCount, offset + pageSize)
|
let requestedEnd = min(questionCount, offset + pageSize)
|
||||||
let coveredEnd = page.nextOffset ?? requestedEnd
|
let coveredEnd = page.nextOffset ?? requestedEnd
|
||||||
@@ -377,50 +526,162 @@ final class TrainingRemoteExamViewModel {
|
|||||||
try await loadCurrentPage(service: service)
|
try await loadCurrentPage(service: service)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func performMutation(service: any TrainingDataServing) async throws {
|
private func finishDraftRead(service: any TrainingDataServing) {
|
||||||
guard let mutation = pendingMutation else { return }
|
isReadingDraft = false
|
||||||
|
let waiters = draftReadWaiters
|
||||||
|
draftReadWaiters = []
|
||||||
|
for waiter in waiters { waiter.resume() }
|
||||||
|
if hasUnsavedChanges { scheduleSave(service: service) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func notifyDraftState() {
|
||||||
|
Task { @MainActor [weak self] in self?.onDraftSaveStateChange?() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func queueDraft(service: any TrainingDataServing) {
|
||||||
|
do { try persistDraft() }
|
||||||
|
catch { reportSaveFailure(error) }
|
||||||
|
notifyDraftState()
|
||||||
|
scheduleSave(service: service)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func scheduleSave(service: any TrainingDataServing) {
|
||||||
|
debounceTask?.cancel()
|
||||||
|
guard saveFailure == nil, !hasDraftConflict, !recoveryStorageFailed, !isReadingDraft,
|
||||||
|
identityIsValid, !shouldReturnToCenter, !hasPendingSubmission, submittedAttempt == nil else { return }
|
||||||
|
let delay = debounceNanoseconds
|
||||||
|
debounceTask = Task { @MainActor [weak self] in
|
||||||
|
do { try await Task.sleep(nanoseconds: delay) }
|
||||||
|
catch { return }
|
||||||
|
guard !Task.isCancelled, let self, !self.isReadingDraft else { return }
|
||||||
|
self.debounceTask = nil
|
||||||
|
_ = await self.flushDraft(service: service)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func restoreDraftIfNeeded() throws {
|
||||||
|
guard let context, let paper else { throw TrainingError.invalidPaper }
|
||||||
|
guard restoredPaperID != paper.id else { return }
|
||||||
|
desiredAnswers = [:]
|
||||||
|
desiredPosition = nil
|
||||||
|
pendingMutation = nil
|
||||||
|
draftGeneration = nil
|
||||||
|
hasDraftConflict = false
|
||||||
|
if let record = try draftStore.load(taskID: taskID, paperSnapshotID: paper.id, context: context) {
|
||||||
|
draftGeneration = record.generation
|
||||||
|
draftRevision = max(draftRevision, record.revision)
|
||||||
|
desiredAnswers = Dictionary(uniqueKeysWithValues: record.answers.map { ($0.questionID, $0) })
|
||||||
|
desiredPosition = record.lastQuestionOrder
|
||||||
|
if let order = record.lastQuestionOrder, (1...questionCount).contains(order) { currentIndex = order - 1 }
|
||||||
|
hasDraftConflict = record.hasConflict
|
||||||
|
if let save = record.pendingSave { pendingMutation = .save(save) }
|
||||||
|
if let reset = record.pendingReset {
|
||||||
|
pendingMutation = .reset(reset)
|
||||||
|
initialResetRequested = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
restoredPaperID = paper.id
|
||||||
|
try persistDraft()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func persistDraft() throws {
|
||||||
|
guard let context, let paper, restoredPaperID == paper.id else { return }
|
||||||
|
var record = TrainingDraftRecord(taskID: taskID, paperSnapshotID: paper.id, context: context,
|
||||||
|
revision: max(1, draftRevision), answers: desiredAnswers.values.sorted { $0.order < $1.order },
|
||||||
|
lastQuestionOrder: desiredPosition, hasConflict: hasDraftConflict)
|
||||||
|
if case .save(let request)? = pendingMutation { record.pendingSave = request }
|
||||||
|
if case .reset(let request)? = pendingMutation { record.pendingReset = request }
|
||||||
|
draftGeneration = try draftStore.save(record, replacing: draftGeneration)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func reportSaveFailure(_ error: Error) {
|
||||||
|
saveFailure = error.localizedDescription
|
||||||
|
if error is TrainingDraftStorageError { recoveryStorageFailed = true }
|
||||||
|
report(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func drainDraft(service: any TrainingDataServing) async -> Bool {
|
||||||
|
isSaving = true
|
||||||
|
notifyDraftState()
|
||||||
|
defer { isSaving = false; writerTask = nil; notifyDraftState() }
|
||||||
do {
|
do {
|
||||||
let confirmation: TrainingDraftConfirmation
|
while hasUnsavedChanges {
|
||||||
switch mutation {
|
try await authorize()
|
||||||
case .save(let request): confirmation = try await service.saveDraft(taskID: taskID, request: request)
|
guard !hasDraftConflict, let paper else { return false }
|
||||||
case .reset(let request): confirmation = try await service.resetDraft(taskID: taskID, request: request)
|
if pendingMutation == nil {
|
||||||
}
|
// 一个任务只有一个 writer;发送后 payload 和幂等键不再被本机后续点击改写。
|
||||||
try await authorize()
|
let changes = desiredAnswers.values.sorted { $0.order < $1.order }.prefix(20).map {
|
||||||
guard confirmation.draftRevision >= draftRevision, (0...questionCount).contains(confirmation.answeredCount) else {
|
TrainingDraftChange(questionID: $0.questionID, selectedOptionIDs: $0.selectedOptionIDs)
|
||||||
throw TrainingError.invalidAnswers
|
|
||||||
}
|
|
||||||
pendingMutation = nil
|
|
||||||
draftRevision = confirmation.draftRevision
|
|
||||||
switch mutation {
|
|
||||||
case .reset:
|
|
||||||
// 重置重试返回当前实况,不能根据成功响应把之后的新答案清空。
|
|
||||||
currentIndex = 0
|
|
||||||
try await refreshDraft(service: service)
|
|
||||||
case .save(let request):
|
|
||||||
for change in request.changes {
|
|
||||||
answerCache[change.questionID] = Set(change.selectedOptionIDs)
|
|
||||||
if let question = questionCache.values.first(where: { $0.id == change.questionID }) {
|
|
||||||
if change.selectedOptionIDs.isEmpty { answeredQuestionOrders.remove(question.order) }
|
|
||||||
else { answeredQuestionOrders.insert(question.order) }
|
|
||||||
}
|
}
|
||||||
|
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString,
|
||||||
|
paperSnapshotID: paper.id, baseRevision: draftRevision,
|
||||||
|
lastQuestionOrder: desiredPosition, changes: changes))
|
||||||
}
|
}
|
||||||
if answeredCount != confirmation.answeredCount { try await refreshDraft(service: service) }
|
try persistDraft()
|
||||||
}
|
guard let mutation = pendingMutation else { return true }
|
||||||
} catch {
|
do {
|
||||||
if case TrainingRemoteError.draftRevisionConflict = error {
|
let confirmation: TrainingDraftConfirmation
|
||||||
pendingMutation = nil
|
switch mutation {
|
||||||
try? await refreshDraft(service: service)
|
case .save(let request): confirmation = try await service.saveDraft(taskID: taskID, request: request)
|
||||||
} else if let remote = error as? TrainingRemoteError, remote.code != nil {
|
case .reset(let request): confirmation = try await service.resetDraft(taskID: taskID, request: request)
|
||||||
if case .idempotencyConflict = remote { /* 保留原请求,禁止换键覆盖。 */ }
|
}
|
||||||
else {
|
try await authorize()
|
||||||
|
let base: Int
|
||||||
|
switch mutation { case .save(let value): base = value.baseRevision; case .reset(let value): base = value.baseRevision }
|
||||||
|
guard confirmation.draftRevision >= base, (0...questionCount).contains(confirmation.answeredCount) else {
|
||||||
|
throw TrainingError.invalidAnswers
|
||||||
|
}
|
||||||
|
let staleAcknowledgement = confirmation.draftRevision < draftRevision
|
||||||
pendingMutation = nil
|
pendingMutation = nil
|
||||||
if let latest = try? await service.progress(taskID: taskID) {
|
if staleAcknowledgement, !desiredAnswers.isEmpty { hasDraftConflict = true }
|
||||||
try await authorize()
|
draftRevision = max(draftRevision, confirmation.draftRevision)
|
||||||
progress = latest
|
switch mutation {
|
||||||
} else { progress = nil }
|
case .save(let request):
|
||||||
|
for change in request.changes {
|
||||||
|
let sent = Set(change.selectedOptionIDs)
|
||||||
|
answerCache[change.questionID] = sent
|
||||||
|
if let answer = desiredAnswers[change.questionID] {
|
||||||
|
if sent.isEmpty { confirmedAnsweredOrders.remove(answer.order) }
|
||||||
|
else { confirmedAnsweredOrders.insert(answer.order) }
|
||||||
|
// 迟到 ACK 只确认它发送的版本,不能覆盖期间产生的更新选择。
|
||||||
|
if !staleAcknowledgement, answer.selectedOptionIDs == change.selectedOptionIDs {
|
||||||
|
desiredAnswers.removeValue(forKey: change.questionID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if desiredPosition == request.lastQuestionOrder { desiredPosition = nil }
|
||||||
|
try persistDraft()
|
||||||
|
if staleAcknowledgement || confirmedAnsweredOrders.count != confirmation.answeredCount {
|
||||||
|
try await refreshDraft(service: service)
|
||||||
|
}
|
||||||
|
case .reset:
|
||||||
|
currentIndex = 0
|
||||||
|
desiredAnswers = [:]
|
||||||
|
desiredPosition = nil
|
||||||
|
try persistDraft()
|
||||||
|
try await refreshDraft(service: service)
|
||||||
|
}
|
||||||
|
saveFailure = nil
|
||||||
|
errorMessage = nil
|
||||||
|
try persistDraft()
|
||||||
|
notifyDraftState()
|
||||||
|
} catch {
|
||||||
|
if case TrainingRemoteError.draftRevisionConflict = error {
|
||||||
|
// 明确拒绝才解除原请求;先取权威版本,保留全部本机意图并等待用户确认。
|
||||||
|
pendingMutation = nil
|
||||||
|
hasDraftConflict = true
|
||||||
|
try persistDraft()
|
||||||
|
do { try await refreshDraft(service: service); try persistDraft() }
|
||||||
|
catch { reportSaveFailure(error) }
|
||||||
|
}
|
||||||
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw error
|
return true
|
||||||
|
} catch {
|
||||||
|
reportSaveFailure(error)
|
||||||
|
notifyDraftState()
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,6 +730,11 @@ final class TrainingRemoteExamViewModel {
|
|||||||
guard attempt.taskID == taskID, attempt.paperSnapshotID == pending.request.paperSnapshotID else { throw TrainingError.invalidAnswers }
|
guard attempt.taskID == taskID, attempt.paperSnapshotID == pending.request.paperSnapshotID else { throw TrainingError.invalidAnswers }
|
||||||
try pendingStore.remove(pending)
|
try pendingStore.remove(pending)
|
||||||
pendingSubmission = nil
|
pendingSubmission = nil
|
||||||
|
desiredAnswers = [:]
|
||||||
|
desiredPosition = nil
|
||||||
|
pendingMutation = nil
|
||||||
|
hasDraftConflict = false
|
||||||
|
try? persistDraft()
|
||||||
submittedAttempt = attempt
|
submittedAttempt = attempt
|
||||||
let state = TrainingTaskState(learnerStatus: attempt.passed ? .completed : .pendingExam,
|
let state = TrainingTaskState(learnerStatus: attempt.passed ? .completed : .pendingExam,
|
||||||
completedAt: attempt.passed ? attempt.submittedAt : nil, canRetry: false, blockReason: attempt.passed ? "completed" : nil)
|
completedAt: attempt.passed ? attempt.submittedAt : nil, canRetry: false, blockReason: attempt.passed ? "completed" : nil)
|
||||||
|
|||||||
@@ -56,7 +56,6 @@ final class TrainingCenterViewController: TrainingBaseViewController {
|
|||||||
hero.spacing = 8
|
hero.spacing = 8
|
||||||
hero.backgroundColor = UIColor(red: 45/255, green: 128/255, blue: 250/255, alpha: 1)
|
hero.backgroundColor = UIColor(red: 45/255, green: 128/255, blue: 250/255, alpha: 1)
|
||||||
hero.layer.cornerRadius = 14
|
hero.layer.cornerRadius = 14
|
||||||
hero.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
|
|
||||||
hero.isLayoutMarginsRelativeArrangement = true
|
hero.isLayoutMarginsRelativeArrangement = true
|
||||||
hero.layoutMargins = UIEdgeInsets(top: 19, left: 17, bottom: 18, right: 17)
|
hero.layoutMargins = UIEdgeInsets(top: 19, left: 17, bottom: 18, right: 17)
|
||||||
hero.addArrangedSubview(greetingLabel)
|
hero.addArrangedSubview(greetingLabel)
|
||||||
@@ -83,7 +82,11 @@ final class TrainingCenterViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
hero.setCustomSpacing(18, after: titleLabel)
|
hero.setCustomSpacing(18, after: titleLabel)
|
||||||
hero.addArrangedSubview(stats)
|
hero.addArrangedSubview(stats)
|
||||||
header.addArrangedSubview(hero)
|
let heroContainer = UIStackView(arrangedSubviews: [hero])
|
||||||
|
heroContainer.axis = .vertical
|
||||||
|
heroContainer.isLayoutMarginsRelativeArrangement = true
|
||||||
|
heroContainer.layoutMargins = UIEdgeInsets(top: 12, left: 13, bottom: 12, right: 13)
|
||||||
|
header.addArrangedSubview(heroContainer)
|
||||||
let body = UIStackView()
|
let body = UIStackView()
|
||||||
body.axis = .vertical
|
body.axis = .vertical
|
||||||
body.spacing = 11
|
body.spacing = 11
|
||||||
|
|||||||
@@ -90,6 +90,11 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
|
|
||||||
override func viewDidLoad() {
|
override func viewDidLoad() {
|
||||||
super.viewDidLoad()
|
super.viewDidLoad()
|
||||||
|
viewModel.onDraftSaveStateChange = { [weak self] in
|
||||||
|
guard let self, !self.isPerformingOperation else { return }
|
||||||
|
self.applyState()
|
||||||
|
self.scheduleNavigationIfNeeded()
|
||||||
|
}
|
||||||
loadExam()
|
loadExam()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +116,10 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
override func viewWillDisappear(_ animated: Bool) {
|
override func viewWillDisappear(_ animated: Bool) {
|
||||||
super.viewWillDisappear(animated)
|
super.viewWillDisappear(animated)
|
||||||
// 自有答题卡和确认弹窗关闭后继续当前题,真实导航返回才刷新考试资格。
|
// 自有答题卡和确认弹窗关闭后继续当前题,真实导航返回才刷新考试资格。
|
||||||
if navigationController?.topViewController !== self { needsReloadOnReturn = true }
|
if navigationController?.topViewController !== self {
|
||||||
|
needsReloadOnReturn = true
|
||||||
|
Task { @MainActor in _ = await viewModel.flushDraft(service: service) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||||
@@ -128,7 +136,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
private func applyState() {
|
private func applyState() {
|
||||||
setOperationInteractionEnabled(true)
|
setOperationInteractionEnabled(true)
|
||||||
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
|
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
|
||||||
: viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
|
: viewModel.hasDraftConflict ? "确认本机答案" : viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
|
||||||
guard let question = viewModel.currentQuestion else {
|
guard let question = viewModel.currentQuestion else {
|
||||||
clearOptions()
|
clearOptions()
|
||||||
positionLabel.text = ""
|
positionLabel.text = ""
|
||||||
@@ -151,8 +159,10 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
for button in optionButtons.values { button.isEnabled = viewModel.canEdit }
|
for button in optionButtons.values { button.isEnabled = viewModel.canEdit }
|
||||||
previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0
|
previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0
|
||||||
nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1
|
nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1
|
||||||
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · 答案已保存,可稍后继续"
|
let saveState = viewModel.draftSaveMessage
|
||||||
statusLabel.textColor = viewModel.errorMessage == nil ? AppColor.textSecondary : AppColor.danger
|
statusLabel.text = viewModel.hasPendingMutation || viewModel.errorMessage == nil
|
||||||
|
? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · \(saveState)" : viewModel.errorMessage
|
||||||
|
statusLabel.textColor = viewModel.hasPendingMutation || viewModel.errorMessage != nil ? AppColor.danger : AppColor.textSecondary
|
||||||
submitButton.setTitle(pendingTitle ?? (viewModel.isBusy ? "正在保存…" : "交卷"), for: .normal)
|
submitButton.setTitle(pendingTitle ?? (viewModel.isBusy ? "正在保存…" : "交卷"), for: .normal)
|
||||||
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
|
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
|
||||||
}
|
}
|
||||||
@@ -259,18 +269,20 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func selectOption(_ id: String) {
|
private func selectOption(_ id: String) {
|
||||||
guard !isPerformingOperation, let selected = viewModel.selectionPreview(optionID: id) else { return }
|
guard !isPerformingOperation, viewModel.selectLocally(optionID: id, service: service) else { return }
|
||||||
updateOptionSelection(selected)
|
// desired 已同步更新;连续多选不等待 Task 或网络,保留同题按钮实例。
|
||||||
beginOperation(message: "正在保存答案…")
|
applyState()
|
||||||
Task { @MainActor in
|
|
||||||
await viewModel.select(optionID: id, service: service)
|
|
||||||
finishOperation()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func goToQuestion(_ index: Int) {
|
private func goToQuestion(_ index: Int) {
|
||||||
guard !isPerformingOperation, viewModel.canEdit,
|
guard !isPerformingOperation, viewModel.canEdit,
|
||||||
(0..<viewModel.questionCount).contains(index), index != viewModel.currentIndex else { return }
|
(0..<viewModel.questionCount).contains(index), index != viewModel.currentIndex else { return }
|
||||||
|
if viewModel.goToCachedQuestion(index, service: service) {
|
||||||
|
applyState()
|
||||||
|
scrollView.setContentOffset(.zero, animated: false)
|
||||||
|
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
|
||||||
|
return
|
||||||
|
}
|
||||||
beginOperation(message: "正在加载题目…")
|
beginOperation(message: "正在加载题目…")
|
||||||
Task { @MainActor in
|
Task { @MainActor in
|
||||||
await viewModel.goToQuestion(index, service: service)
|
await viewModel.goToQuestion(index, service: service)
|
||||||
@@ -295,9 +307,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
|
|
||||||
@objc private func submitTapped() {
|
@objc private func submitTapped() {
|
||||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||||
|
if viewModel.hasDraftConflict { confirmDraftConflict(); return }
|
||||||
if viewModel.hasPendingMutation {
|
if viewModel.hasPendingMutation {
|
||||||
beginOperation(message: "正在重试保存…")
|
Task { @MainActor in await viewModel.retryMutation(service: service); applyState() }
|
||||||
Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() }
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if viewModel.hasPendingSubmission { performSubmit(); return }
|
if viewModel.hasPendingSubmission { performSubmit(); return }
|
||||||
@@ -320,6 +332,23 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
present(alert, animated: true)
|
present(alert, animated: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func confirmDraftConflict() {
|
||||||
|
guard presentedViewController == nil else { return }
|
||||||
|
let alert = UIAlertController(title: "答案已在其他设备变更", message: "本机尚未保存的选择已保留。应用本机选择会更新对应题目的答案,也可以使用其他设备已保存的答案。", preferredStyle: .alert)
|
||||||
|
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
|
||||||
|
for (title, useLocal) in [("使用已保存答案", false), ("应用本机选择", true)] {
|
||||||
|
alert.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in
|
||||||
|
guard let self else { return }
|
||||||
|
self.beginOperation(message: "正在确认草稿…", showsLoading: false)
|
||||||
|
Task { @MainActor in
|
||||||
|
await self.viewModel.resolveDraftConflict(useLocalAnswers: useLocal, service: self.service)
|
||||||
|
self.finishOperation()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
present(alert, animated: true)
|
||||||
|
}
|
||||||
|
|
||||||
private func performSubmit() {
|
private func performSubmit() {
|
||||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||||
beginOperation(message: "正在提交并确认成绩…")
|
beginOperation(message: "正在提交并确认成绩…")
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 草稿日志的身份隔离、格式校验与跨页面代次保护。
|
||||||
|
@Suite("培训本机草稿持久化")
|
||||||
|
struct TrainingDraftStoreTests {
|
||||||
|
private let context = TrainingContext(accountScope: "account_1", scenicID: 10, storeID: 3)
|
||||||
|
|
||||||
|
@Test("原子文件在新存储实例和不同defaults域中恢复同一日志,不依赖异步defaults刷新")
|
||||||
|
func atomicFileSurvivesReconstruction() throws {
|
||||||
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("TrainingDraftStore-\(UUID().uuidString)")
|
||||||
|
defer { try? FileManager.default.removeItem(at: directory) }
|
||||||
|
let name = "TrainingDraftStoreTests-\(UUID().uuidString)"
|
||||||
|
let otherName = name + "-other"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
let otherDefaults = try #require(UserDefaults(suiteName: otherName))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name); otherDefaults.removePersistentDomain(forName: otherName) }
|
||||||
|
let original = TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1", context: context, revision: 5,
|
||||||
|
answers: [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["A"])])
|
||||||
|
let store = TrainingDraftStore(defaults: defaults, directoryURL: directory)
|
||||||
|
let generation = try store.save(original, replacing: nil)
|
||||||
|
let reconstructed = TrainingDraftStore(defaults: otherDefaults, directoryURL: directory)
|
||||||
|
let restored = try #require(try reconstructed.load(taskID: "task_1", paperSnapshotID: "paper_1", context: context))
|
||||||
|
#expect(restored.generation == generation)
|
||||||
|
#expect(restored.answers == original.answers)
|
||||||
|
#expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).count == 1)
|
||||||
|
#expect(defaults.persistentDomain(forName: name)?.isEmpty != false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("按账号景区店铺任务试卷隔离,恢复原请求与本机较新意图且不含token")
|
||||||
|
func partitionedRecovery() throws {
|
||||||
|
let name = "TrainingDraftStoreTests-\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let store = TrainingDraftStore(defaults: defaults)
|
||||||
|
let request = TrainingDraftSaveRequest(requestID: "original", paperSnapshotID: "paper_1", baseRevision: 5,
|
||||||
|
lastQuestionOrder: 2, changes: [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["A"])])
|
||||||
|
let record = TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1", context: context, revision: 5,
|
||||||
|
answers: [TrainingDraftLocalAnswer(questionID: "q2", order: 2, selectedOptionIDs: ["A", "B"])],
|
||||||
|
lastQuestionOrder: 2, pendingSave: request)
|
||||||
|
try store.save(record, replacing: nil)
|
||||||
|
let restored = try #require(try store.load(taskID: "task_1", paperSnapshotID: "paper_1", context: context))
|
||||||
|
#expect(restored.answers == record.answers)
|
||||||
|
#expect(restored.pendingSave == request)
|
||||||
|
for other in [TrainingContext(accountScope: "account_2", scenicID: 10, storeID: 3),
|
||||||
|
TrainingContext(accountScope: "account_1", scenicID: 11, storeID: 3),
|
||||||
|
TrainingContext(accountScope: "account_1", scenicID: 10, storeID: 4)] {
|
||||||
|
#expect(try store.load(taskID: "task_1", paperSnapshotID: "paper_1", context: other) == nil)
|
||||||
|
}
|
||||||
|
#expect(try store.load(taskID: "task_2", paperSnapshotID: "paper_1", context: context) == nil)
|
||||||
|
#expect(try store.load(taskID: "task_1", paperSnapshotID: "paper_2", context: context) == nil)
|
||||||
|
let values = defaults.persistentDomain(forName: name)?.values.compactMap { $0 as? Data } ?? []
|
||||||
|
let encoded = try #require(values.first.flatMap { String(data: $0, encoding: .utf8) })
|
||||||
|
#expect(!encoded.lowercased().contains("token"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("新页面接管后,旧ACK不能清除新选择,已保存的空日志仍拒绝旧代次复写")
|
||||||
|
func compareAndSwapProtectsNewPage() throws {
|
||||||
|
let name = "TrainingDraftStoreTests-\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let store = TrainingDraftStore(defaults: defaults)
|
||||||
|
var record = TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1", context: context, revision: 1,
|
||||||
|
answers: [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["A"])])
|
||||||
|
let oldGeneration = try store.save(record, replacing: nil)
|
||||||
|
record.answers = [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["B"])]
|
||||||
|
let newGeneration = try store.save(record, replacing: oldGeneration)
|
||||||
|
record.answers = []
|
||||||
|
#expect(throws: TrainingDraftStorageError.replaced) { try store.save(record, replacing: oldGeneration) }
|
||||||
|
#expect(try store.load(taskID: "task_1", paperSnapshotID: "paper_1", context: context)?.answers.first?.selectedOptionIDs == ["B"])
|
||||||
|
try store.save(record, replacing: newGeneration)
|
||||||
|
#expect(throws: TrainingDraftStorageError.replaced) { try store.save(record, replacing: oldGeneration) }
|
||||||
|
#expect(throws: TrainingDraftStorageError.replaced) { try store.save(record, replacing: nil) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("重复题号、非法选项、越界位置或超过20条的在飞请求不能覆盖有效日志")
|
||||||
|
func rejectsMalformedRecords() throws {
|
||||||
|
let name = "TrainingDraftStoreTests-\(UUID().uuidString)"
|
||||||
|
let defaults = try #require(UserDefaults(suiteName: name))
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let store = TrainingDraftStore(defaults: defaults)
|
||||||
|
let valid = TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1", context: context, revision: 3)
|
||||||
|
let generation = try store.save(valid, replacing: nil)
|
||||||
|
var malformed: [TrainingDraftRecord] = []
|
||||||
|
var record = valid
|
||||||
|
record.answers = [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["A"]),
|
||||||
|
TrainingDraftLocalAnswer(questionID: "q2", order: 1, selectedOptionIDs: ["B"])]
|
||||||
|
malformed.append(record)
|
||||||
|
record = valid
|
||||||
|
record.answers = [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: [""])]
|
||||||
|
malformed.append(record)
|
||||||
|
record = valid
|
||||||
|
record.lastQuestionOrder = 501
|
||||||
|
malformed.append(record)
|
||||||
|
record = valid
|
||||||
|
record.pendingSave = TrainingDraftSaveRequest(requestID: "invalid", paperSnapshotID: "paper_1", baseRevision: 3,
|
||||||
|
lastQuestionOrder: 1, changes: (1...21).map { TrainingDraftChange(questionID: "q\($0)", selectedOptionIDs: ["A"]) })
|
||||||
|
malformed.append(record)
|
||||||
|
record = valid
|
||||||
|
record.pendingSave = TrainingDraftSaveRequest(requestID: "duplicate", paperSnapshotID: "paper_1", baseRevision: 3,
|
||||||
|
lastQuestionOrder: 1, changes: [TrainingDraftChange(questionID: "q1", selectedOptionIDs: ["A"]),
|
||||||
|
TrainingDraftChange(questionID: "q1", selectedOptionIDs: ["B"])])
|
||||||
|
malformed.append(record)
|
||||||
|
for value in malformed {
|
||||||
|
#expect(throws: TrainingDraftStorageError.invalidRecord) { try store.save(value, replacing: generation) }
|
||||||
|
}
|
||||||
|
#expect(try store.load(taskID: "task_1", paperSnapshotID: "paper_1", context: context)?.generation == generation)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 暂停第一批 ACK,允许测试在请求未确认期间继续点击和切题。
|
||||||
|
private actor TrainingDraftWriterGate {
|
||||||
|
private var continuation: CheckedContinuation<Void, Never>?
|
||||||
|
private var released = false
|
||||||
|
private var count = 0
|
||||||
|
|
||||||
|
/// 只暂停首次保存,后续串行批次直接返回。
|
||||||
|
func pauseFirst() async {
|
||||||
|
count += 1
|
||||||
|
guard count == 1, !released else { return }
|
||||||
|
await withCheckedContinuation { continuation = $0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 释放尚未确认的请求,也支持在请求进入前释放。
|
||||||
|
func release() { released = true; continuation?.resume(); continuation = nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 确保超时重试可以单独返回原请求的历史 ACK。
|
||||||
|
private actor TrainingDraftRetryCounter {
|
||||||
|
private var count = 0
|
||||||
|
/// 递增调用次数。
|
||||||
|
func next() -> Int { count += 1; return count }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求悬停期间切换身份的可控来源。
|
||||||
|
@MainActor
|
||||||
|
private final class TrainingDraftTestIdentity {
|
||||||
|
var context: TrainingContext?
|
||||||
|
/// 固定首次进入时的账号范围。
|
||||||
|
init(_ context: TrainingContext) { self.context = context }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本机意图、后台串行保存、持久恢复和交卷屏障的独立回归。
|
||||||
|
@Suite("培训草稿后台合并保存")
|
||||||
|
@MainActor
|
||||||
|
struct TrainingDraftWriterTests {
|
||||||
|
private let context = TrainingContext(accountScope: "draft_writer", scenicID: 10, storeID: 3)
|
||||||
|
|
||||||
|
private func domain() throws -> (String, UserDefaults) {
|
||||||
|
let name = "TrainingDraftWriterTests-\(UUID().uuidString)"
|
||||||
|
return (name, try #require(UserDefaults(suiteName: name)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func model(_ defaults: UserDefaults) -> TrainingRemoteExamViewModel {
|
||||||
|
let scope = context
|
||||||
|
return TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
||||||
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults),
|
||||||
|
debounceNanoseconds: 60_000_000_000, currentContext: { scope })
|
||||||
|
}
|
||||||
|
|
||||||
|
private func waitUntil(_ predicate: () async -> Bool) async throws {
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||||
|
while !(await predicate()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(5)) }
|
||||||
|
#expect(await predicate())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("重复单选无请求,快速多选及跨缓存题变化合并成一批")
|
||||||
|
func coalescesLocalChoicesAcrossCachedQuestions() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.questionsHandler = { offset, limit in
|
||||||
|
let end = min(30, offset + limit)
|
||||||
|
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset,
|
||||||
|
nextOffset: end < 30 ? end : nil, hasMore: end < 30,
|
||||||
|
items: ((offset + 1)...end).map { order in
|
||||||
|
let value = TrainingRemoteFixtures.question(order)
|
||||||
|
return TrainingQuestionItem(id: value.id, order: order, type: order == 2 ? .multiple : .single,
|
||||||
|
stem: value.stem, options: value.options)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
await source.seedDraft(revision: 3, answers: ["q1": ["A"]])
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
#expect(!vm.selectLocally(optionID: "A", service: source))
|
||||||
|
#expect(vm.selectLocally(optionID: "B", service: source))
|
||||||
|
#expect(vm.goToCachedQuestion(1, service: source))
|
||||||
|
#expect(vm.selectLocally(optionID: "A", service: source))
|
||||||
|
#expect(vm.selectLocally(optionID: "B", service: source))
|
||||||
|
#expect(vm.currentSelectedIDs == ["A", "B"])
|
||||||
|
#expect(vm.answeredQuestionOrders == [1, 2])
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
#expect(await vm.flushDraft(service: source))
|
||||||
|
let requests = await source.savedRequests
|
||||||
|
#expect(requests.count == 1)
|
||||||
|
#expect(requests.first?.baseRevision == 3)
|
||||||
|
#expect(requests.first?.changes == [TrainingDraftChange(questionID: "q1", selectedOptionIDs: ["B"]),
|
||||||
|
TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["A", "B"])])
|
||||||
|
#expect(!vm.hasUnsavedChanges)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("超过20题的本机修改按协议边界串行拆批,并逐批推进确认版本")
|
||||||
|
func batchesAtTwentyChanges() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
for index in 0..<25 {
|
||||||
|
if index != vm.currentIndex { await vm.goToQuestion(index, service: source) }
|
||||||
|
#expect(vm.selectLocally(optionID: "A", service: source))
|
||||||
|
}
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
#expect(await vm.flushDraft(service: source))
|
||||||
|
let requests = await source.savedRequests
|
||||||
|
#expect(requests.map { $0.changes.count } == [20, 5])
|
||||||
|
#expect(requests.map(\.baseRevision) == [1, 2])
|
||||||
|
#expect(vm.answeredCount == 25)
|
||||||
|
#expect(!vm.hasUnsavedChanges)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未缓存题读取悬停时防抖及离页flush都等读取完成,不并发写旧版本")
|
||||||
|
func uncachedReadCoordinatesDebounceAndFlush() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let gate = TrainingDraftWriterGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.questionsHandler = { offset, limit in
|
||||||
|
if offset == 10 { await gate.pauseFirst() }
|
||||||
|
let end = min(30, offset + limit)
|
||||||
|
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset,
|
||||||
|
nextOffset: end < 30 ? end : nil, hasMore: end < 30,
|
||||||
|
items: ((offset + 1)...end).map(TrainingRemoteFixtures.question))
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
let scope = context
|
||||||
|
let vm = TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
||||||
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults),
|
||||||
|
debounceNanoseconds: 20_000_000, currentContext: { scope })
|
||||||
|
await vm.load(service: source)
|
||||||
|
vm.selectLocally(optionID: "A", service: source)
|
||||||
|
let navigate = Task { await vm.goToQuestion(10, service: source) }
|
||||||
|
try await waitUntil { (await source.calls).contains { $0.name == "questions" && $0.offset == 10 } }
|
||||||
|
let leavingFlush = Task { await vm.flushDraft(service: source) }
|
||||||
|
try await Task.sleep(for: .milliseconds(50))
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
await gate.release()
|
||||||
|
await navigate.value
|
||||||
|
#expect(await leavingFlush.value)
|
||||||
|
#expect(vm.currentQuestion?.id == "q11")
|
||||||
|
#expect(await source.savedRequests.count == 1)
|
||||||
|
#expect(await source.savedRequests.first?.lastQuestionOrder == 11)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("原子日志写入失败时保留期望选择并阻止发起PATCH")
|
||||||
|
func failedDiskWriteStopsNetworkMutation() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("TrainingDraftWriteFailure-\(UUID().uuidString)")
|
||||||
|
defer { try? FileManager.default.removeItem(at: directory) }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
let scope = context
|
||||||
|
let vm = TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
||||||
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults),
|
||||||
|
draftStore: TrainingDraftStore(defaults: defaults, directoryURL: directory),
|
||||||
|
debounceNanoseconds: 60_000_000_000, currentContext: { scope })
|
||||||
|
await vm.load(service: source)
|
||||||
|
#expect(vm.canEdit)
|
||||||
|
try FileManager.default.removeItem(at: directory)
|
||||||
|
try Data("blocks-directory".utf8).write(to: directory)
|
||||||
|
#expect(vm.selectLocally(optionID: "A", service: source))
|
||||||
|
#expect(vm.currentSelectedIDs == ["A"])
|
||||||
|
#expect(!vm.canEdit && vm.hasPendingMutation)
|
||||||
|
#expect(!(await vm.flushDraft(service: source)))
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("B已确认、A在飞时改回B,慢ACK不能清除新意图且下批用最新版本")
|
||||||
|
func slowAcknowledgementCannotOverwriteReverseSelection() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let gate = TrainingDraftWriterGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.seedDraft(revision: 5, answers: ["q1": ["B"]])
|
||||||
|
await source.configure { configuration in
|
||||||
|
configuration.saveHandler = { request in
|
||||||
|
await gate.pauseFirst()
|
||||||
|
await source.seedDraft(revision: request.baseRevision + 1,
|
||||||
|
answers: ["q1": request.changes.first?.selectedOptionIDs ?? []])
|
||||||
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||||
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
vm.selectLocally(optionID: "A", service: source)
|
||||||
|
let flush = Task { await vm.flushDraft(service: source) }
|
||||||
|
try await waitUntil { await source.savedRequests.count == 1 }
|
||||||
|
#expect(vm.isSaving && vm.canEdit && !vm.isBusy)
|
||||||
|
vm.selectLocally(optionID: "B", service: source)
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
let journal = try #require(try TrainingDraftStore(defaults: defaults).load(taskID: "task_1", paperSnapshotID: "paper_1", context: context))
|
||||||
|
#expect(journal.pendingSave?.changes.first?.selectedOptionIDs == ["A"])
|
||||||
|
#expect(journal.answers.first?.selectedOptionIDs == ["B"])
|
||||||
|
await gate.release()
|
||||||
|
#expect(await flush.value)
|
||||||
|
let requests = await source.savedRequests
|
||||||
|
#expect(requests.map(\.baseRevision) == [5, 6])
|
||||||
|
#expect(requests.map { $0.changes.first?.selectedOptionIDs } == [["A"], ["B"]])
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
#expect(!vm.hasUnsavedChanges)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("交卷等待在飞及后续意图全部确认,期间锁编辑并只提交最终版本")
|
||||||
|
func submissionFlushesAllChangesBeforeRequest() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let gate = TrainingDraftWriterGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.questionCount = 1
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
await source.seedDraft(revision: 5, answers: ["q1": ["B"]])
|
||||||
|
await source.configure { configuration in
|
||||||
|
configuration.saveHandler = { request in
|
||||||
|
await gate.pauseFirst()
|
||||||
|
await source.seedDraft(revision: request.baseRevision + 1,
|
||||||
|
answers: ["q1": request.changes.first?.selectedOptionIDs ?? []])
|
||||||
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||||
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
vm.selectLocally(optionID: "A", service: source)
|
||||||
|
let save = Task { await vm.flushDraft(service: source) }
|
||||||
|
try await waitUntil { await source.savedRequests.count == 1 }
|
||||||
|
vm.selectLocally(optionID: "B", service: source)
|
||||||
|
let submit = Task { await vm.submit(service: source) }
|
||||||
|
try await waitUntil { vm.isBusy }
|
||||||
|
#expect(!vm.canEdit)
|
||||||
|
#expect(!vm.selectLocally(optionID: "A", service: source))
|
||||||
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
|
await gate.release()
|
||||||
|
#expect(await save.value)
|
||||||
|
#expect(await submit.value?.id == "attempt_1")
|
||||||
|
#expect(await source.submissionRequests.first?.draftRevision == 7)
|
||||||
|
#expect(await source.savedRequests.count == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("恢复尚未发送的选择发现服务端版本已改变,保留overlay并等待明确确认")
|
||||||
|
func recoveredDirtyDraftDoesNotOverwriteNewRemoteRevision() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let store = TrainingDraftStore(defaults: defaults)
|
||||||
|
try store.save(TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1", context: context, revision: 2,
|
||||||
|
answers: [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["A"])], lastQuestionOrder: 1), replacing: nil)
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.seedDraft(revision: 9, answers: ["q1": ["B"]])
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
#expect(vm.currentSelectedIDs == ["A"])
|
||||||
|
#expect(vm.hasDraftConflict && vm.canEdit)
|
||||||
|
#expect(!(await vm.flushDraft(service: source)))
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
await vm.resolveDraftConflict(useLocalAnswers: true, service: source)
|
||||||
|
#expect(await source.savedRequests.first?.baseRevision == 9)
|
||||||
|
#expect(vm.currentSelectedIDs == ["A"])
|
||||||
|
#expect(!vm.hasDraftConflict && !vm.hasUnsavedChanges)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未知原请求跨页面恢复后先同键确认,再发送本机较新选择")
|
||||||
|
func restoresFrozenRequestAndNewerIntent() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let request = TrainingDraftSaveRequest(requestID: "frozen", paperSnapshotID: "paper_1", baseRevision: 4,
|
||||||
|
lastQuestionOrder: 1, changes: [TrainingDraftChange(questionID: "q1", selectedOptionIDs: ["A"])])
|
||||||
|
try TrainingDraftStore(defaults: defaults).save(TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1",
|
||||||
|
context: context, revision: 4, answers: [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["B"])],
|
||||||
|
lastQuestionOrder: 1, pendingSave: request), replacing: nil)
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.seedDraft(revision: 4, answers: [:])
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
let requests = await source.savedRequests
|
||||||
|
#expect(requests.count == 2)
|
||||||
|
#expect(requests.first == request)
|
||||||
|
#expect(requests.last?.baseRevision == 5)
|
||||||
|
#expect(requests.last?.changes.first?.selectedOptionIDs == ["B"])
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
#expect(!vm.hasUnsavedChanges)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("重建重考页恢复未知reset只用原键,成功返回的新答案不被第二次新键清空")
|
||||||
|
func restoredResetDoesNotCreateSecondReset() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let request = TrainingDraftResetRequest(requestID: "original_reset", paperSnapshotID: "paper_1", baseRevision: 3)
|
||||||
|
try TrainingDraftStore(defaults: defaults).save(TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1",
|
||||||
|
context: context, revision: 3, pendingReset: request), replacing: nil)
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.seedDraft(revision: 5, answers: ["q1": ["B"]])
|
||||||
|
await source.configure { configuration in
|
||||||
|
configuration.resetHandler = { _ in
|
||||||
|
TrainingDraftConfirmation(draftRevision: 5, savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source, resetDraft: true)
|
||||||
|
#expect(await source.resetRequests == [request])
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
#expect(vm.canEdit)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("未知请求重试返回历史ACK低于已观察版本时,较新意图不得静默覆盖云端")
|
||||||
|
func historicalAcknowledgementRequiresConflictConfirmation() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let request = TrainingDraftSaveRequest(requestID: "frozen", paperSnapshotID: "paper_1", baseRevision: 5,
|
||||||
|
lastQuestionOrder: 1, changes: [TrainingDraftChange(questionID: "q1", selectedOptionIDs: ["A"])])
|
||||||
|
try TrainingDraftStore(defaults: defaults).save(TrainingDraftRecord(taskID: "task_1", paperSnapshotID: "paper_1",
|
||||||
|
context: context, revision: 5, answers: [TrainingDraftLocalAnswer(questionID: "q1", order: 1, selectedOptionIDs: ["B"])],
|
||||||
|
lastQuestionOrder: 1, pendingSave: request), replacing: nil)
|
||||||
|
let counter = TrainingDraftRetryCounter()
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.seedDraft(revision: 100, answers: ["q1": ["A"]])
|
||||||
|
await source.configure { configuration in
|
||||||
|
configuration.saveHandler = { _ in
|
||||||
|
if await counter.next() == 1 { throw URLError(.timedOut) }
|
||||||
|
return TrainingDraftConfirmation(draftRevision: 6, savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
#expect(vm.draftRevision == 100)
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
await vm.retryMutation(service: source)
|
||||||
|
#expect(vm.hasDraftConflict)
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
#expect(await source.savedRequests == [request, request])
|
||||||
|
#expect(!(await vm.flushDraft(service: source)))
|
||||||
|
#expect(await source.savedRequests.count == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("身份变化拒绝迟到ACK,原账号日志保留且不向新账号继续发送")
|
||||||
|
func identityChangePreservesOriginalJournal() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let identity = TrainingDraftTestIdentity(context)
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
let gate = TrainingDraftWriterGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
await source.configure { configuration in
|
||||||
|
configuration.saveHandler = { request in
|
||||||
|
await gate.pauseFirst()
|
||||||
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||||
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let vm = TrainingRemoteExamViewModel(taskID: "task_1", context: context,
|
||||||
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults),
|
||||||
|
debounceNanoseconds: 60_000_000_000, currentContext: { identity.context })
|
||||||
|
await vm.load(service: source)
|
||||||
|
vm.selectLocally(optionID: "A", service: source)
|
||||||
|
let flush = Task { await vm.flushDraft(service: source) }
|
||||||
|
try await waitUntil { await source.savedRequests.count == 1 }
|
||||||
|
let store = TrainingDraftStore(defaults: defaults)
|
||||||
|
let original = try #require(try store.load(taskID: "task_1", paperSnapshotID: "paper_1", context: context))
|
||||||
|
identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3)
|
||||||
|
await gate.release()
|
||||||
|
#expect(!(await flush.value))
|
||||||
|
#expect(vm.isIdentityInvalid && vm.shouldReturnToCenter)
|
||||||
|
#expect(vm.currentQuestion == nil && vm.currentSelectedIDs.isEmpty)
|
||||||
|
#expect(try store.load(taskID: "task_1", paperSnapshotID: "paper_1", context: context) == original)
|
||||||
|
#expect(await source.savedRequests.count == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("普通版本冲突明确选择云端时只丢本机未保存意图,不重发PATCH")
|
||||||
|
func conflictCanUseSavedAnswers() async throws {
|
||||||
|
let (name, defaults) = try domain()
|
||||||
|
defer { defaults.removePersistentDomain(forName: name) }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
let vm = model(defaults)
|
||||||
|
await vm.load(service: source)
|
||||||
|
await source.seedDraft(revision: 7, answers: ["q1": ["B"]])
|
||||||
|
vm.selectLocally(optionID: "A", service: source)
|
||||||
|
#expect(!(await vm.flushDraft(service: source)))
|
||||||
|
#expect(vm.currentSelectedIDs == ["A"] && vm.hasDraftConflict)
|
||||||
|
await vm.resolveDraftConflict(useLocalAnswers: false, service: source)
|
||||||
|
#expect(vm.currentSelectedIDs == ["B"])
|
||||||
|
#expect(await source.savedRequests.count == 1)
|
||||||
|
#expect(!vm.hasUnsavedChanges && !vm.hasDraftConflict)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,12 +3,11 @@ import Testing
|
|||||||
import UIKit
|
import UIKit
|
||||||
@testable import suixinkan
|
@testable import suixinkan
|
||||||
|
|
||||||
/// 分别在分页正文和位置保存阶段,覆盖前后翻题的同步动作锁。
|
/// 仅未缓存题页读取需要同步动作锁,位置保存由后台串行处理。
|
||||||
enum TrainingNavigationScenario: String, CaseIterable, Sendable {
|
enum TrainingNavigationScenario: String, CaseIterable, Sendable {
|
||||||
case previousQuestions, nextQuestions, previousPosition, nextPosition
|
case previousQuestions, nextQuestions
|
||||||
|
|
||||||
var isPrevious: Bool { self == .previousQuestions || self == .previousPosition }
|
var isPrevious: Bool { self == .previousQuestions }
|
||||||
var waitsForQuestions: Bool { self == .previousQuestions || self == .nextQuestions }
|
|
||||||
var initialOrder: Int { isPrevious ? 11 : 10 }
|
var initialOrder: Int { isPrevious ? 11 : 10 }
|
||||||
var targetOrder: Int { isPrevious ? 10 : 11 }
|
var targetOrder: Int { isPrevious ? 10 : 11 }
|
||||||
var initialOffset: Int { isPrevious ? 10 : 0 }
|
var initialOffset: Int { isPrevious ? 10 : 0 }
|
||||||
@@ -64,7 +63,7 @@ private struct TrainingNavigationButtonAppearance: Equatable {
|
|||||||
struct TrainingExamNavigationInteractionTests {
|
struct TrainingExamNavigationInteractionTests {
|
||||||
private let context = TrainingContext(accountScope: "exam_navigation", scenicID: 10, storeID: 3)
|
private let context = TrainingContext(accountScope: "exam_navigation", scenicID: 10, storeID: 3)
|
||||||
|
|
||||||
@Test("前后翻题等待题页或位置保存时不置灰,重复动作不会偏离目标", arguments: TrainingNavigationScenario.allCases)
|
@Test("未缓存题页读取时不置灰,重复动作不会偏离目标", arguments: TrainingNavigationScenario.allCases)
|
||||||
func navigationPreservesAppearanceAndTarget(scenario: TrainingNavigationScenario) async throws {
|
func navigationPreservesAppearanceAndTarget(scenario: TrainingNavigationScenario) async throws {
|
||||||
let domain = try makeDefaults()
|
let domain = try makeDefaults()
|
||||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
@@ -72,14 +71,9 @@ struct TrainingExamNavigationInteractionTests {
|
|||||||
defer { Task { await gate.release() } }
|
defer { Task { await gate.release() } }
|
||||||
var configuration = TrainingDataStub.Configuration()
|
var configuration = TrainingDataStub.Configuration()
|
||||||
configuration.questionsHandler = { offset, limit in
|
configuration.questionsHandler = { offset, limit in
|
||||||
if scenario.waitsForQuestions, offset == scenario.targetOffset { await gate.wait() }
|
if offset == scenario.targetOffset { await gate.wait() }
|
||||||
return Self.questions(total: 30, offset: offset, limit: limit)
|
return Self.questions(total: 30, offset: offset, limit: limit)
|
||||||
}
|
}
|
||||||
configuration.saveHandler = { request in
|
|
||||||
if !scenario.waitsForQuestions { await gate.wait() }
|
|
||||||
return TrainingDraftConfirmation(draftRevision: request.baseRevision,
|
|
||||||
savedAt: TrainingRemoteFixtures.now, answeredCount: 30)
|
|
||||||
}
|
|
||||||
let source = TrainingDataStub(configuration: configuration)
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
await source.seedDraft(revision: 5, answers: Dictionary(uniqueKeysWithValues: (1...30).map { ("q\($0)", ["A"]) }), lastOrder: scenario.initialOrder)
|
await source.seedDraft(revision: 5, answers: Dictionary(uniqueKeysWithValues: (1...30).map { ("q\($0)", ["A"]) }), lastOrder: scenario.initialOrder)
|
||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
@@ -125,7 +119,7 @@ struct TrainingExamNavigationInteractionTests {
|
|||||||
#expect(await source.submissionRequests.isEmpty)
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
let questionsWhileWaiting = await source.calls.filter { $0.name == "questions" }
|
let questionsWhileWaiting = await source.calls.filter { $0.name == "questions" }
|
||||||
#expect(questionsWhileWaiting.map(\.offset) == [scenario.initialOffset, scenario.targetOffset])
|
#expect(questionsWhileWaiting.map(\.offset) == [scenario.initialOffset, scenario.targetOffset])
|
||||||
#expect(await source.savedRequests.count == (scenario.waitsForQuestions ? 0 : 1))
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
|
||||||
await gate.release()
|
await gate.release()
|
||||||
try await waitUntil {
|
try await waitUntil {
|
||||||
@@ -136,6 +130,7 @@ struct TrainingExamNavigationInteractionTests {
|
|||||||
#expect(model.errorMessage == nil)
|
#expect(model.errorMessage == nil)
|
||||||
#expect([previous, next, submit].allSatisfy { $0.isEnabled && $0.isUserInteractionEnabled })
|
#expect([previous, next, submit].allSatisfy { $0.isEnabled && $0.isUserInteractionEnabled })
|
||||||
#expect([previous, next, submit].map { TrainingNavigationButtonAppearance($0) } == Array(appearances.prefix(3)))
|
#expect([previous, next, submit].map { TrainingNavigationButtonAppearance($0) } == Array(appearances.prefix(3)))
|
||||||
|
#expect(await model.flushDraft(service: source))
|
||||||
let requests = await source.savedRequests
|
let requests = await source.savedRequests
|
||||||
#expect(requests.count == 1)
|
#expect(requests.count == 1)
|
||||||
#expect(requests.first?.lastQuestionOrder == scenario.targetOrder)
|
#expect(requests.first?.lastQuestionOrder == scenario.targetOrder)
|
||||||
@@ -176,6 +171,7 @@ struct TrainingExamNavigationInteractionTests {
|
|||||||
#expect(allowed.alpha == 1)
|
#expect(allowed.alpha == 1)
|
||||||
#expect(button("training.exam.submit", in: controller.view)?.isEnabled == true)
|
#expect(button("training.exam.submit", in: controller.view)?.isEnabled == true)
|
||||||
#expect(controller.navigationItem.rightBarButtonItem?.isEnabled == true)
|
#expect(controller.navigationItem.rightBarButtonItem?.isEnabled == true)
|
||||||
|
#expect(await model.flushDraft(service: source))
|
||||||
let before = await source.calls
|
let before = await source.calls
|
||||||
disabled.sendActions(for: .touchUpInside)
|
disabled.sendActions(for: .touchUpInside)
|
||||||
try await settleTransitions([navigation, controller])
|
try await settleTransitions([navigation, controller])
|
||||||
@@ -271,12 +267,75 @@ struct TrainingExamNavigationInteractionTests {
|
|||||||
#expect(finalCalls.filter { $0.name == "questions" }.map(\.offset) == [400, 490])
|
#expect(finalCalls.filter { $0.name == "questions" }.map(\.offset) == [400, 490])
|
||||||
#expect(finalCalls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 10])
|
#expect(finalCalls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 10])
|
||||||
#expect(finalCalls.filter { $0.name == "questions" }.allSatisfy { $0.limit == 10 })
|
#expect(finalCalls.filter { $0.name == "questions" }.allSatisfy { $0.limit == 10 })
|
||||||
|
#expect(await model.flushDraft(service: source))
|
||||||
let saves = await source.savedRequests
|
let saves = await source.savedRequests
|
||||||
#expect(saves.count == 1)
|
#expect(saves.count == 1)
|
||||||
#expect(saves.first?.lastQuestionOrder == 500 && saves.first?.changes.isEmpty == true)
|
#expect(saves.first?.lastQuestionOrder == 500 && saves.first?.changes.isEmpty == true)
|
||||||
#expect(await source.submissionRequests.isEmpty)
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test("保存挂起时缓存翻题和答题卡继续可用,本地答案不会被旧页刷新覆盖")
|
||||||
|
func cachedNavigationAndAnswerCardRemainAvailableWhileSaving() async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let domain = try makeDefaults()
|
||||||
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
|
let gate = TrainingNavigationRequestGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.questionCount = 3
|
||||||
|
configuration.saveHandler = { request in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + (request.changes.isEmpty ? 0 : 1),
|
||||||
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 3)
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
await source.seedDraft(revision: 5, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]], lastOrder: 2)
|
||||||
|
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 }
|
||||||
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
|
try await settleTransitions([navigation, controller])
|
||||||
|
let initialReads = await source.calls.filter { ["task", "progress", "paper", "questions", "draft"].contains($0.name) }
|
||||||
|
let optionB = try #require(button("training.option.B", in: controller.view))
|
||||||
|
optionB.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { await gate.requestCount == 1 }
|
||||||
|
#expect(model.isSaving && model.canEdit && !manager.isShowing)
|
||||||
|
let next = try #require(button("training.exam.next", in: controller.view))
|
||||||
|
next.sendActions(for: .touchUpInside)
|
||||||
|
// 缓存跳转须当场完成,不能等正在保存的首批请求。
|
||||||
|
#expect(model.currentIndex == 2 && model.currentQuestion?.id == "q3")
|
||||||
|
#expect(!model.isBusy && model.isSaving && !manager.isShowing)
|
||||||
|
#expect(!next.isEnabled)
|
||||||
|
let previous = try #require(button("training.exam.previous", in: controller.view))
|
||||||
|
#expect(previous.isEnabled && previous.isUserInteractionEnabled)
|
||||||
|
previous.sendActions(for: .touchUpInside)
|
||||||
|
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
||||||
|
#expect(button("training.option.B", in: controller.view)?.accessibilityTraits.contains(.selected) == true)
|
||||||
|
#expect(!manager.isShowing && model.canEdit)
|
||||||
|
let cardSheet = try await openAnswerCard(controller)
|
||||||
|
let card = try #require(cardSheet.topViewController as? TrainingAnswerCardViewController)
|
||||||
|
let collection = try #require(allViews(card.view).compactMap { $0 as? UICollectionView }.first)
|
||||||
|
try await waitUntil { collection.numberOfItems(inSection: 0) == 3 }
|
||||||
|
#expect(!manager.isShowing && model.isSaving)
|
||||||
|
let done = try #require(card.navigationItem.rightBarButtonItem)
|
||||||
|
try activate(done)
|
||||||
|
try await waitUntil { controller.presentedViewController == nil }
|
||||||
|
try await settleTransitions([navigation, controller, cardSheet])
|
||||||
|
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
||||||
|
#expect(!manager.isShowing && model.canEdit)
|
||||||
|
#expect(await source.savedRequests.count == 1)
|
||||||
|
let finalReads = await source.calls.filter { ["task", "progress", "paper", "questions", "draft"].contains($0.name) }
|
||||||
|
#expect(finalReads == initialReads)
|
||||||
|
#expect(navigation.topViewController === controller)
|
||||||
|
await gate.release()
|
||||||
|
#expect(await model.flushDraft(service: source))
|
||||||
|
#expect(!model.isSaving && !model.hasUnsavedChanges && model.currentSelectedIDs == ["B"])
|
||||||
|
}
|
||||||
|
|
||||||
private nonisolated static func questions(total: Int, offset: Int, limit: Int) -> TrainingQuestionPage {
|
private nonisolated static func questions(total: Int, offset: Int, limit: Int) -> TrainingQuestionPage {
|
||||||
let end = min(total, offset + limit)
|
let end = min(total, offset + limit)
|
||||||
let items: [TrainingQuestionItem] = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : []
|
let items: [TrainingQuestionItem] = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : []
|
||||||
@@ -300,9 +359,7 @@ struct TrainingExamNavigationInteractionTests {
|
|||||||
let window = UIWindow(windowScene: scene)
|
let window = UIWindow(windowScene: scene)
|
||||||
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||||
window.rootViewController = navigation
|
window.rootViewController = navigation
|
||||||
navigation.beginAppearanceTransition(true, animated: false)
|
|
||||||
window.isHidden = false
|
window.isHidden = false
|
||||||
navigation.endAppearanceTransition()
|
|
||||||
navigation.view.layoutIfNeeded()
|
navigation.view.layoutIfNeeded()
|
||||||
return window
|
return window
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,20 +3,20 @@ import Testing
|
|||||||
import UIKit
|
import UIKit
|
||||||
@testable import suixinkan
|
@testable import suixinkan
|
||||||
|
|
||||||
/// 明确挂起保存响应,使测试可检查请求发出前后以及确认前的界面状态。
|
/// 明确挂起首批保存响应,后续批次只能在原确认后发送。
|
||||||
private actor TrainingSelectionSaveGate {
|
private actor TrainingSelectionSaveGate {
|
||||||
private var responses: [CheckedContinuation<Void, Never>] = []
|
private var responses: [CheckedContinuation<Void, Never>] = []
|
||||||
private var released = false
|
private var released = false
|
||||||
private(set) var requestCount = 0
|
private(set) var requestCount = 0
|
||||||
|
|
||||||
/// 保存请求等待测试释放;意外并发请求也独立等待,不覆盖原 continuation。
|
/// 保存请求等待测试释放,意外并发也不会覆盖原 continuation。
|
||||||
func wait() async {
|
func wait() async {
|
||||||
requestCount += 1
|
requestCount += 1
|
||||||
if released { return }
|
if released { return }
|
||||||
await withCheckedContinuation { responses.append($0) }
|
await withCheckedContinuation { responses.append($0) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 完成所有已挂起请求,避免失败断言留下未结束的异步任务。
|
/// 释放全部已挂起请求,异常退出也不会遗留测试任务。
|
||||||
func release() {
|
func release() {
|
||||||
released = true
|
released = true
|
||||||
let pending = responses
|
let pending = responses
|
||||||
@@ -25,11 +25,11 @@ private actor TrainingSelectionSaveGate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 首次保存丢失响应,重试确认同一请求的草稿版本。
|
/// 首批保存丢失响应,后续确认用于检查同键恢复与较新本地选择的串行提交。
|
||||||
private actor TrainingSelectionTimeoutResponse {
|
private actor TrainingSelectionTimeoutResponse {
|
||||||
private var count = 0
|
private var count = 0
|
||||||
|
|
||||||
/// 不依赖固定延时,第一次失败、第二次确认原增量负载。
|
/// 首次失败,其后每次只确认调用方传入的冻结版本。
|
||||||
func confirm(_ request: TrainingDraftSaveRequest) throws -> TrainingDraftConfirmation {
|
func confirm(_ request: TrainingDraftSaveRequest) throws -> TrainingDraftConfirmation {
|
||||||
count += 1
|
count += 1
|
||||||
if count == 1 { throw URLError(.timedOut) }
|
if count == 1 { throw URLError(.timedOut) }
|
||||||
@@ -38,14 +38,14 @@ private actor TrainingSelectionTimeoutResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 捕获实际 AppButton 外观,覆盖主按钮置灰和次按钮 alpha 降低两种退化。
|
/// 捕获实际按钮外观,避免保存时重新出现置灰或透明度变化。
|
||||||
private struct TrainingSelectionButtonAppearance: Equatable {
|
private struct TrainingSelectionButtonAppearance: Equatable {
|
||||||
let isEnabled: Bool
|
let isEnabled: Bool
|
||||||
let alpha: CGFloat
|
let alpha: CGFloat
|
||||||
let backgroundColor: UIColor?
|
let backgroundColor: UIColor?
|
||||||
let normalTitleColor: UIColor?
|
let normalTitleColor: UIColor?
|
||||||
|
|
||||||
/// 从当前按钮读取外观,避免只断言业务状态而漏掉闪烁。
|
/// 同步读取 UIKit 外观,独立于业务 ViewModel 状态。
|
||||||
@MainActor
|
@MainActor
|
||||||
init(_ button: UIButton) {
|
init(_ button: UIButton) {
|
||||||
isEnabled = button.isEnabled
|
isEnabled = button.isEnabled
|
||||||
@@ -55,14 +55,42 @@ private struct TrainingSelectionButtonAppearance: Equatable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 真机 UIKit 答题交互:保存期间外观稳定,确认与失败均使用服务端权威答案。
|
/// 在真实 keyWindow 检查全局遮罩,结束后恢复原应用窗口。
|
||||||
|
@MainActor
|
||||||
|
private final class TrainingSelectionWindowScope {
|
||||||
|
let window: UIWindow
|
||||||
|
private weak var previousKeyWindow: UIWindow?
|
||||||
|
|
||||||
|
/// 由 UIKit 自己发送 appearance 生命周期,不手动重复调用。
|
||||||
|
init(_ navigation: UINavigationController) throws {
|
||||||
|
let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
|
||||||
|
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
|
||||||
|
window = UIWindow(windowScene: scene)
|
||||||
|
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||||
|
window.rootViewController = navigation
|
||||||
|
window.makeKeyAndVisible()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清理本例窗口并恢复先前的 keyWindow。
|
||||||
|
func close() {
|
||||||
|
window.isHidden = true
|
||||||
|
window.rootViewController = nil
|
||||||
|
previousKeyWindow?.makeKey()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本地即时选择与串行后台保存的真实 UIKit 回归,不操作真实学员数据。
|
||||||
@Suite("培训答题选项保存交互", .serialized)
|
@Suite("培训答题选项保存交互", .serialized)
|
||||||
@MainActor
|
@MainActor
|
||||||
struct TrainingExamSelectionInteractionTests {
|
struct TrainingExamSelectionInteractionTests {
|
||||||
private let context = TrainingContext(accountScope: "exam_selection", scenicID: 10, storeID: 3)
|
private let context = TrainingContext(accountScope: "exam_selection", scenicID: 10, storeID: 3)
|
||||||
|
|
||||||
@Test("选项即时高亮,保存期间其它控件不置灰且连续操作只写入一次", arguments: [TrainingQuestionType.single, .multiple])
|
@Test("后台保存不显示遮罩,在途连续改选保持即时高亮且按确认版本串行写入", arguments: [TrainingQuestionType.single, .multiple])
|
||||||
func selectionKeepsAppearanceAndSerializesActions(type: TrainingQuestionType) async throws {
|
func selectionRemainsInteractiveDuringBackgroundSave(type: TrainingQuestionType) async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
let domain = try makeDefaults()
|
let domain = try makeDefaults()
|
||||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
let gate = TrainingSelectionSaveGate()
|
let gate = TrainingSelectionSaveGate()
|
||||||
@@ -78,80 +106,78 @@ struct TrainingExamSelectionInteractionTests {
|
|||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
let navigation = UINavigationController(rootViewController: controller)
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
let window = try makeWindow(navigation)
|
let scope = try TrainingSelectionWindowScope(navigation)
|
||||||
defer { window.isHidden = true }
|
defer { scope.close() }
|
||||||
try await waitUntil { model.canEdit && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
let optionA = try #require(button("training.option.A", in: controller.view))
|
let optionA = try #require(button("training.option.A", in: controller.view))
|
||||||
let optionB = try #require(button("training.option.B", in: controller.view))
|
let optionB = try #require(button("training.option.B", in: controller.view))
|
||||||
let previous = try #require(button("training.exam.previous", in: controller.view))
|
let controls = try ["training.exam.previous", "training.exam.next", "training.exam.submit"].map {
|
||||||
let next = try #require(button("training.exam.next", in: controller.view))
|
try #require(button($0, in: controller.view))
|
||||||
let submit = try #require(button("training.exam.submit", in: controller.view))
|
}
|
||||||
let answerCard = try #require(controller.navigationItem.rightBarButtonItem)
|
|
||||||
let controls = [previous, next, submit]
|
|
||||||
let appearances = controls.map { TrainingSelectionButtonAppearance($0) }
|
let appearances = controls.map { TrainingSelectionButtonAppearance($0) }
|
||||||
let answerCardWasEnabled = answerCard.isEnabled
|
let firstSelection: Set<String> = type == .single ? ["A"] : ["A", "B"]
|
||||||
let callsBefore = await source.calls
|
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
||||||
let expectedSelection: Set<String> = type == .single ? ["A"] : ["A", "B"]
|
|
||||||
#expect(model.currentIndex == 1)
|
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
|
||||||
#expect(previous.isEnabled && next.isEnabled && submit.isEnabled && answerCardWasEnabled)
|
|
||||||
|
|
||||||
optionA.sendActions(for: .touchUpInside)
|
optionA.sendActions(for: .touchUpInside)
|
||||||
// 不让出 main actor:确认网络 Task 启动前已经高亮并锁住所有动作入口。
|
// 不让出主 actor:选择与落盘先完成,网络防抖不能延迟高亮。
|
||||||
|
#expect(model.currentSelectedIDs == firstSelection)
|
||||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
#expect(optionA.accessibilityTraits.contains(.selected))
|
||||||
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
||||||
#expect(optionA.configuration?.baseBackgroundColor == AppColor.primaryLight)
|
#expect(!manager.isShowing)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.canEdit && !model.isBusy)
|
||||||
|
#expect(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
||||||
|
try await waitUntil { await gate.requestCount == 1 }
|
||||||
|
#expect(model.isSaving && model.hasUnsavedChanges && model.canEdit && !model.isBusy)
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
#expect(!scope.window.subviews.contains { $0 is GlobalLoadingOverlayView && !$0.isHidden })
|
||||||
|
|
||||||
|
optionB.sendActions(for: .touchUpInside)
|
||||||
|
#expect(model.currentSelectedIDs == (type == .single ? ["B"] : ["A"]))
|
||||||
|
optionA.sendActions(for: .touchUpInside)
|
||||||
|
#expect(model.currentSelectedIDs == (type == .single ? ["A"] : []))
|
||||||
|
if type == .multiple { #expect(model.answeredCount == 2) }
|
||||||
optionB.sendActions(for: .touchUpInside)
|
optionB.sendActions(for: .touchUpInside)
|
||||||
next.sendActions(for: .touchUpInside)
|
|
||||||
submit.sendActions(for: .touchUpInside)
|
|
||||||
if let action = answerCard.action {
|
|
||||||
UIApplication.shared.sendAction(action, to: answerCard.target, from: answerCard, for: nil)
|
|
||||||
}
|
|
||||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
|
||||||
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
|
||||||
#expect(controller.presentedViewController == nil)
|
|
||||||
#expect(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
|
||||||
#expect(answerCard.isEnabled == answerCardWasEnabled)
|
|
||||||
|
|
||||||
try await waitUntil { await gate.requestCount > 0 }
|
|
||||||
#expect(model.isBusy)
|
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.currentSelectedIDs == ["B"])
|
||||||
#expect(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
#expect(!optionA.accessibilityTraits.contains(.selected) && optionB.accessibilityTraits.contains(.selected))
|
||||||
#expect(answerCard.isEnabled == answerCardWasEnabled)
|
#expect(optionA.isEnabled && optionB.isEnabled && optionA.isUserInteractionEnabled && optionB.isUserInteractionEnabled)
|
||||||
#expect(!optionA.isUserInteractionEnabled && !optionB.isUserInteractionEnabled)
|
|
||||||
#expect(controls.allSatisfy { !$0.isUserInteractionEnabled })
|
|
||||||
#expect(allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == "正在保存答案…" })
|
|
||||||
#expect(button("training.option.A", in: controller.view) === optionA)
|
|
||||||
#expect(button("training.option.B", in: controller.view) === optionB)
|
|
||||||
let pendingRequests = await source.savedRequests
|
|
||||||
#expect(pendingRequests.count == 1)
|
|
||||||
#expect(pendingRequests.first?.baseRevision == 5)
|
|
||||||
#expect(pendingRequests.first?.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: expectedSelection.sorted())])
|
|
||||||
#expect(await source.submissionRequests.isEmpty)
|
|
||||||
let callsDuringSave = await source.calls
|
|
||||||
#expect(callsDuringSave.filter { $0.name == "questions" || $0.name == "draft" } == callsBefore.filter { $0.name == "questions" || $0.name == "draft" })
|
|
||||||
#expect(navigation.topViewController === controller)
|
|
||||||
#expect(model.currentIndex == 1)
|
|
||||||
|
|
||||||
await gate.release()
|
|
||||||
try await waitUntil { model.canEdit && model.currentSelectedIDs == expectedSelection && optionA.isUserInteractionEnabled }
|
|
||||||
#expect(model.draftRevision == 6)
|
|
||||||
#expect(model.answeredCount == 3)
|
|
||||||
#expect(model.errorMessage == nil)
|
|
||||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
|
||||||
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
|
||||||
#expect(button("training.option.A", in: controller.view) === optionA)
|
|
||||||
#expect(button("training.option.B", in: controller.view) === optionB)
|
|
||||||
#expect(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
#expect(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
||||||
#expect(controls.allSatisfy { $0.isUserInteractionEnabled })
|
#expect(controls.allSatisfy { $0.isUserInteractionEnabled })
|
||||||
|
#expect(controller.navigationItem.rightBarButtonItem?.isEnabled == true)
|
||||||
|
#expect(button("training.option.A", in: controller.view) === optionA)
|
||||||
|
#expect(button("training.option.B", in: controller.view) === optionB)
|
||||||
#expect(await source.savedRequests.count == 1)
|
#expect(await source.savedRequests.count == 1)
|
||||||
#expect(navigation.topViewController === controller)
|
let firstRequests = await source.savedRequests
|
||||||
#expect(controller.presentedViewController == nil)
|
let first = try #require(firstRequests.first)
|
||||||
|
#expect(first.baseRevision == 5)
|
||||||
|
#expect(first.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: firstSelection.sorted())])
|
||||||
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
|
#expect(allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text?.contains("保存") == true })
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
let screenshot = UIGraphicsImageRenderer(size: navigation.view.bounds.size).image { output in
|
||||||
|
navigation.view.layer.render(in: output.cgContext)
|
||||||
|
}
|
||||||
|
Attachment.record(screenshot, named: "后台保存中仍可改选-\(type == .single ? "单选" : "多选")", as: .png)
|
||||||
|
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !model.hasUnsavedChanges && !model.isSaving && model.currentSelectedIDs == ["B"] }
|
||||||
|
#expect(model.draftRevision == 7 && model.answeredCount == 3)
|
||||||
|
#expect(model.canEdit && model.errorMessage == nil)
|
||||||
|
let requests = await source.savedRequests
|
||||||
|
#expect(requests.count == 2)
|
||||||
|
#expect(requests.last?.baseRevision == 6)
|
||||||
|
#expect(requests.last?.requestID != first.requestID)
|
||||||
|
#expect(requests.last?.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["B"])])
|
||||||
|
#expect(button("training.option.A", in: controller.view) === optionA)
|
||||||
|
#expect(button("training.option.B", in: controller.view) === optionB)
|
||||||
|
#expect(!optionA.accessibilityTraits.contains(.selected) && optionB.accessibilityTraits.contains(.selected))
|
||||||
|
#expect(!manager.isShowing && navigation.topViewController === controller)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("保存超时恢复已确认选项并提供重试,禁止新选择更换原请求")
|
@Test("超时保留本地选择,继续改选不替换原键,重试后再保存较新答案")
|
||||||
func timeoutRestoresConfirmedAnswerAndRetriesIdenticalPayload() async throws {
|
func timeoutKeepsDesiredAnswerAndRetriesFrozenPayloadBeforeLatestSelection() async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
let domain = try makeDefaults()
|
let domain = try makeDefaults()
|
||||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
let response = TrainingSelectionTimeoutResponse()
|
let response = TrainingSelectionTimeoutResponse()
|
||||||
@@ -162,44 +188,39 @@ struct TrainingExamSelectionInteractionTests {
|
|||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
let navigation = UINavigationController(rootViewController: controller)
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
let window = try makeWindow(navigation)
|
let scope = try TrainingSelectionWindowScope(navigation)
|
||||||
defer { window.isHidden = true }
|
defer { scope.close() }
|
||||||
try await waitUntil { model.canEdit && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
let optionA = try #require(button("training.option.A", in: controller.view))
|
let optionA = try #require(button("training.option.A", in: controller.view))
|
||||||
let optionB = try #require(button("training.option.B", in: controller.view))
|
let optionB = try #require(button("training.option.B", in: controller.view))
|
||||||
optionA.sendActions(for: .touchUpInside)
|
optionA.sendActions(for: .touchUpInside)
|
||||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
try await waitUntil { model.hasPendingMutation && model.errorMessage != nil && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "重试保存" }
|
||||||
try await waitUntil { model.hasPendingMutation && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "重试保存" }
|
#expect(model.canEdit && model.currentSelectedIDs == ["A"])
|
||||||
let retry = try #require(button("training.exam.submit", in: controller.view))
|
#expect(optionA.accessibilityTraits.contains(.selected) && !optionB.accessibilityTraits.contains(.selected))
|
||||||
#expect(retry.isEnabled && retry.isUserInteractionEnabled)
|
#expect(!manager.isShowing && model.draftRevision == 5)
|
||||||
#expect(!model.canEdit)
|
let originals = await source.savedRequests
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
let original = try #require(originals.first)
|
||||||
#expect(!optionA.accessibilityTraits.contains(.selected))
|
|
||||||
#expect(optionB.accessibilityTraits.contains(.selected))
|
|
||||||
#expect(!optionA.isEnabled && !optionB.isEnabled)
|
|
||||||
#expect(model.draftRevision == 5)
|
|
||||||
let error = try #require(model.errorMessage)
|
|
||||||
#expect(allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == error })
|
|
||||||
let originalRequests = await source.savedRequests
|
|
||||||
let original = try #require(originalRequests.first)
|
|
||||||
#expect(originalRequests.count == 1)
|
|
||||||
#expect(original.baseRevision == 5)
|
#expect(original.baseRevision == 5)
|
||||||
#expect(original.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["A"])])
|
#expect(original.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["A"])])
|
||||||
optionB.sendActions(for: .touchUpInside)
|
optionB.sendActions(for: .touchUpInside)
|
||||||
|
#expect(model.currentSelectedIDs == ["B"] && optionB.accessibilityTraits.contains(.selected))
|
||||||
|
// 覆盖完整防抖窗口,确认失败的冻结请求没有被新选择偷偷换键重发。
|
||||||
|
try await Task.sleep(for: .milliseconds(350))
|
||||||
#expect(await source.savedRequests.count == 1)
|
#expect(await source.savedRequests.count == 1)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.hasPendingMutation && !manager.isShowing)
|
||||||
|
let retry = try #require(button("training.exam.submit", in: controller.view))
|
||||||
|
#expect(retry.isEnabled && retry.isUserInteractionEnabled)
|
||||||
retry.sendActions(for: .touchUpInside)
|
retry.sendActions(for: .touchUpInside)
|
||||||
try await waitUntil { model.canEdit && model.currentSelectedIDs == ["A"] && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "交卷" }
|
try await waitUntil { model.canEdit && !model.hasPendingMutation && !model.hasUnsavedChanges && model.currentSelectedIDs == ["B"] }
|
||||||
let retriedRequests = await source.savedRequests
|
let requests = await source.savedRequests
|
||||||
#expect(retriedRequests.count == 2)
|
#expect(requests.count == 3)
|
||||||
#expect(retriedRequests.last == original)
|
#expect(requests[1] == original)
|
||||||
#expect(model.draftRevision == 6)
|
#expect(requests[2].baseRevision == 6 && requests[2].requestID != original.requestID)
|
||||||
#expect(!model.hasPendingMutation)
|
#expect(requests[2].changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["B"])])
|
||||||
#expect(model.errorMessage == nil)
|
#expect(model.draftRevision == 7 && model.errorMessage == nil)
|
||||||
#expect(button("training.option.A", in: controller.view) === optionA)
|
#expect(button("training.option.A", in: controller.view) === optionA)
|
||||||
#expect(button("training.option.B", in: controller.view) === optionB)
|
#expect(button("training.option.B", in: controller.view) === optionB)
|
||||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
#expect(!optionA.accessibilityTraits.contains(.selected) && optionB.accessibilityTraits.contains(.selected))
|
||||||
#expect(!optionB.accessibilityTraits.contains(.selected))
|
|
||||||
#expect(navigation.topViewController === controller)
|
#expect(navigation.topViewController === controller)
|
||||||
#expect(await source.submissionRequests.isEmpty)
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
}
|
}
|
||||||
@@ -231,18 +252,6 @@ struct TrainingExamSelectionInteractionTests {
|
|||||||
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { scope })
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { scope })
|
||||||
}
|
}
|
||||||
|
|
||||||
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 allViews(_ view: UIView) -> [UIView] {
|
private func allViews(_ view: UIView) -> [UIView] {
|
||||||
[view] + view.subviews.flatMap { allViews($0) }
|
[view] + view.subviews.flatMap { allViews($0) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ struct TrainingRemoteExamTests {
|
|||||||
private func makeModel(defaults: UserDefaults, identity: TrainingExamTestIdentity? = nil) -> TrainingRemoteExamViewModel {
|
private func makeModel(defaults: UserDefaults, identity: TrainingExamTestIdentity? = nil) -> TrainingRemoteExamViewModel {
|
||||||
let scope = identity?.context ?? context
|
let scope = identity?.context ?? context
|
||||||
return TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
return TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
||||||
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { if let identity { return identity.context }; return scope })
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), debounceNanoseconds: 60_000_000_000, currentContext: { if let identity { return identity.context }; return scope })
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("500题恢复和随机跳题只下载所在页,已答状态来自全局题号")
|
@Test("500题恢复和随机跳题只下载所在页,已答状态来自全局题号")
|
||||||
@@ -145,9 +145,11 @@ struct TrainingRemoteExamTests {
|
|||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
await model.load(service: source)
|
await model.load(service: source)
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(model.draftRevision == 2)
|
#expect(model.draftRevision == 2)
|
||||||
#expect(model.answeredQuestionOrders == [1])
|
#expect(model.answeredQuestionOrders == [1])
|
||||||
await model.select(optionID: "B", service: source)
|
await model.select(optionID: "B", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
let requests = await source.savedRequests
|
let requests = await source.savedRequests
|
||||||
#expect(requests.map(\.baseRevision) == [1, 2])
|
#expect(requests.map(\.baseRevision) == [1, 2])
|
||||||
#expect(requests.allSatisfy { $0.changes.count == 1 && $0.changes.first?.questionID == "q1" })
|
#expect(requests.allSatisfy { $0.changes.count == 1 && $0.changes.first?.questionID == "q1" })
|
||||||
@@ -176,14 +178,17 @@ struct TrainingRemoteExamTests {
|
|||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
await model.load(service: source)
|
await model.load(service: source)
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
await model.select(optionID: "B", service: source)
|
await model.select(optionID: "B", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.currentSelectedIDs == ["B"])
|
||||||
#expect((await source.savedRequests).map { $0.changes.first?.selectedOptionIDs } == [["A"], ["A", "B"], ["B"]])
|
#expect((await source.savedRequests).map { $0.changes.first?.selectedOptionIDs } == [["A"], ["A", "B"], ["B"]])
|
||||||
#expect(model.answeredCount == 1)
|
#expect(model.answeredCount == 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("保存超时暂停编辑,重试同ID同版本同内容")
|
@Test("保存超时保留本机选择,重试原请求后再保存较新的改选")
|
||||||
func saveFailureRetainsOriginalRequest() async throws {
|
func saveFailureRetainsOriginalRequest() async throws {
|
||||||
let domain = try makeDefaults()
|
let domain = try makeDefaults()
|
||||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
@@ -197,20 +202,24 @@ struct TrainingRemoteExamTests {
|
|||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
await model.load(service: source)
|
await model.load(service: source)
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(model.hasPendingMutation)
|
#expect(model.hasPendingMutation)
|
||||||
#expect(!model.canEdit)
|
#expect(model.canEdit)
|
||||||
#expect(model.currentSelectedIDs.isEmpty)
|
#expect(model.currentSelectedIDs == ["A"])
|
||||||
await model.select(optionID: "B", service: source)
|
await model.select(optionID: "B", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(await source.savedRequests.count == 1)
|
#expect(await source.savedRequests.count == 1)
|
||||||
await model.retryMutation(service: source)
|
await model.retryMutation(service: source)
|
||||||
let requests = await source.savedRequests
|
let requests = await source.savedRequests
|
||||||
#expect(requests.count == 2)
|
#expect(requests.count == 3)
|
||||||
#expect(requests[0] == requests[1])
|
#expect(requests[0] == requests[1])
|
||||||
#expect(model.currentSelectedIDs == ["A"])
|
#expect(requests[2].baseRevision == requests[1].baseRevision + 1)
|
||||||
|
#expect(requests[2].changes.first?.selectedOptionIDs == ["B"])
|
||||||
|
#expect(model.currentSelectedIDs == ["B"])
|
||||||
#expect(!model.hasPendingMutation)
|
#expect(!model.hasPendingMutation)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("版本冲突读取最新元信息与当前页,不覆盖其它设备的新答案")
|
@Test("版本冲突读取权威草稿并保留本机意图,明确确认前不覆盖其他设备")
|
||||||
func conflictRefreshesCurrentPage() async throws {
|
func conflictRefreshesCurrentPage() async throws {
|
||||||
let domain = try makeDefaults()
|
let domain = try makeDefaults()
|
||||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
@@ -219,11 +228,13 @@ struct TrainingRemoteExamTests {
|
|||||||
await model.load(service: source)
|
await model.load(service: source)
|
||||||
await source.seedDraft(revision: 8, answers: ["q1": ["B"], "q10": ["A"]])
|
await source.seedDraft(revision: 8, answers: ["q1": ["B"], "q10": ["A"]])
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(model.draftRevision == 8)
|
#expect(model.draftRevision == 8)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.currentSelectedIDs == ["A"])
|
||||||
#expect(model.answeredCount == 2)
|
#expect(model.answeredCount == 2)
|
||||||
#expect(model.errorMessage != nil)
|
#expect(model.errorMessage != nil)
|
||||||
#expect(!model.hasPendingMutation)
|
#expect(model.hasPendingMutation)
|
||||||
|
#expect(model.hasDraftConflict)
|
||||||
#expect(await source.savedRequests.count == 1)
|
#expect(await source.savedRequests.count == 1)
|
||||||
let calls = await source.calls
|
let calls = await source.calls
|
||||||
#expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 0, 10])
|
#expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 0, 10])
|
||||||
@@ -435,11 +446,13 @@ struct TrainingRemoteExamTests {
|
|||||||
#expect(!model.canEdit)
|
#expect(!model.canEdit)
|
||||||
#expect(model.canRetryCurrentPage)
|
#expect(model.canRetryCurrentPage)
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(await source.savedRequests.isEmpty)
|
#expect(await source.savedRequests.isEmpty)
|
||||||
await model.retryCurrentPage(service: source)
|
await model.retryCurrentPage(service: source)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.currentSelectedIDs == ["B"])
|
||||||
#expect(model.canEdit)
|
#expect(model.canEdit)
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect((await source.savedRequests).last?.changes.first?.selectedOptionIDs == ["A", "B"])
|
#expect((await source.savedRequests).last?.changes.first?.selectedOptionIDs == ["A", "B"])
|
||||||
await model.goToQuestion(0, service: source)
|
await model.goToQuestion(0, service: source)
|
||||||
#expect(model.currentSelectedIDs == ["A"])
|
#expect(model.currentSelectedIDs == ["A"])
|
||||||
@@ -462,11 +475,13 @@ struct TrainingRemoteExamTests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
await model.select(optionID: "A", service: source)
|
await model.select(optionID: "A", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
#expect(!model.canEdit)
|
#expect(!model.canEdit)
|
||||||
#expect(model.canRetryCurrentPage)
|
#expect(model.canRetryCurrentPage)
|
||||||
#expect(!model.hasPendingMutation)
|
#expect(model.hasPendingMutation)
|
||||||
await model.retryCurrentPage(service: source)
|
await model.retryCurrentPage(service: source)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.currentSelectedIDs == ["A"])
|
||||||
|
#expect(model.hasDraftConflict)
|
||||||
#expect(model.draftRevision == 8)
|
#expect(model.draftRevision == 8)
|
||||||
#expect(model.canEdit)
|
#expect(model.canEdit)
|
||||||
#expect(await source.savedRequests.count == 1)
|
#expect(await source.savedRequests.count == 1)
|
||||||
@@ -578,6 +593,7 @@ struct TrainingRemoteExamTests {
|
|||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
await model.load(service: source, resetDraft: true)
|
await model.load(service: source, resetDraft: true)
|
||||||
await model.select(optionID: "B", service: source)
|
await model.select(optionID: "B", service: source)
|
||||||
|
_ = await model.flushDraft(service: source)
|
||||||
await model.load(service: source, resetDraft: true)
|
await model.load(service: source, resetDraft: true)
|
||||||
#expect(await source.resetRequests.count == 1)
|
#expect(await source.resetRequests.count == 1)
|
||||||
#expect(model.currentSelectedIDs == ["B"])
|
#expect(model.currentSelectedIDs == ["B"])
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import Testing
|
|||||||
import UIKit
|
import UIKit
|
||||||
@testable import suixinkan
|
@testable import suixinkan
|
||||||
|
|
||||||
/// 选项保存与跨页题目请求,分别验证成功和失败后的 Loading 释放。
|
/// 选项后台保存不展示 Loading,未缓存题页请求仍持有前台 Loading。
|
||||||
enum TrainingLoadingExamScenario: String, CaseIterable, Sendable {
|
enum TrainingLoadingExamScenario: String, CaseIterable, Sendable {
|
||||||
case selectionSuccess, selectionFailure, nextSuccess, nextFailure
|
case selectionSuccess, selectionFailure, nextSuccess, nextFailure
|
||||||
var selectsAnswer: Bool { self == .selectionSuccess || self == .selectionFailure }
|
var selectsAnswer: Bool { self == .selectionSuccess || self == .selectionFailure }
|
||||||
@@ -37,6 +37,20 @@ private actor TrainingLoadingRequestGate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 初次恢复失败后挂起下一次精确查询,测试公开的恢复交卷按钮。
|
||||||
|
private actor TrainingLoadingSubmissionRecovery {
|
||||||
|
private var count = 0
|
||||||
|
|
||||||
|
/// 初次抛出网络错误,让页面显示恢复按钮;随后只返回原提交的一条成绩。
|
||||||
|
func recover(gate: TrainingLoadingRequestGate) async throws -> TrainingCursorPage<TrainingAttemptSummary> {
|
||||||
|
count += 1
|
||||||
|
if count == 1 { throw URLError(.timedOut) }
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt()], nextCursor: nil,
|
||||||
|
hasMore: false, serverTime: TrainingRemoteFixtures.now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 将全局 Loading 放进本例独立的真实 keyWindow,关闭后恢复原 keyWindow。
|
/// 将全局 Loading 放进本例独立的真实 keyWindow,关闭后恢复原 keyWindow。
|
||||||
@MainActor
|
@MainActor
|
||||||
private final class TrainingLoadingWindowScope {
|
private final class TrainingLoadingWindowScope {
|
||||||
@@ -68,7 +82,7 @@ private final class TrainingLoadingWindowScope {
|
|||||||
struct TrainingRequestLoadingTests {
|
struct TrainingRequestLoadingTests {
|
||||||
private let context = TrainingContext(accountScope: "training_loading", scenicID: 10, storeID: 3)
|
private let context = TrainingContext(accountScope: "training_loading", scenicID: 10, storeID: 3)
|
||||||
|
|
||||||
@Test("选项和翻题点击同步展示 App Loading,成功或失败均关闭", arguments: TrainingLoadingExamScenario.allCases)
|
@Test("选项保存不显示 Loading,未缓存翻题同步显示且成功失败均关闭", arguments: TrainingLoadingExamScenario.allCases)
|
||||||
func examRequestsOwnLoadingUntilResponse(scenario: TrainingLoadingExamScenario) async throws {
|
func examRequestsOwnLoadingUntilResponse(scenario: TrainingLoadingExamScenario) async throws {
|
||||||
let manager = GlobalLoadingManager.shared
|
let manager = GlobalLoadingManager.shared
|
||||||
manager.hideAll()
|
manager.hideAll()
|
||||||
@@ -107,18 +121,19 @@ struct TrainingRequestLoadingTests {
|
|||||||
#expect(!hasVisibleOverlay(in: scope.window))
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
let action = try #require(button(scenario.selectsAnswer ? "training.option.B" : "training.exam.next", in: controller.view))
|
let action = try #require(button(scenario.selectsAnswer ? "training.option.B" : "training.exam.next", in: controller.view))
|
||||||
action.sendActions(for: .touchUpInside)
|
action.sendActions(for: .touchUpInside)
|
||||||
// 不让出主 actor,要求点击处理当场持有 Loading,而非等网络 Task 启动。
|
// 未缓存翻题当场持有 Loading;本地选择在防抖和后台保存期间均不阻塞页面。
|
||||||
#expect(manager.isShowing)
|
#expect(manager.isShowing == !scenario.selectsAnswer)
|
||||||
#expect(hasVisibleOverlay(in: scope.window))
|
#expect(hasVisibleOverlay(in: scope.window) == !scenario.selectsAnswer)
|
||||||
action.sendActions(for: .touchUpInside)
|
action.sendActions(for: .touchUpInside)
|
||||||
try await waitUntil { await gate.requestCount > 0 }
|
try await waitUntil { await gate.requestCount > 0 }
|
||||||
#expect(model.isBusy)
|
#expect(model.isBusy == !scenario.selectsAnswer)
|
||||||
#expect(manager.isShowing)
|
#expect(model.isSaving == scenario.selectsAnswer)
|
||||||
#expect(hasVisibleOverlay(in: scope.window))
|
#expect(manager.isShowing == !scenario.selectsAnswer)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window) == !scenario.selectsAnswer)
|
||||||
#expect(await gate.requestCount == 1)
|
#expect(await gate.requestCount == 1)
|
||||||
#expect(await source.savedRequests.count == (scenario.selectsAnswer ? 1 : 0))
|
#expect(await source.savedRequests.count == (scenario.selectsAnswer ? 1 : 0))
|
||||||
await gate.release()
|
await gate.release()
|
||||||
try await waitUntil { !model.isBusy && !manager.isShowing && (scenario.fails ? model.errorMessage != nil : model.canEdit) }
|
try await waitUntil { !model.isBusy && !model.isSaving && !manager.isShowing && (scenario.fails ? model.errorMessage != nil : model.canEdit) }
|
||||||
#expect(!hasVisibleOverlay(in: scope.window))
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
#expect(navigation.topViewController === controller)
|
#expect(navigation.topViewController === controller)
|
||||||
if scenario.fails {
|
if scenario.fails {
|
||||||
@@ -130,6 +145,7 @@ struct TrainingRequestLoadingTests {
|
|||||||
#expect(model.currentIndex == (scenario.selectsAnswer ? 9 : 10))
|
#expect(model.currentIndex == (scenario.selectsAnswer ? 9 : 10))
|
||||||
#expect(model.currentSelectedIDs == (scenario.selectsAnswer ? ["B"] : ["A"]))
|
#expect(model.currentSelectedIDs == (scenario.selectsAnswer ? ["B"] : ["A"]))
|
||||||
#expect(model.errorMessage == nil)
|
#expect(model.errorMessage == nil)
|
||||||
|
#expect(await model.flushDraft(service: source))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,12 +195,12 @@ struct TrainingRequestLoadingTests {
|
|||||||
let gate = TrainingLoadingRequestGate()
|
let gate = TrainingLoadingRequestGate()
|
||||||
defer { Task { await gate.release() } }
|
defer { Task { await gate.release() } }
|
||||||
var configuration = TrainingDataStub.Configuration()
|
var configuration = TrainingDataStub.Configuration()
|
||||||
configuration.saveHandler = { request in
|
configuration.questionsHandler = { offset, limit in
|
||||||
await gate.wait()
|
if offset == 10 { await gate.wait() }
|
||||||
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
return Self.questions(offset: offset, limit: limit)
|
||||||
savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
|
||||||
}
|
}
|
||||||
let source = TrainingDataStub(configuration: configuration)
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
await source.seedDraft(revision: 5, answers: [:], lastOrder: 10)
|
||||||
let model = makeModel(defaults: domain.defaults)
|
let model = makeModel(defaults: domain.defaults)
|
||||||
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
let navigation = UINavigationController(rootViewController: controller)
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
@@ -192,8 +208,8 @@ struct TrainingRequestLoadingTests {
|
|||||||
defer { scope.close() }
|
defer { scope.close() }
|
||||||
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
try await settleTransitions([navigation, controller])
|
try await settleTransitions([navigation, controller])
|
||||||
let optionA = try #require(button("training.option.A", in: controller.view))
|
let next = try #require(button("training.exam.next", in: controller.view))
|
||||||
optionA.sendActions(for: .touchUpInside)
|
next.sendActions(for: .touchUpInside)
|
||||||
try await waitUntil { await gate.requestCount > 0 }
|
try await waitUntil { await gate.requestCount > 0 }
|
||||||
#expect(manager.isShowing)
|
#expect(manager.isShowing)
|
||||||
let covering = UIViewController()
|
let covering = UIViewController()
|
||||||
@@ -206,13 +222,58 @@ struct TrainingRequestLoadingTests {
|
|||||||
defer { manager.endRequest(newerToken) }
|
defer { manager.endRequest(newerToken) }
|
||||||
#expect(manager.isShowing && hasVisibleOverlay(in: scope.window))
|
#expect(manager.isShowing && hasVisibleOverlay(in: scope.window))
|
||||||
await gate.release()
|
await gate.release()
|
||||||
try await waitUntil { model.canEdit && model.currentSelectedIDs == ["A"] && optionA.isUserInteractionEnabled }
|
try await waitUntil { model.canEdit && model.currentQuestion?.order == 11 && next.isUserInteractionEnabled }
|
||||||
#expect(manager.isShowing)
|
#expect(manager.isShowing)
|
||||||
#expect(hasVisibleOverlay(in: scope.window))
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
#expect(navigation.topViewController === covering)
|
#expect(navigation.topViewController === covering)
|
||||||
manager.endRequest(newerToken)
|
manager.endRequest(newerToken)
|
||||||
#expect(!manager.isShowing)
|
#expect(!manager.isShowing)
|
||||||
#expect(!hasVisibleOverlay(in: scope.window))
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(await model.flushDraft(service: source))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("恢复未知交卷结果继续使用前台 Loading,不新建交卷或重放草稿")
|
||||||
|
func recoveringSubmissionOwnsLoadingAndKeepsOriginalRequest() async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let domain = try makeDefaults()
|
||||||
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
|
let gate = TrainingLoadingRequestGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
let recovery = TrainingLoadingSubmissionRecovery()
|
||||||
|
let store = TrainingPendingSubmissionStore(defaults: domain.defaults)
|
||||||
|
let original = TrainingPendingSubmission(taskID: "task_1",
|
||||||
|
request: TrainingSubmissionRequest(submissionID: "original-unknown-submit", paperSnapshotID: "paper_1", draftRevision: 5), context: context)
|
||||||
|
try store.save(original)
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.attemptsHandler = { _, _, _ in try await recovery.recover(gate: gate) }
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
let model = makeModel(defaults: domain.defaults)
|
||||||
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let scope = try TrainingLoadingWindowScope(navigation)
|
||||||
|
defer { scope.close() }
|
||||||
|
try await waitUntil {
|
||||||
|
model.hasPendingSubmission && !manager.isShowing && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "恢复交卷结果"
|
||||||
|
}
|
||||||
|
let restore = try #require(button("training.exam.submit", in: controller.view))
|
||||||
|
restore.sendActions(for: .touchUpInside)
|
||||||
|
#expect(manager.isShowing && hasVisibleOverlay(in: scope.window))
|
||||||
|
try await waitUntil { await gate.requestCount == 1 }
|
||||||
|
#expect(model.isBusy && manager.isShowing)
|
||||||
|
let stillPending = try store.load(taskID: "task_1", context: context)
|
||||||
|
#expect(stillPending == original)
|
||||||
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { model.submittedAttempt != nil && !model.isBusy && !manager.isShowing }
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
let pendingAfter = try store.load(taskID: "task_1", context: context)
|
||||||
|
#expect(pendingAfter == nil)
|
||||||
|
#expect(await source.submissionRequests.isEmpty)
|
||||||
|
#expect(await source.savedRequests.isEmpty)
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempts" }.count == 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("培训列表下一页和错误重试同步展示 Loading,确认后关闭", arguments: TrainingLoadingCenterScenario.allCases)
|
@Test("培训列表下一页和错误重试同步展示 Loading,确认后关闭", arguments: TrainingLoadingCenterScenario.allCases)
|
||||||
|
|||||||
Reference in New Issue
Block a user