261 lines
14 KiB
Swift
261 lines
14 KiB
Swift
import Foundation
|
|
import Testing
|
|
import UIKit
|
|
@testable import suixinkan
|
|
|
|
/// 明确挂起保存响应,使测试可检查请求发出前后以及确认前的界面状态。
|
|
private actor TrainingSelectionSaveGate {
|
|
private var responses: [CheckedContinuation<Void, Never>] = []
|
|
private var released = false
|
|
private(set) var requestCount = 0
|
|
|
|
/// 保存请求等待测试释放;意外并发请求也独立等待,不覆盖原 continuation。
|
|
func wait() async {
|
|
requestCount += 1
|
|
if released { return }
|
|
await withCheckedContinuation { responses.append($0) }
|
|
}
|
|
|
|
/// 完成所有已挂起请求,避免失败断言留下未结束的异步任务。
|
|
func release() {
|
|
released = true
|
|
let pending = responses
|
|
responses = []
|
|
pending.forEach { $0.resume() }
|
|
}
|
|
}
|
|
|
|
/// 首次保存丢失响应,重试确认同一请求的草稿版本。
|
|
private actor TrainingSelectionTimeoutResponse {
|
|
private var count = 0
|
|
|
|
/// 不依赖固定延时,第一次失败、第二次确认原增量负载。
|
|
func confirm(_ request: TrainingDraftSaveRequest) throws -> TrainingDraftConfirmation {
|
|
count += 1
|
|
if count == 1 { throw URLError(.timedOut) }
|
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 3)
|
|
}
|
|
}
|
|
|
|
/// 捕获实际 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)
|
|
}
|
|
}
|