fix(training): 优化答题交互并消除按钮置灰闪动
This commit is contained in:
@@ -167,19 +167,25 @@ final class TrainingRemoteExamViewModel {
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 计算本次点击的展示选择,不提前修改已确认答案或草稿版本。
|
||||
func selectionPreview(optionID: String) -> Set<String>? {
|
||||
guard canEdit, let question = currentQuestion,
|
||||
question.options.contains(where: { $0.id == optionID }) else { return nil }
|
||||
var selected = currentSelectedIDs
|
||||
if question.type == .single { selected = [optionID] }
|
||||
else if selected.contains(optionID) { selected.remove(optionID) }
|
||||
else { selected.insert(optionID) }
|
||||
return selected
|
||||
}
|
||||
|
||||
/// 增量保存当前一题,网络结果未知时保留原 ID 和完整请求供重试。
|
||||
func select(optionID: String, service: any TrainingDataServing) async {
|
||||
guard canEdit, let question = currentQuestion, let paper,
|
||||
question.options.contains(where: { $0.id == optionID }) else { return }
|
||||
guard let selected = selectionPreview(optionID: optionID), let question = currentQuestion, let paper else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
var selected = currentSelectedIDs
|
||||
if question.type == .single { selected = [optionID] }
|
||||
else if selected.contains(optionID) { selected.remove(optionID) }
|
||||
else { selected.insert(optionID) }
|
||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
||||
baseRevision: draftRevision, lastQuestionOrder: question.order,
|
||||
changes: [TrainingDraftChange(questionID: question.id, selectedOptionIDs: selected.sorted())]))
|
||||
|
||||
@@ -10,6 +10,10 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
private var openedResult = false
|
||||
private var navigationIsScheduled = false
|
||||
private var hasAppeared = false
|
||||
private var isPerformingOperation = false
|
||||
private var needsReloadOnReturn = false
|
||||
private var renderedQuestion: TrainingQuestionItem?
|
||||
private var optionButtons: [String: UIButton] = [:]
|
||||
private let scrollView = UIScrollView()
|
||||
private let contentStack = TrainingUI.card()
|
||||
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
|
||||
@@ -48,6 +52,8 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
navigationStack.distribution = .fillEqually
|
||||
navigationStack.addArrangedSubview(previousButton)
|
||||
navigationStack.addArrangedSubview(nextButton)
|
||||
previousButton.accessibilityIdentifier = "training.exam.previous"
|
||||
nextButton.accessibilityIdentifier = "training.exam.next"
|
||||
[positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview)
|
||||
bottomStack.axis = .vertical
|
||||
bottomStack.spacing = 8
|
||||
@@ -89,18 +95,29 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
let returning = hasAppeared
|
||||
let shouldReload = needsReloadOnReturn
|
||||
needsReloadOnReturn = false
|
||||
hasAppeared = true
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
|
||||
beginOperation(message: "正在确认考试状态…")
|
||||
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
|
||||
return
|
||||
}
|
||||
if returning, !viewModel.isBusy { loadExam() }
|
||||
if returning, shouldReload { loadExam() }
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
// 自有答题卡和确认弹窗关闭后继续当前题,真实导航返回才刷新考试资格。
|
||||
if navigationController?.topViewController !== self { needsReloadOnReturn = true }
|
||||
}
|
||||
|
||||
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||
|
||||
private func loadExam() {
|
||||
disableControls()
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
beginOperation(message: "正在加载试卷…")
|
||||
Task { @MainActor in
|
||||
await viewModel.load(service: service, resetDraft: resetDraft)
|
||||
finishOperation()
|
||||
@@ -108,10 +125,11 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
private func applyState() {
|
||||
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||
setOperationInteractionEnabled(true)
|
||||
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
|
||||
: viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
|
||||
guard let question = viewModel.currentQuestion else {
|
||||
clearOptions()
|
||||
positionLabel.text = ""
|
||||
questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…")
|
||||
hintLabel.text = ""
|
||||
@@ -127,29 +145,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(viewModel.questionCount) 题 · \(question.type == .single ? "单选题" : "多选题")"
|
||||
questionLabel.text = question.stem
|
||||
hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分"
|
||||
for (index, option) in question.options.enumerated() {
|
||||
let selected = viewModel.currentSelectedIDs.contains(option.id)
|
||||
let button = UIButton(type: .system)
|
||||
var configuration = UIButton.Configuration.filled()
|
||||
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
|
||||
configuration.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
|
||||
configuration.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
|
||||
configuration.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
|
||||
configuration.imagePadding = 12
|
||||
configuration.titleAlignment = .leading
|
||||
configuration.cornerStyle = .medium
|
||||
button.configuration = configuration
|
||||
button.contentHorizontalAlignment = .leading
|
||||
button.titleLabel?.numberOfLines = 0
|
||||
button.titleLabel?.lineBreakMode = .byWordWrapping
|
||||
button.isEnabled = viewModel.canEdit
|
||||
button.accessibilityIdentifier = "training.option.\(option.id)"
|
||||
button.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
|
||||
optionStack.addArrangedSubview(button)
|
||||
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
|
||||
}
|
||||
renderOptions(for: question)
|
||||
updateOptionSelection(viewModel.currentSelectedIDs)
|
||||
for button in optionButtons.values { button.isEnabled = viewModel.canEdit }
|
||||
previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0
|
||||
nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1
|
||||
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · 答案已保存,可稍后继续"
|
||||
@@ -158,13 +156,65 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
|
||||
}
|
||||
|
||||
private func disableControls() {
|
||||
optionStack.arrangedSubviews.compactMap { $0 as? UIButton }.forEach { $0.isEnabled = false }
|
||||
[previousButton, nextButton, submitButton].forEach { $0.isEnabled = false }
|
||||
navigationItem.rightBarButtonItem?.isEnabled = false
|
||||
private func clearOptions() {
|
||||
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||
optionButtons = [:]
|
||||
renderedQuestion = nil
|
||||
}
|
||||
|
||||
private func renderOptions(for question: TrainingQuestionItem) {
|
||||
guard renderedQuestion != question else { return }
|
||||
clearOptions()
|
||||
renderedQuestion = question
|
||||
for (index, option) in question.options.enumerated() {
|
||||
let button = UIButton(type: .system)
|
||||
var configuration = UIButton.Configuration.filled()
|
||||
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
|
||||
configuration.imagePadding = 12
|
||||
configuration.titleAlignment = .leading
|
||||
configuration.cornerStyle = .medium
|
||||
button.configuration = configuration
|
||||
button.contentHorizontalAlignment = .leading
|
||||
button.titleLabel?.numberOfLines = 0
|
||||
button.titleLabel?.lineBreakMode = .byWordWrapping
|
||||
button.accessibilityIdentifier = "training.option.\(option.id)"
|
||||
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
|
||||
optionButtons[option.id] = button
|
||||
optionStack.addArrangedSubview(button)
|
||||
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
|
||||
}
|
||||
}
|
||||
|
||||
private func updateOptionSelection(_ selectedIDs: Set<String>) {
|
||||
UIView.performWithoutAnimation {
|
||||
for (id, button) in optionButtons {
|
||||
let selected = selectedIDs.contains(id)
|
||||
var configuration = button.configuration
|
||||
configuration?.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
|
||||
configuration?.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
|
||||
configuration?.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
|
||||
button.configuration = configuration
|
||||
button.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func setOperationInteractionEnabled(_ enabled: Bool) {
|
||||
// 网络操作只暂停动作,保留已启用控件的颜色和透明度。
|
||||
let buttons: [UIButton] = Array(optionButtons.values) + [previousButton, nextButton, submitButton]
|
||||
for button in buttons { button.isUserInteractionEnabled = enabled }
|
||||
}
|
||||
|
||||
private func beginOperation(message: String) {
|
||||
isPerformingOperation = true
|
||||
setOperationInteractionEnabled(false)
|
||||
statusLabel.text = message
|
||||
statusLabel.textColor = AppColor.textSecondary
|
||||
}
|
||||
|
||||
private func finishOperation() {
|
||||
isPerformingOperation = false
|
||||
applyState()
|
||||
scheduleNavigationIfNeeded()
|
||||
}
|
||||
@@ -203,8 +253,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
private func selectOption(_ id: String) {
|
||||
guard viewModel.canEdit else { return }
|
||||
disableControls()
|
||||
guard !isPerformingOperation, let selected = viewModel.selectionPreview(optionID: id) else { return }
|
||||
updateOptionSelection(selected)
|
||||
beginOperation(message: "正在保存答案…")
|
||||
Task { @MainActor in
|
||||
await viewModel.select(optionID: id, service: service)
|
||||
finishOperation()
|
||||
@@ -212,8 +263,9 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
private func goToQuestion(_ index: Int) {
|
||||
guard viewModel.canEdit else { return }
|
||||
disableControls()
|
||||
guard !isPerformingOperation, viewModel.canEdit,
|
||||
(0..<viewModel.questionCount).contains(index), index != viewModel.currentIndex else { return }
|
||||
beginOperation(message: "正在加载题目…")
|
||||
Task { @MainActor in
|
||||
await viewModel.goToQuestion(index, service: service)
|
||||
finishOperation()
|
||||
@@ -226,7 +278,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
@objc private func nextTapped() { goToQuestion(viewModel.currentIndex + 1) }
|
||||
|
||||
@objc private func answerCardTapped() {
|
||||
guard viewModel.canEdit else { return }
|
||||
guard !isPerformingOperation, viewModel.canEdit, presentedViewController == nil else { return }
|
||||
let controller = TrainingAnswerCardViewController(questionCount: viewModel.questionCount,
|
||||
answeredOrders: viewModel.answeredQuestionOrders, currentIndex: viewModel.currentIndex)
|
||||
controller.onSelect = { [weak self] index in self?.goToQuestion(index) }
|
||||
@@ -236,15 +288,15 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
@objc private func submitTapped() {
|
||||
guard !viewModel.isBusy else { return }
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
if viewModel.hasPendingMutation {
|
||||
disableControls()
|
||||
beginOperation(message: "正在重试保存…")
|
||||
Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() }
|
||||
return
|
||||
}
|
||||
if viewModel.hasPendingSubmission { performSubmit(); return }
|
||||
if viewModel.canRetryCurrentPage {
|
||||
disableControls()
|
||||
beginOperation(message: "正在加载题目…")
|
||||
Task { @MainActor in await viewModel.retryCurrentPage(service: service); finishOperation() }
|
||||
return
|
||||
}
|
||||
@@ -255,6 +307,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
showToast("还有 \(viewModel.questionCount - viewModel.answeredCount) 道题未作答,已定位到第一道")
|
||||
return
|
||||
}
|
||||
guard presentedViewController == nil else { return }
|
||||
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(viewModel.questionCount) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "交卷", style: .default) { [weak self] _ in self?.performSubmit() })
|
||||
@@ -262,7 +315,8 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
private func performSubmit() {
|
||||
disableControls()
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
beginOperation(message: "正在提交并确认成绩…")
|
||||
Task { @MainActor in
|
||||
_ = await viewModel.submit(service: service)
|
||||
finishOperation()
|
||||
|
||||
@@ -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