perf(training): 优化答题自动保存与培训页面交互
This commit is contained in:
@@ -3,20 +3,20 @@ 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。
|
||||
/// 保存请求等待测试释放,意外并发也不会覆盖原 continuation。
|
||||
func wait() async {
|
||||
requestCount += 1
|
||||
if released { return }
|
||||
await withCheckedContinuation { responses.append($0) }
|
||||
}
|
||||
|
||||
/// 完成所有已挂起请求,避免失败断言留下未结束的异步任务。
|
||||
/// 释放全部已挂起请求,异常退出也不会遗留测试任务。
|
||||
func release() {
|
||||
released = true
|
||||
let pending = responses
|
||||
@@ -25,11 +25,11 @@ private actor TrainingSelectionSaveGate {
|
||||
}
|
||||
}
|
||||
|
||||
/// 首次保存丢失响应,重试确认同一请求的草稿版本。
|
||||
/// 首批保存丢失响应,后续确认用于检查同键恢复与较新本地选择的串行提交。
|
||||
private actor TrainingSelectionTimeoutResponse {
|
||||
private var count = 0
|
||||
|
||||
/// 不依赖固定延时,第一次失败、第二次确认原增量负载。
|
||||
/// 首次失败,其后每次只确认调用方传入的冻结版本。
|
||||
func confirm(_ request: TrainingDraftSaveRequest) throws -> TrainingDraftConfirmation {
|
||||
count += 1
|
||||
if count == 1 { throw URLError(.timedOut) }
|
||||
@@ -38,14 +38,14 @@ private actor TrainingSelectionTimeoutResponse {
|
||||
}
|
||||
}
|
||||
|
||||
/// 捕获实际 AppButton 外观,覆盖主按钮置灰和次按钮 alpha 降低两种退化。
|
||||
/// 捕获实际按钮外观,避免保存时重新出现置灰或透明度变化。
|
||||
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
|
||||
@@ -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)
|
||||
@MainActor
|
||||
struct TrainingExamSelectionInteractionTests {
|
||||
private let context = TrainingContext(accountScope: "exam_selection", scenicID: 10, storeID: 3)
|
||||
|
||||
@Test("选项即时高亮,保存期间其它控件不置灰且连续操作只写入一次", arguments: [TrainingQuestionType.single, .multiple])
|
||||
func selectionKeepsAppearanceAndSerializesActions(type: TrainingQuestionType) async throws {
|
||||
@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()
|
||||
@@ -78,80 +106,78 @@ struct TrainingExamSelectionInteractionTests {
|
||||
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 && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||
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 previous = try #require(button("training.exam.previous", in: controller.view))
|
||||
let next = try #require(button("training.exam.next", 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 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 answerCardWasEnabled = answerCard.isEnabled
|
||||
let callsBefore = await source.calls
|
||||
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)
|
||||
let firstSelection: Set<String> = type == .single ? ["A"] : ["A", "B"]
|
||||
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
||||
|
||||
optionA.sendActions(for: .touchUpInside)
|
||||
// 不让出 main actor:确认网络 Task 启动前已经高亮并锁住所有动作入口。
|
||||
// 不让出主 actor:选择与落盘先完成,网络防抖不能延迟高亮。
|
||||
#expect(model.currentSelectedIDs == firstSelection)
|
||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
||||
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
||||
#expect(optionA.configuration?.baseBackgroundColor == AppColor.primaryLight)
|
||||
#expect(model.currentSelectedIDs == ["B"])
|
||||
#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)
|
||||
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(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
||||
#expect(answerCard.isEnabled == answerCardWasEnabled)
|
||||
#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(!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)
|
||||
#expect(navigation.topViewController === controller)
|
||||
#expect(controller.presentedViewController == nil)
|
||||
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 timeoutRestoresConfirmedAnswerAndRetriesIdenticalPayload() async throws {
|
||||
@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()
|
||||
@@ -162,44 +188,39 @@ struct TrainingExamSelectionInteractionTests {
|
||||
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 && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||
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)
|
||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
||||
try await waitUntil { model.hasPendingMutation && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "重试保存" }
|
||||
let retry = try #require(button("training.exam.submit", in: controller.view))
|
||||
#expect(retry.isEnabled && retry.isUserInteractionEnabled)
|
||||
#expect(!model.canEdit)
|
||||
#expect(model.currentSelectedIDs == ["B"])
|
||||
#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)
|
||||
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.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)
|
||||
try await waitUntil { model.canEdit && model.currentSelectedIDs == ["A"] && self.button("training.exam.submit", in: controller.view)?.title(for: .normal) == "交卷" }
|
||||
let retriedRequests = await source.savedRequests
|
||||
#expect(retriedRequests.count == 2)
|
||||
#expect(retriedRequests.last == original)
|
||||
#expect(model.draftRevision == 6)
|
||||
#expect(!model.hasPendingMutation)
|
||||
#expect(model.errorMessage == nil)
|
||||
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))
|
||||
#expect(!optionB.accessibilityTraits.contains(.selected))
|
||||
#expect(!optionA.accessibilityTraits.contains(.selected) && optionB.accessibilityTraits.contains(.selected))
|
||||
#expect(navigation.topViewController === controller)
|
||||
#expect(await source.submissionRequests.isEmpty)
|
||||
}
|
||||
@@ -231,18 +252,6 @@ struct TrainingExamSelectionInteractionTests {
|
||||
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] {
|
||||
[view] + view.subviews.flatMap { allViews($0) }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user