fix(training): 优化答题交互并消除按钮置灰闪动
This commit is contained in:
@@ -0,0 +1,349 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import suixinkan
|
||||
|
||||
/// 分别在分页正文和位置保存阶段,覆盖前后翻题的同步动作锁。
|
||||
enum TrainingNavigationScenario: String, CaseIterable, Sendable {
|
||||
case previousQuestions, nextQuestions, previousPosition, nextPosition
|
||||
|
||||
var isPrevious: Bool { self == .previousQuestions || self == .previousPosition }
|
||||
var waitsForQuestions: Bool { self == .previousQuestions || self == .nextQuestions }
|
||||
var initialOrder: Int { isPrevious ? 11 : 10 }
|
||||
var targetOrder: Int { isPrevious ? 10 : 11 }
|
||||
var initialOffset: Int { isPrevious ? 10 : 0 }
|
||||
var targetOffset: Int { isPrevious ? 0 : 10 }
|
||||
}
|
||||
|
||||
/// 精确挂起选定请求,允许验证网络等待时的外观和重复操作。
|
||||
private actor TrainingNavigationRequestGate {
|
||||
private var continuations: [CheckedContinuation<Void, Never>] = []
|
||||
private var released = false
|
||||
private(set) var requestCount = 0
|
||||
|
||||
/// 每次请求独立登记,重复写入不会覆盖已等待的响应。
|
||||
func wait() async {
|
||||
requestCount += 1
|
||||
if released { return }
|
||||
await withCheckedContinuation { continuations.append($0) }
|
||||
}
|
||||
|
||||
/// 完成全部已等待响应,也用于异常退出时释放测试任务。
|
||||
func release() {
|
||||
released = true
|
||||
let pending = continuations
|
||||
continuations = []
|
||||
pending.forEach { $0.resume() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录按钮的实际外观,区分业务禁用与请求期间的交互暂停。
|
||||
private struct TrainingNavigationButtonAppearance: Equatable {
|
||||
let isEnabled: Bool
|
||||
let alpha: CGFloat
|
||||
let backgroundColor: UIColor?
|
||||
let normalTitleColor: UIColor?
|
||||
let configuredBackgroundColor: UIColor?
|
||||
let configuredForegroundColor: UIColor?
|
||||
|
||||
/// 同时覆盖 AppButton 和选项 Configuration 的颜色。
|
||||
@MainActor
|
||||
init(_ button: UIButton) {
|
||||
isEnabled = button.isEnabled
|
||||
alpha = button.alpha
|
||||
backgroundColor = button.backgroundColor
|
||||
normalTitleColor = button.titleColor(for: .normal)
|
||||
configuredBackgroundColor = button.configuration?.baseBackgroundColor
|
||||
configuredForegroundColor = button.configuration?.baseForegroundColor
|
||||
}
|
||||
}
|
||||
|
||||
/// 在真实窗口验证前后翻题和答题卡返回,不接触全局登录态或真实网络。
|
||||
@Suite("培训答题翻题和答题卡交互", .serialized)
|
||||
@MainActor
|
||||
struct TrainingExamNavigationInteractionTests {
|
||||
private let context = TrainingContext(accountScope: "exam_navigation", scenicID: 10, storeID: 3)
|
||||
|
||||
@Test("前后翻题等待题页或位置保存时不置灰,重复动作不会偏离目标", arguments: TrainingNavigationScenario.allCases)
|
||||
func navigationPreservesAppearanceAndTarget(scenario: TrainingNavigationScenario) async throws {
|
||||
let domain = try makeDefaults()
|
||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||
let gate = TrainingNavigationRequestGate()
|
||||
defer { Task { await gate.release() } }
|
||||
var configuration = TrainingDataStub.Configuration()
|
||||
configuration.questionsHandler = { offset, limit in
|
||||
if scenario.waitsForQuestions, offset == scenario.targetOffset { await gate.wait() }
|
||||
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)
|
||||
await source.seedDraft(revision: 5, answers: Dictionary(uniqueKeysWithValues: (1...30).map { ("q\($0)", ["A"]) }), lastOrder: scenario.initialOrder)
|
||||
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 }
|
||||
try await settleTransitions([navigation, controller])
|
||||
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 optionA = try #require(button("training.option.A", in: controller.view))
|
||||
let optionB = try #require(button("training.option.B", in: controller.view))
|
||||
let answerCard = try #require(controller.navigationItem.rightBarButtonItem)
|
||||
let controls = [previous, next, submit, optionA, optionB]
|
||||
let appearances = controls.map { TrainingNavigationButtonAppearance($0) }
|
||||
let moving = scenario.isPrevious ? previous : next
|
||||
#expect(controls.allSatisfy { $0.isEnabled })
|
||||
#expect(answerCard.isEnabled)
|
||||
#expect(model.currentIndex == scenario.initialOrder - 1)
|
||||
|
||||
moving.sendActions(for: .touchUpInside)
|
||||
// 同一 main actor 中连续动作,验证 Task 启动之前就已串行化。
|
||||
moving.sendActions(for: .touchUpInside)
|
||||
previous.sendActions(for: .touchUpInside)
|
||||
next.sendActions(for: .touchUpInside)
|
||||
optionB.sendActions(for: .touchUpInside)
|
||||
submit.sendActions(for: .touchUpInside)
|
||||
try activate(answerCard)
|
||||
#expect(controls.map { TrainingNavigationButtonAppearance($0) } == appearances)
|
||||
#expect(answerCard.isEnabled)
|
||||
#expect(controller.presentedViewController == nil)
|
||||
try await waitUntil { await gate.requestCount > 0 }
|
||||
#expect(model.isBusy)
|
||||
#expect(model.currentIndex == scenario.targetOrder - 1)
|
||||
#expect(controls.map { TrainingNavigationButtonAppearance($0) } == appearances)
|
||||
#expect(controls.allSatisfy { !$0.isUserInteractionEnabled })
|
||||
#expect(answerCard.isEnabled)
|
||||
#expect(allViews(controller.view).compactMap { $0 as? UILabel }.contains { $0.text == "正在加载题目…" })
|
||||
#expect(navigation.topViewController === controller)
|
||||
#expect(controller.presentedViewController == nil)
|
||||
#expect(await source.submissionRequests.isEmpty)
|
||||
let questionsWhileWaiting = await source.calls.filter { $0.name == "questions" }
|
||||
#expect(questionsWhileWaiting.map(\.offset) == [scenario.initialOffset, scenario.targetOffset])
|
||||
#expect(await source.savedRequests.count == (scenario.waitsForQuestions ? 0 : 1))
|
||||
|
||||
await gate.release()
|
||||
try await waitUntil {
|
||||
model.canEdit && model.currentQuestion?.order == scenario.targetOrder && next.isUserInteractionEnabled
|
||||
}
|
||||
#expect(model.currentIndex == scenario.targetOrder - 1)
|
||||
#expect(model.currentSelectedIDs == ["A"])
|
||||
#expect(model.errorMessage == nil)
|
||||
#expect([previous, next, submit].allSatisfy { $0.isEnabled && $0.isUserInteractionEnabled })
|
||||
#expect([previous, next, submit].map { TrainingNavigationButtonAppearance($0) } == Array(appearances.prefix(3)))
|
||||
let requests = await source.savedRequests
|
||||
#expect(requests.count == 1)
|
||||
#expect(requests.first?.lastQuestionOrder == scenario.targetOrder)
|
||||
#expect(requests.first?.changes.isEmpty == true)
|
||||
#expect(requests.first?.baseRevision == 5)
|
||||
#expect(await gate.requestCount == 1)
|
||||
let calls = await source.calls
|
||||
#expect(calls.filter { $0.name == "questions" }.map(\.offset) == [scenario.initialOffset, scenario.targetOffset])
|
||||
#expect(calls.filter { $0.name == "task" || $0.name == "progress" || $0.name == "paper" }.map(\.name) == ["task", "progress", "paper"])
|
||||
#expect(calls.filter { $0.name == "draft" && $0.limit == 0 }.count == 1)
|
||||
#expect(navigation.topViewController === controller)
|
||||
#expect(controller.presentedViewController == nil)
|
||||
}
|
||||
|
||||
@Test("首末题仅禁用越界方向,完成请求不会把所有控件一律启用", arguments: [1, 30])
|
||||
func firstAndLastQuestionKeepBoundaryDisabled(targetOrder: Int) async throws {
|
||||
let domain = try makeDefaults()
|
||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||
let source = TrainingDataStub()
|
||||
await source.seedDraft(revision: 3, answers: [:], lastOrder: targetOrder == 1 ? 2 : 29)
|
||||
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 }
|
||||
try await settleTransitions([navigation, controller])
|
||||
let previous = try #require(button("training.exam.previous", in: controller.view))
|
||||
let next = try #require(button("training.exam.next", in: controller.view))
|
||||
let moving = targetOrder == 1 ? previous : next
|
||||
moving.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { model.canEdit && model.currentQuestion?.order == targetOrder && moving.isUserInteractionEnabled }
|
||||
let disabled = targetOrder == 1 ? previous : next
|
||||
let allowed = targetOrder == 1 ? next : previous
|
||||
#expect(!disabled.isEnabled)
|
||||
#expect(allowed.isEnabled)
|
||||
#expect(abs(disabled.alpha - 0.6) < 0.001)
|
||||
#expect(allowed.alpha == 1)
|
||||
#expect(button("training.exam.submit", in: controller.view)?.isEnabled == true)
|
||||
#expect(controller.navigationItem.rightBarButtonItem?.isEnabled == true)
|
||||
let before = await source.calls
|
||||
disabled.sendActions(for: .touchUpInside)
|
||||
try await settleTransitions([navigation, controller])
|
||||
#expect(model.currentIndex == targetOrder - 1)
|
||||
#expect(!disabled.isEnabled && allowed.isEnabled)
|
||||
#expect(await source.calls == before)
|
||||
}
|
||||
|
||||
@Test("答题卡完成或系统关闭不重载课程,500题跨页选择只请求目标页")
|
||||
func answerCardDismissalAndRandomAccessAvoidFullReload() async throws {
|
||||
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 = 500
|
||||
configuration.questionsHandler = { offset, limit in
|
||||
if offset == 490 { await gate.wait() }
|
||||
return Self.questions(total: 500, offset: offset, limit: limit)
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
await source.seedDraft(revision: 5, answers: ["q401": ["B"], "q500": ["A"]], lastOrder: 401)
|
||||
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 }
|
||||
try await settleTransitions([navigation, controller])
|
||||
let initialCalls = await source.calls
|
||||
|
||||
let doneSheet = try await openAnswerCard(controller)
|
||||
let doneCard = try #require(doneSheet.topViewController as? TrainingAnswerCardViewController)
|
||||
let done = try #require(doneCard.navigationItem.rightBarButtonItem)
|
||||
// 正规 appearance transition 模拟答题卡完全覆盖考试页的系统回调。
|
||||
controller.beginAppearanceTransition(false, animated: false)
|
||||
controller.endAppearanceTransition()
|
||||
try activate(done)
|
||||
try await waitUntil { controller.presentedViewController == nil }
|
||||
try await settleTransitions([navigation, controller, doneSheet])
|
||||
controller.beginAppearanceTransition(true, animated: false)
|
||||
controller.endAppearanceTransition()
|
||||
try await settleTransitions([navigation, controller])
|
||||
#expect(model.currentIndex == 400 && model.currentSelectedIDs == ["B"])
|
||||
#expect(await source.calls == initialCalls)
|
||||
|
||||
let systemSheet = try await openAnswerCard(controller)
|
||||
let presentation = systemSheet.presentationController
|
||||
controller.beginAppearanceTransition(false, animated: false)
|
||||
controller.endAppearanceTransition()
|
||||
systemSheet.dismiss(animated: true)
|
||||
try await waitUntil { controller.presentedViewController == nil }
|
||||
try await settleTransitions([navigation, controller, systemSheet])
|
||||
// 转发交互关闭的公开 delegate 回调,覆盖手势关闭后的业务入口。
|
||||
if let presentation { presentation.delegate?.presentationControllerDidDismiss?(presentation) }
|
||||
controller.beginAppearanceTransition(true, animated: false)
|
||||
controller.endAppearanceTransition()
|
||||
try await settleTransitions([navigation, controller])
|
||||
#expect(model.currentIndex == 400 && model.currentSelectedIDs == ["B"])
|
||||
#expect(await source.calls == initialCalls)
|
||||
#expect(button("training.exam.next", in: controller.view)?.isEnabled == true)
|
||||
#expect(controller.navigationItem.rightBarButtonItem?.isEnabled == true)
|
||||
|
||||
let selectionSheet = try await openAnswerCard(controller)
|
||||
let card = try #require(selectionSheet.topViewController as? TrainingAnswerCardViewController)
|
||||
let collection = try #require(allViews(card.view).first { $0 is UICollectionView } as? UICollectionView)
|
||||
try await waitUntil { collection.numberOfItems(inSection: 0) == 500 }
|
||||
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 appearances = [previous, next, submit].map { TrainingNavigationButtonAppearance($0) }
|
||||
let target = IndexPath(item: 499, section: 0)
|
||||
collection.scrollToItem(at: target, at: .centeredVertically, animated: false)
|
||||
collection.layoutIfNeeded()
|
||||
collection.selectItem(at: target, animated: false, scrollPosition: [])
|
||||
collection.delegate?.collectionView?(collection, didSelectItemAt: target)
|
||||
try await waitUntil { await gate.requestCount > 0 }
|
||||
#expect(controller.presentedViewController == nil)
|
||||
#expect(model.currentIndex == 499)
|
||||
#expect([previous, next, submit].map { TrainingNavigationButtonAppearance($0) } == appearances)
|
||||
#expect(controller.navigationItem.rightBarButtonItem?.isEnabled == true)
|
||||
#expect([previous, next, submit].allSatisfy { !$0.isUserInteractionEnabled })
|
||||
#expect(await source.calls.filter { $0.name == "questions" }.map(\.offset) == [400, 490])
|
||||
await gate.release()
|
||||
try await waitUntil { model.canEdit && model.currentQuestion?.id == "q500" && next.isUserInteractionEnabled }
|
||||
try await settleTransitions([navigation, controller, selectionSheet])
|
||||
#expect(model.currentIndex == 499 && model.currentSelectedIDs == ["A"])
|
||||
#expect(model.answeredCount == 2)
|
||||
#expect(previous.isEnabled && !next.isEnabled)
|
||||
#expect(navigation.topViewController === controller)
|
||||
let finalCalls = await source.calls
|
||||
#expect(finalCalls.filter { $0.name == "task" || $0.name == "progress" || $0.name == "paper" } == initialCalls.filter { $0.name == "task" || $0.name == "progress" || $0.name == "paper" })
|
||||
#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 == "questions" }.allSatisfy { $0.limit == 10 })
|
||||
let saves = await source.savedRequests
|
||||
#expect(saves.count == 1)
|
||||
#expect(saves.first?.lastQuestionOrder == 500 && saves.first?.changes.isEmpty == true)
|
||||
#expect(await source.submissionRequests.isEmpty)
|
||||
}
|
||||
|
||||
private nonisolated static func questions(total: Int, offset: Int, limit: Int) -> TrainingQuestionPage {
|
||||
let end = min(total, offset + limit)
|
||||
let items: [TrainingQuestionItem] = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : []
|
||||
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: total, offset: offset,
|
||||
nextOffset: end < total ? end : nil, hasMore: end < total, items: items)
|
||||
}
|
||||
|
||||
private func makeDefaults() throws -> (name: String, defaults: UserDefaults) {
|
||||
let name = "TrainingExamNavigationInteractionTests-\(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 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 openAnswerCard(_ controller: TrainingExamViewController) async throws -> UINavigationController {
|
||||
let item = try #require(controller.navigationItem.rightBarButtonItem)
|
||||
try activate(item)
|
||||
try await waitUntil { controller.presentedViewController is UINavigationController }
|
||||
let presented = try #require(controller.presentedViewController as? UINavigationController)
|
||||
try await settleTransitions([controller, presented])
|
||||
return presented
|
||||
}
|
||||
|
||||
private func activate(_ item: UIBarButtonItem) throws {
|
||||
if let action = item.primaryAction {
|
||||
let dispatcher = UIButton(type: .system)
|
||||
dispatcher.addAction(action, for: .touchUpInside)
|
||||
dispatcher.sendActions(for: .touchUpInside)
|
||||
} else {
|
||||
let action = try #require(item.action)
|
||||
UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil)
|
||||
}
|
||||
}
|
||||
|
||||
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 settleTransitions(_ controllers: [UIViewController]) async throws {
|
||||
try await Task.sleep(for: .milliseconds(20))
|
||||
try await waitUntil { controllers.allSatisfy { $0.transitionCoordinator == nil && !$0.isBeingPresented && !$0.isBeingDismissed } }
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// 捕获实际 AppButton 外观,覆盖主按钮置灰和次按钮 alpha 降低两种退化。
|
||||
private struct TrainingSelectionButtonAppearance: Equatable {
|
||||
let isEnabled: Bool
|
||||
let alpha: CGFloat
|
||||
let backgroundColor: UIColor?
|
||||
let normalTitleColor: UIColor?
|
||||
|
||||
/// 从当前按钮读取外观,避免只断言业务状态而漏掉闪烁。
|
||||
@MainActor
|
||||
init(_ button: UIButton) {
|
||||
isEnabled = button.isEnabled
|
||||
alpha = button.alpha
|
||||
backgroundColor = button.backgroundColor
|
||||
normalTitleColor = button.titleColor(for: .normal)
|
||||
}
|
||||
}
|
||||
|
||||
/// 真机 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 {
|
||||
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 window = try makeWindow(navigation)
|
||||
defer { window.isHidden = true }
|
||||
try await waitUntil { model.canEdit && 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 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)
|
||||
|
||||
optionA.sendActions(for: .touchUpInside)
|
||||
// 不让出 main actor:确认网络 Task 启动前已经高亮并锁住所有动作入口。
|
||||
#expect(optionA.accessibilityTraits.contains(.selected))
|
||||
#expect(optionB.accessibilityTraits.contains(.selected) == (type == .multiple))
|
||||
#expect(optionA.configuration?.baseBackgroundColor == AppColor.primaryLight)
|
||||
#expect(model.currentSelectedIDs == ["B"])
|
||||
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(controls.map { TrainingSelectionButtonAppearance($0) } == appearances)
|
||||
#expect(controls.allSatisfy { $0.isUserInteractionEnabled })
|
||||
#expect(await source.savedRequests.count == 1)
|
||||
#expect(navigation.topViewController === controller)
|
||||
#expect(controller.presentedViewController == nil)
|
||||
}
|
||||
|
||||
@Test("保存超时恢复已确认选项并提供重试,禁止新选择更换原请求")
|
||||
func timeoutRestoresConfirmedAnswerAndRetriesIdenticalPayload() async throws {
|
||||
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 window = try makeWindow(navigation)
|
||||
defer { window.isHidden = true }
|
||||
try await waitUntil { model.canEdit && 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)
|
||||
#expect(original.baseRevision == 5)
|
||||
#expect(original.changes == [TrainingDraftChange(questionID: "q2", selectedOptionIDs: ["A"])])
|
||||
optionB.sendActions(for: .touchUpInside)
|
||||
#expect(await source.savedRequests.count == 1)
|
||||
#expect(model.currentSelectedIDs == ["B"])
|
||||
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)
|
||||
#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(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 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) }
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ struct TrainingUIRenderingTests {
|
||||
#expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem })
|
||||
Attachment.record(render(navigation.view), named: "成绩答案解析展开", as: .png)
|
||||
learning.sendActions(for: .touchUpInside)
|
||||
try await waitForNavigation(in: navigation) { $0 === course }
|
||||
try await settleTransitions(in: navigation)
|
||||
#expect(navigation.topViewController === course)
|
||||
navigation.setViewControllers([center, result], animated: false)
|
||||
@@ -94,6 +95,7 @@ struct TrainingUIRenderingTests {
|
||||
await result.reload()
|
||||
let newLearning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" })
|
||||
newLearning.sendActions(for: .touchUpInside)
|
||||
try await waitForNavigation(in: navigation) { ($0 as? TrainingCourseViewController)?.taskID == "task_1" }
|
||||
try await settleTransitions(in: navigation)
|
||||
#expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "task_1")
|
||||
await source.configure { $0.attemptHandler = { _ in
|
||||
@@ -113,6 +115,7 @@ struct TrainingUIRenderingTests {
|
||||
Attachment.record(render(navigation.view), named: "通过成绩仍可返回学习", as: .png)
|
||||
let completion = try #require(allViews(passedResult.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" })
|
||||
completion.sendActions(for: .touchUpInside)
|
||||
try await waitForNavigation(in: navigation) { $0 === center }
|
||||
try await settleTransitions(in: navigation)
|
||||
#expect(navigation.topViewController === center)
|
||||
}
|
||||
@@ -158,6 +161,16 @@ struct TrainingUIRenderingTests {
|
||||
Attachment.record(image, named: "100题答题卡", as: .png)
|
||||
}
|
||||
|
||||
/// 等待实际目标页面,避免转场尚未开始时误把 nil coordinator 当作完成。
|
||||
private func waitForNavigation(in navigation: UINavigationController, matches: (UIViewController?) -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||
while !matches(navigation.topViewController), ContinuousClock.now < deadline {
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
let reached = matches(navigation.topViewController)
|
||||
try #require(reached)
|
||||
}
|
||||
|
||||
/// 前一导航动画结束后再执行后续操作,避免测试同时驱动互相冲突的转场。
|
||||
private func settleTransitions(in navigation: UINavigationController) async throws {
|
||||
await Task.yield()
|
||||
|
||||
Reference in New Issue
Block a user