270 lines
14 KiB
Swift
270 lines
14 KiB
Swift
import Foundation
|
|
import Testing
|
|
import UIKit
|
|
@testable import suixinkan
|
|
|
|
/// 明确挂起首批保存响应,后续批次只能在原确认后发送。
|
|
private actor TrainingSelectionSaveGate {
|
|
private var responses: [CheckedContinuation<Void, Never>] = []
|
|
private var released = false
|
|
private(set) var requestCount = 0
|
|
|
|
/// 保存请求等待测试释放,意外并发也不会覆盖原 continuation。
|
|
func wait() async {
|
|
requestCount += 1
|
|
if released { return }
|
|
await withCheckedContinuation { responses.append($0) }
|
|
}
|
|
|
|
/// 释放全部已挂起请求,异常退出也不会遗留测试任务。
|
|
func release() {
|
|
released = true
|
|
let pending = responses
|
|
responses = []
|
|
pending.forEach { $0.resume() }
|
|
}
|
|
}
|
|
|
|
/// 首批保存丢失响应,后续确认用于检查同键恢复与较新本地选择的串行提交。
|
|
private actor TrainingSelectionTimeoutResponse {
|
|
private var count = 0
|
|
|
|
/// 首次失败,其后每次只确认调用方传入的冻结版本。
|
|
func confirm(_ request: TrainingDraftSaveRequest) throws -> TrainingDraftConfirmation {
|
|
count += 1
|
|
if count == 1 { throw URLError(.timedOut) }
|
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 3)
|
|
}
|
|
}
|
|
|
|
/// 捕获实际按钮外观,避免保存时重新出现置灰或透明度变化。
|
|
private struct TrainingSelectionButtonAppearance: Equatable {
|
|
let isEnabled: Bool
|
|
let alpha: CGFloat
|
|
let backgroundColor: UIColor?
|
|
let normalTitleColor: UIColor?
|
|
|
|
/// 同步读取 UIKit 外观,独立于业务 ViewModel 状态。
|
|
@MainActor
|
|
init(_ button: UIButton) {
|
|
isEnabled = button.isEnabled
|
|
alpha = button.alpha
|
|
backgroundColor = button.backgroundColor
|
|
normalTitleColor = button.titleColor(for: .normal)
|
|
}
|
|
}
|
|
|
|
/// 在真实 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)
|
|
@MainActor
|
|
struct TrainingExamSelectionInteractionTests {
|
|
private let context = TrainingContext(accountScope: "exam_selection", scenicID: 10, storeID: 3)
|
|
|
|
@Test("后台保存不显示遮罩,在途连续改选保持即时高亮且按确认版本串行写入", arguments: [TrainingQuestionType.single, .multiple])
|
|
func selectionRemainsInteractiveDuringBackgroundSave(type: TrainingQuestionType) async throws {
|
|
let manager = GlobalLoadingManager.shared
|
|
manager.hideAll()
|
|
defer { manager.hideAll() }
|
|
let domain = try makeDefaults()
|
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
|
let gate = TrainingSelectionSaveGate()
|
|
defer { Task { await gate.release() } }
|
|
var configuration = makeConfiguration(type: type)
|
|
configuration.saveHandler = { request in
|
|
await gate.wait()
|
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 3)
|
|
}
|
|
let source = TrainingDataStub(configuration: configuration)
|
|
await source.seedDraft(revision: 5, answers: ["q1": ["A"], "q2": ["B"], "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 scope = try TrainingSelectionWindowScope(navigation)
|
|
defer { scope.close() }
|
|
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 optionB = try #require(button("training.option.B", in: controller.view))
|
|
let controls = try ["training.exam.previous", "training.exam.next", "training.exam.submit"].map {
|
|
try #require(button($0, in: controller.view))
|
|
}
|
|
let appearances = controls.map { TrainingSelectionButtonAppearance($0) }
|
|
let firstSelection: Set<String> = type == .single ? ["A"] : ["A", "B"]
|
|
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
|
|
|
optionA.sendActions(for: .touchUpInside)
|
|
// 不让出主 actor:选择与落盘先完成,网络防抖不能延迟高亮。
|
|
#expect(model.currentSelectedIDs == firstSelection)
|
|
#expect(optionA.accessibilityTraits.contains(.selected))
|
|
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
|
#expect(!manager.isShowing)
|
|
#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)
|
|
#expect(model.currentSelectedIDs == ["B"])
|
|
#expect(!optionA.accessibilityTraits.contains(.selected) && optionB.accessibilityTraits.contains(.selected))
|
|
#expect(optionA.isEnabled && optionB.isEnabled && optionA.isUserInteractionEnabled && optionB.isUserInteractionEnabled)
|
|
#expect(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
|
#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)
|
|
let firstRequests = await source.savedRequests
|
|
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("超时保留本地选择,继续改选不替换原键,重试后再保存较新答案")
|
|
func timeoutKeepsDesiredAnswerAndRetriesFrozenPayloadBeforeLatestSelection() async throws {
|
|
let manager = GlobalLoadingManager.shared
|
|
manager.hideAll()
|
|
defer { manager.hideAll() }
|
|
let domain = try makeDefaults()
|
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
|
let response = TrainingSelectionTimeoutResponse()
|
|
var configuration = makeConfiguration(type: .single)
|
|
configuration.saveHandler = { request in try await response.confirm(request) }
|
|
let source = TrainingDataStub(configuration: configuration)
|
|
await source.seedDraft(revision: 5, answers: ["q1": ["A"], "q2": ["B"], "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 scope = try TrainingSelectionWindowScope(navigation)
|
|
defer { scope.close() }
|
|
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 optionB = try #require(button("training.option.B", in: controller.view))
|
|
optionA.sendActions(for: .touchUpInside)
|
|
try await waitUntil { model.hasPendingMutation && model.errorMessage != nil && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "重试保存" }
|
|
#expect(model.canEdit && model.currentSelectedIDs == ["A"])
|
|
#expect(optionA.accessibilityTraits.contains(.selected) && !optionB.accessibilityTraits.contains(.selected))
|
|
#expect(!manager.isShowing && model.draftRevision == 5)
|
|
let originals = await source.savedRequests
|
|
let original = try #require(originals.first)
|
|
#expect(original.baseRevision == 5)
|
|
#expect(original.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["A"])])
|
|
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(model.hasPendingMutation && !manager.isShowing)
|
|
let retry = try #require(button("training.exam.submit", in: controller.view))
|
|
#expect(retry.isEnabled && retry.isUserInteractionEnabled)
|
|
retry.sendActions(for: .touchUpInside)
|
|
try await waitUntil { model.canEdit && !model.hasPendingMutation && !model.hasUnsavedChanges && model.currentSelectedIDs == ["B"] }
|
|
let requests = await source.savedRequests
|
|
#expect(requests.count == 3)
|
|
#expect(requests[1] == original)
|
|
#expect(requests[2].baseRevision == 6 && requests[2].requestID != original.requestID)
|
|
#expect(requests[2].changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["B"])])
|
|
#expect(model.draftRevision == 7 && model.errorMessage == nil)
|
|
#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(navigation.topViewController === controller)
|
|
#expect(await source.submissionRequests.isEmpty)
|
|
}
|
|
|
|
private func makeConfiguration(type: TrainingQuestionType) -> TrainingDataStub.Configuration {
|
|
var configuration = TrainingDataStub.Configuration()
|
|
configuration.questionCount = 3
|
|
configuration.questionsHandler = { offset, limit in
|
|
let end = min(3, offset + limit)
|
|
let items: [TrainingQuestionItem] = offset < end ? ((offset + 1)...end).map { order in
|
|
let question = TrainingRemoteFixtures.question(order)
|
|
return TrainingQuestionItem(id: question.id, order: order, type: order == 2 ? type : .single,
|
|
stem: question.stem, options: question.options)
|
|
} : []
|
|
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 3, offset: offset,
|
|
nextOffset: end < 3 ? end : nil, hasMore: end < 3, items: items)
|
|
}
|
|
return configuration
|
|
}
|
|
|
|
private func makeDefaults() throws -> (name: String, defaults: UserDefaults) {
|
|
let name = "TrainingExamSelectionInteractionTests-\(UUID().uuidString)"
|
|
return (name, try #require(UserDefaults(suiteName: name)))
|
|
}
|
|
|
|
private func makeModel(defaults: UserDefaults) -> TrainingRemoteExamViewModel {
|
|
let scope = context
|
|
return TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { scope })
|
|
}
|
|
|
|
private func allViews(_ view: UIView) -> [UIView] {
|
|
[view] + view.subviews.flatMap { allViews($0) }
|
|
}
|
|
|
|
private func button(_ identifier: String, in view: UIView) -> UIButton? {
|
|
allViews(view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == identifier }
|
|
}
|
|
|
|
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
|
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
|
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
|
let reached = await condition()
|
|
try #require(reached)
|
|
}
|
|
}
|