407 lines
23 KiB
Swift
407 lines
23 KiB
Swift
import Foundation
|
|
import Testing
|
|
import UIKit
|
|
@testable import suixinkan
|
|
|
|
/// 仅未缓存题页读取需要同步动作锁,位置保存由后台串行处理。
|
|
enum TrainingNavigationScenario: String, CaseIterable, Sendable {
|
|
case previousQuestions, nextQuestions
|
|
|
|
var isPrevious: Bool { self == .previousQuestions }
|
|
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 offset == scenario.targetOffset { await gate.wait() }
|
|
return Self.questions(total: 30, offset: offset, limit: limit)
|
|
}
|
|
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.isEmpty)
|
|
|
|
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)))
|
|
#expect(await model.flushDraft(service: source))
|
|
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)
|
|
#expect(await model.flushDraft(service: source))
|
|
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 })
|
|
#expect(await model.flushDraft(service: source))
|
|
let saves = await source.savedRequests
|
|
#expect(saves.count == 1)
|
|
#expect(saves.first?.lastQuestionOrder == 500 && saves.first?.changes.isEmpty == true)
|
|
#expect(await source.submissionRequests.isEmpty)
|
|
}
|
|
|
|
@Test("保存挂起时缓存翻题和答题卡继续可用,本地答案不会被旧页刷新覆盖")
|
|
func cachedNavigationAndAnswerCardRemainAvailableWhileSaving() async throws {
|
|
let manager = GlobalLoadingManager.shared
|
|
manager.hideAll()
|
|
defer { manager.hideAll() }
|
|
let domain = try makeDefaults()
|
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
|
let gate = TrainingNavigationRequestGate()
|
|
defer { Task { await gate.release() } }
|
|
var configuration = TrainingDataStub.Configuration()
|
|
configuration.questionCount = 3
|
|
configuration.saveHandler = { request in
|
|
await gate.wait()
|
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + (request.changes.isEmpty ? 0 : 1),
|
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 3)
|
|
}
|
|
let source = TrainingDataStub(configuration: configuration)
|
|
await source.seedDraft(revision: 5, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]], lastOrder: 2)
|
|
let model = makeModel(defaults: domain.defaults)
|
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
|
let navigation = UINavigationController(rootViewController: controller)
|
|
let window = try makeWindow(navigation)
|
|
defer { window.isHidden = true }
|
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
|
try await settleTransitions([navigation, controller])
|
|
let initialReads = await source.calls.filter { ["task", "progress", "paper", "questions", "draft"].contains($0.name) }
|
|
let optionB = try #require(button("training.option.B", in: controller.view))
|
|
optionB.sendActions(for: .touchUpInside)
|
|
try await waitUntil { await gate.requestCount == 1 }
|
|
#expect(model.isSaving && model.canEdit && !manager.isShowing)
|
|
let next = try #require(button("training.exam.next", in: controller.view))
|
|
next.sendActions(for: .touchUpInside)
|
|
// 缓存跳转须当场完成,不能等正在保存的首批请求。
|
|
#expect(model.currentIndex == 2 && model.currentQuestion?.id == "q3")
|
|
#expect(!model.isBusy && model.isSaving && !manager.isShowing)
|
|
#expect(!next.isEnabled)
|
|
let previous = try #require(button("training.exam.previous", in: controller.view))
|
|
#expect(previous.isEnabled && previous.isUserInteractionEnabled)
|
|
previous.sendActions(for: .touchUpInside)
|
|
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
|
#expect(button("training.option.B", in: controller.view)?.accessibilityTraits.contains(.selected) == true)
|
|
#expect(!manager.isShowing && model.canEdit)
|
|
let cardSheet = try await openAnswerCard(controller)
|
|
let card = try #require(cardSheet.topViewController as? TrainingAnswerCardViewController)
|
|
let collection = try #require(allViews(card.view).compactMap { $0 as? UICollectionView }.first)
|
|
try await waitUntil { collection.numberOfItems(inSection: 0) == 3 }
|
|
#expect(!manager.isShowing && model.isSaving)
|
|
let done = try #require(card.navigationItem.rightBarButtonItem)
|
|
try activate(done)
|
|
try await waitUntil { controller.presentedViewController == nil }
|
|
try await settleTransitions([navigation, controller, cardSheet])
|
|
#expect(model.currentIndex == 1 && model.currentSelectedIDs == ["B"])
|
|
#expect(!manager.isShowing && model.canEdit)
|
|
#expect(await source.savedRequests.count == 1)
|
|
let finalReads = await source.calls.filter { ["task", "progress", "paper", "questions", "draft"].contains($0.name) }
|
|
#expect(finalReads == initialReads)
|
|
#expect(navigation.topViewController === controller)
|
|
await gate.release()
|
|
#expect(await model.flushDraft(service: source))
|
|
#expect(!model.isSaving && !model.hasUnsavedChanges && model.currentSelectedIDs == ["B"])
|
|
}
|
|
|
|
private nonisolated static func questions(total: Int, offset: Int, limit: Int) -> TrainingQuestionPage {
|
|
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
|
|
window.isHidden = false
|
|
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)
|
|
}
|
|
}
|