feat(training): 为请求操作接入通用Loading
This commit is contained in:
@@ -0,0 +1,404 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import suixinkan
|
||||
|
||||
/// 选项保存与跨页题目请求,分别验证成功和失败后的 Loading 释放。
|
||||
enum TrainingLoadingExamScenario: String, CaseIterable, Sendable {
|
||||
case selectionSuccess, selectionFailure, nextSuccess, nextFailure
|
||||
var selectsAnswer: Bool { self == .selectionSuccess || self == .selectionFailure }
|
||||
var fails: Bool { self == .selectionFailure || self == .nextFailure }
|
||||
}
|
||||
|
||||
/// 列表显式分页和错误重试均应持有请求 Loading。
|
||||
enum TrainingLoadingCenterScenario: String, CaseIterable, Sendable {
|
||||
case nextPage, retry
|
||||
}
|
||||
|
||||
/// 让请求响应明确等待测试确认,观察同步 Loading 和页面离开后的迟到回调。
|
||||
private actor TrainingLoadingRequestGate {
|
||||
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() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 将全局 Loading 放进本例独立的真实 keyWindow,关闭后恢复原 keyWindow。
|
||||
@MainActor
|
||||
private final class TrainingLoadingWindowScope {
|
||||
let window: UIWindow
|
||||
private weak var previousKeyWindow: UIWindow?
|
||||
|
||||
/// 本例只接管窗口,不写入 AppStore 的账号、景区或店铺。
|
||||
init(_ navigation: UINavigationController) throws {
|
||||
let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
|
||||
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
|
||||
window = UIWindow(windowScene: scene)
|
||||
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
window.rootViewController = navigation
|
||||
window.makeKeyAndVisible()
|
||||
navigation.view.layoutIfNeeded()
|
||||
}
|
||||
|
||||
/// 隐藏测试窗口并恢复之前的应用窗口。
|
||||
func close() {
|
||||
window.isHidden = true
|
||||
window.rootViewController = nil
|
||||
previousKeyWindow?.makeKey()
|
||||
}
|
||||
}
|
||||
|
||||
/// 请求 Loading 的页面生命周期回归;每例清理全局展示并使用独立网络和持久化域。
|
||||
@Suite("培训页面请求 Loading", .serialized)
|
||||
@MainActor
|
||||
struct TrainingRequestLoadingTests {
|
||||
private let context = TrainingContext(accountScope: "training_loading", scenicID: 10, storeID: 3)
|
||||
|
||||
@Test("选项和翻题点击同步展示 App Loading,成功或失败均关闭", arguments: TrainingLoadingExamScenario.allCases)
|
||||
func examRequestsOwnLoadingUntilResponse(scenario: TrainingLoadingExamScenario) async throws {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.hideAll()
|
||||
defer { manager.hideAll() }
|
||||
let domain = try makeDefaults()
|
||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||
let gate = TrainingLoadingRequestGate()
|
||||
defer { Task { await gate.release() } }
|
||||
var configuration = TrainingDataStub.Configuration()
|
||||
if scenario.selectsAnswer {
|
||||
configuration.saveHandler = { request in
|
||||
await gate.wait()
|
||||
if scenario.fails { throw URLError(.timedOut) }
|
||||
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||
savedAt: TrainingRemoteFixtures.now, answeredCount: 30)
|
||||
}
|
||||
} else {
|
||||
configuration.questionsHandler = { offset, limit in
|
||||
if offset == 10 {
|
||||
await gate.wait()
|
||||
if scenario.fails { throw URLError(.timedOut) }
|
||||
}
|
||||
return Self.questions(offset: offset, limit: limit)
|
||||
}
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
await source.seedDraft(revision: 5, answers: Dictionary(uniqueKeysWithValues: (1...30).map { ("q\($0)", ["A"]) }), lastOrder: 10)
|
||||
let model = makeModel(defaults: domain.defaults)
|
||||
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
let scope = try TrainingLoadingWindowScope(navigation)
|
||||
defer { scope.close() }
|
||||
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||
try await settleTransitions([navigation, controller])
|
||||
#expect(scope.window.isKeyWindow)
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
let action = try #require(button(scenario.selectsAnswer ? "training.option.B" : "training.exam.next", in: controller.view))
|
||||
action.sendActions(for: .touchUpInside)
|
||||
// 不让出主 actor,要求点击处理当场持有 Loading,而非等网络 Task 启动。
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
action.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { await gate.requestCount > 0 }
|
||||
#expect(model.isBusy)
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
#expect(await gate.requestCount == 1)
|
||||
#expect(await source.savedRequests.count == (scenario.selectsAnswer ? 1 : 0))
|
||||
await gate.release()
|
||||
try await waitUntil { !model.isBusy && !manager.isShowing && (scenario.fails ? model.errorMessage != nil : model.canEdit) }
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
#expect(navigation.topViewController === controller)
|
||||
if scenario.fails {
|
||||
#expect(model.errorMessage != nil)
|
||||
let retry = try #require(button("training.exam.submit", in: controller.view))
|
||||
#expect(retry.isEnabled)
|
||||
#expect(retry.title(for: .normal) == (scenario.selectsAnswer ? "重试保存" : "重试加载本题"))
|
||||
} else {
|
||||
#expect(model.currentIndex == (scenario.selectsAnswer ? 9 : 10))
|
||||
#expect(model.currentSelectedIDs == (scenario.selectsAnswer ? ["B"] : ["A"]))
|
||||
#expect(model.errorMessage == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("答题卡打开和完成关闭是本地操作,不显示 Loading 或重读任务")
|
||||
func localAnswerCardDoesNotStartRequestLoading() async throws {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.hideAll()
|
||||
defer { manager.hideAll() }
|
||||
let domain = try makeDefaults()
|
||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||
let source = TrainingDataStub()
|
||||
await source.seedDraft(revision: 3, answers: ["q10": ["B"]], lastOrder: 10)
|
||||
let model = makeModel(defaults: domain.defaults)
|
||||
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
let scope = try TrainingLoadingWindowScope(navigation)
|
||||
defer { scope.close() }
|
||||
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||
try await settleTransitions([navigation, controller])
|
||||
let before = await source.calls
|
||||
let answerCard = try #require(controller.navigationItem.rightBarButtonItem)
|
||||
try activate(answerCard)
|
||||
#expect(!manager.isShowing)
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
try await waitUntil { controller.presentedViewController is UINavigationController }
|
||||
let presented = try #require(controller.presentedViewController as? UINavigationController)
|
||||
try await settleTransitions([controller, presented])
|
||||
#expect(!manager.isShowing)
|
||||
let card = try #require(presented.topViewController as? TrainingAnswerCardViewController)
|
||||
let done = try #require(card.navigationItem.rightBarButtonItem)
|
||||
try activate(done)
|
||||
#expect(!manager.isShowing)
|
||||
try await waitUntil { controller.presentedViewController == nil }
|
||||
try await settleTransitions([navigation, controller, presented])
|
||||
#expect(!manager.isShowing && !hasVisibleOverlay(in: scope.window))
|
||||
#expect(await source.calls == before)
|
||||
#expect(model.currentIndex == 9 && model.currentSelectedIDs == ["B"])
|
||||
}
|
||||
|
||||
@Test("离开考试页立即释放自身 Loading,旧响应不能关闭后来请求的令牌")
|
||||
func leavingExamReleasesOwnedLoadingWithoutHidingNewRequest() async throws {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.hideAll()
|
||||
defer { manager.hideAll() }
|
||||
let domain = try makeDefaults()
|
||||
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||
let gate = TrainingLoadingRequestGate()
|
||||
defer { Task { await gate.release() } }
|
||||
var configuration = TrainingDataStub.Configuration()
|
||||
configuration.saveHandler = { request in
|
||||
await gate.wait()
|
||||
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||
savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
let model = makeModel(defaults: domain.defaults)
|
||||
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
let scope = try TrainingLoadingWindowScope(navigation)
|
||||
defer { scope.close() }
|
||||
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||
try await settleTransitions([navigation, controller])
|
||||
let optionA = try #require(button("training.option.A", in: controller.view))
|
||||
optionA.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { await gate.requestCount > 0 }
|
||||
#expect(manager.isShowing)
|
||||
let covering = UIViewController()
|
||||
navigation.pushViewController(covering, animated: false)
|
||||
try await settleTransitions([navigation, controller, covering])
|
||||
#expect(!manager.isShowing)
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
#expect(model.isBusy)
|
||||
let newerToken = manager.beginRequest()
|
||||
defer { manager.endRequest(newerToken) }
|
||||
#expect(manager.isShowing && hasVisibleOverlay(in: scope.window))
|
||||
await gate.release()
|
||||
try await waitUntil { model.canEdit && model.currentSelectedIDs == ["A"] && optionA.isUserInteractionEnabled }
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
#expect(navigation.topViewController === covering)
|
||||
manager.endRequest(newerToken)
|
||||
#expect(!manager.isShowing)
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
}
|
||||
|
||||
@Test("培训列表下一页和错误重试同步展示 Loading,确认后关闭", arguments: TrainingLoadingCenterScenario.allCases)
|
||||
func centerExplicitRequestsOwnLoading(scenario: TrainingLoadingCenterScenario) async throws {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.hideAll()
|
||||
defer { manager.hideAll() }
|
||||
let gate = TrainingLoadingRequestGate()
|
||||
defer { Task { await gate.release() } }
|
||||
var configuration = TrainingDataStub.Configuration()
|
||||
configuration.attemptsHandler = { _, _, cursor in
|
||||
if scenario == .retry { throw URLError(.timedOut) }
|
||||
if cursor != nil { await gate.wait() }
|
||||
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt(id: cursor == nil ? "first" : "second")],
|
||||
nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil)
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
let controller = TrainingCenterViewController(service: source, showsHistory: true)
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
let scope = try TrainingLoadingWindowScope(navigation)
|
||||
defer { scope.close() }
|
||||
let identifier = scenario == .nextPage ? "training.center.more" : "training.center.retry"
|
||||
let title = scenario == .nextPage ? "加载更多" : "重新加载"
|
||||
try await waitUntil {
|
||||
!manager.isShowing && self.centerButton(identifier: identifier, title: title, in: controller.view).map { !$0.isHidden && $0.isEnabled } == true
|
||||
}
|
||||
try await settleTransitions([navigation, controller])
|
||||
let action = try #require(centerButton(identifier: identifier, title: title, in: controller.view))
|
||||
let table = try #require(allViews(controller.view).first { $0 is UITableView } as? UITableView)
|
||||
let statistics = try statisticLabels(in: controller.view)
|
||||
let initialStatistics = statistics.map(\.text)
|
||||
if scenario == .retry {
|
||||
#expect(rowCount(in: table) == 0)
|
||||
await source.configure {
|
||||
$0.attemptsHandler = { _, _, _ in
|
||||
await gate.wait()
|
||||
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt(id: "recovered")], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
#expect(rowCount(in: table) == 1)
|
||||
#expect(initialStatistics == ["1", "0", "—"])
|
||||
}
|
||||
action.sendActions(for: .touchUpInside)
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
try await waitUntil { await gate.requestCount > 0 }
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
if scenario == .nextPage {
|
||||
#expect(rowCount(in: table) == 1)
|
||||
#expect(statistics.map(\.text) == initialStatistics)
|
||||
}
|
||||
await gate.release()
|
||||
try await waitUntil { !manager.isShowing && self.rowCount(in: table) == (scenario == .nextPage ? 2 : 1) }
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
#expect(statistics.map(\.text) == ["1", "0", "—"])
|
||||
#expect(navigation.topViewController === controller)
|
||||
let requests = await source.calls.filter { $0.name == "attempts" }
|
||||
#expect(requests.count == 2)
|
||||
let expectedCursors: [String?] = scenario == .nextPage ? [nil, "next"] : [nil, nil]
|
||||
#expect(requests.map(\.cursor) == expectedCursors)
|
||||
#expect(await gate.requestCount == 1)
|
||||
}
|
||||
|
||||
@Test("切换列表按钮取消旧搜索防抖,不重发记录请求或提前关闭 Loading")
|
||||
func centerTabRequestCancelsPendingSearchDebounce() async throws {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.hideAll()
|
||||
defer { manager.hideAll() }
|
||||
let gate = TrainingLoadingRequestGate()
|
||||
defer { Task { await gate.release() } }
|
||||
var configuration = TrainingDataStub.Configuration()
|
||||
configuration.attemptsHandler = { _, _, _ in
|
||||
await gate.wait()
|
||||
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt(id: "records_target")],
|
||||
nextCursor: nil, hasMore: false, serverTime: nil)
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
let controller = TrainingCenterViewController(service: source)
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
let scope = try TrainingLoadingWindowScope(navigation)
|
||||
defer { scope.close() }
|
||||
let table = try #require(allViews(controller.view).first { $0 is UITableView } as? UITableView)
|
||||
try await waitUntil { !manager.isShowing && self.rowCount(in: table) == 1 }
|
||||
controller.selectTab(.tasks)
|
||||
let search = try #require(allViews(controller.view).compactMap { $0 as? UITextField }.first {
|
||||
$0.accessibilityIdentifier == "training.search"
|
||||
})
|
||||
try await waitUntil { !manager.isShowing && !search.isHidden && self.rowCount(in: table) == 1 }
|
||||
try await settleTransitions([navigation, controller])
|
||||
let taskCallsBefore = await source.calls.filter { $0.name == "tasks" }
|
||||
#expect(await source.calls.filter { $0.name == "attempts" }.isEmpty)
|
||||
|
||||
search.text = "服务"
|
||||
search.sendActions(for: .editingChanged)
|
||||
#expect(!manager.isShowing)
|
||||
// 仍在同一主 actor 回合内,按钮请求必须取消刚安排的 300ms 搜索任务。
|
||||
controller.selectTab(.records)
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
try await waitUntil { await gate.requestCount > 0 }
|
||||
// 此处只等待超过真实防抖期限,响应始终由 gate 控制,不能提前结束请求。
|
||||
try await Task.sleep(for: .milliseconds(450))
|
||||
#expect(manager.isShowing)
|
||||
#expect(hasVisibleOverlay(in: scope.window))
|
||||
#expect(await gate.requestCount == 1)
|
||||
#expect(await source.calls.filter { $0.name == "attempts" }.count == 1)
|
||||
#expect(await source.calls.filter { $0.name == "tasks" } == taskCallsBefore)
|
||||
await gate.release()
|
||||
try await waitUntil { !manager.isShowing && self.rowCount(in: table) == 1 }
|
||||
#expect(!hasVisibleOverlay(in: scope.window))
|
||||
#expect(button("training.tab.2", in: controller.view)?.accessibilityTraits.contains(.selected) == true)
|
||||
#expect(await source.calls.filter { $0.name == "attempts" }.count == 1)
|
||||
#expect(navigation.topViewController === controller)
|
||||
}
|
||||
|
||||
private nonisolated static func questions(offset: Int, limit: Int) -> TrainingQuestionPage {
|
||||
let end = min(30, offset + limit)
|
||||
let items: [TrainingQuestionItem] = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : []
|
||||
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset,
|
||||
nextOffset: end < 30 ? end : nil, hasMore: end < 30, items: items)
|
||||
}
|
||||
|
||||
private func makeDefaults() throws -> (name: String, defaults: UserDefaults) {
|
||||
let name = "TrainingRequestLoadingTests-\(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 hasVisibleOverlay(in window: UIWindow) -> Bool {
|
||||
window.subviews.contains { $0 is GlobalLoadingOverlayView && !$0.isHidden }
|
||||
}
|
||||
|
||||
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 centerButton(identifier: String, title: String, in view: UIView) -> UIButton? {
|
||||
button(identifier, in: view) ?? allViews(view).compactMap { $0 as? UIButton }.first {
|
||||
($0.configuration?.title ?? $0.title(for: .normal)) == title
|
||||
}
|
||||
}
|
||||
|
||||
private func rowCount(in table: UITableView) -> Int {
|
||||
table.numberOfSections > 0 ? table.numberOfRows(inSection: 0) : 0
|
||||
}
|
||||
|
||||
private func statisticLabels(in view: UIView) throws -> [UILabel] {
|
||||
let labels = allViews(view).compactMap { $0 as? UILabel }
|
||||
return try ["待考试", "已完成", "最近得分"].map { title in
|
||||
let caption = try #require(labels.first { $0.text == title })
|
||||
let column = try #require(caption.superview as? UIStackView)
|
||||
return try #require(column.arrangedSubviews.compactMap { $0 as? UILabel }.first { $0 !== caption })
|
||||
}
|
||||
}
|
||||
|
||||
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 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user