feat(training): 为请求操作接入通用Loading
This commit is contained in:
@@ -51,4 +51,48 @@ final class GlobalLoadingManagerTests: XCTestCase {
|
||||
manager.hide()
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
|
||||
/// 清理旧请求后,旧响应的释放不能关闭新请求或普通 show 持有的 Loading。
|
||||
func testStaleRequestTokenDoesNotHideNewLoading() {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
let previous = manager.beginRequest()
|
||||
manager.hideAll()
|
||||
let current = manager.beginRequest()
|
||||
manager.endRequest(previous)
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.endRequest(current)
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
manager.show()
|
||||
manager.endRequest(current)
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.hide()
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
|
||||
/// 请求令牌与已有 show/hide 引用计数可以共存,重复结束不影响其它持有者。
|
||||
func testRequestTokensRespectOtherLoadingOwners() {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.show()
|
||||
let first = manager.beginRequest()
|
||||
let second = manager.beginRequest()
|
||||
manager.endRequest(first)
|
||||
manager.endRequest(first)
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.hide()
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.endRequest(second)
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
|
||||
/// 旧普通请求在全局清理后的迟到 hide 不能抵消新培训请求的独立票据。
|
||||
func testLateLegacyHideCannotEndRequestToken() {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.show()
|
||||
manager.hideAll()
|
||||
let current = manager.beginRequest()
|
||||
manager.hide()
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.endRequest(current)
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
import SafariServices
|
||||
import UIKit
|
||||
import WebKit
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 明确挂起响应,验证等待期间的进度与重复点击,而不依赖固定网络延时。
|
||||
private actor TrainingCourseLoadingGate {
|
||||
private var continuations: [CheckedContinuation<Void, Never>] = []
|
||||
private var released = false
|
||||
private(set) var requestCount = 0
|
||||
|
||||
/// 所有意外并发请求分别等待,方便断言请求数量。
|
||||
func wait() async {
|
||||
requestCount += 1
|
||||
guard !released else { return }
|
||||
await withCheckedContinuation { continuations.append($0) }
|
||||
}
|
||||
|
||||
/// 释放所有挂起响应,测试失败时也不会遗留 continuation。
|
||||
func release() {
|
||||
released = true
|
||||
let pending = continuations
|
||||
continuations = []
|
||||
pending.forEach { $0.resume() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 真机课程请求交互:用户动作显示全局进度,缓存与自动读时不显示。
|
||||
@MainActor
|
||||
final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
private var previousKeyWindow: UIWindow?
|
||||
|
||||
override func tearDown() {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
/// 首次失败释放进度;主动重试保持按钮外观,快速重复点击不重复请求。
|
||||
func testColdLoadFailureAndButtonRetryReleaseLoading() async throws {
|
||||
let first = TrainingCourseLoadingGate()
|
||||
let retry = TrainingCourseLoadingGate()
|
||||
defer { Task { await first.release(); await retry.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure {
|
||||
$0.taskHandler = { _ in await first.wait(); throw URLError(.timedOut) }
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { await first.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
await first.release()
|
||||
let action = try button("training.reading.action", in: controller.view)
|
||||
try await waitUntil { action.isEnabled && action.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing }
|
||||
await source.configure {
|
||||
$0.taskHandler = { _ in await retry.wait(); return TrainingRemoteFixtures.detail() }
|
||||
}
|
||||
let appearance = (action.isEnabled, action.alpha, action.configuration?.baseBackgroundColor)
|
||||
action.sendActions(for: .touchUpInside)
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
XCTAssertEqual(action.isEnabled, appearance.0)
|
||||
XCTAssertEqual(action.alpha, appearance.1)
|
||||
XCTAssertEqual(action.configuration?.baseBackgroundColor, appearance.2)
|
||||
XCTAssertFalse(action.isUserInteractionEnabled)
|
||||
action.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { await retry.requestCount == 1 }
|
||||
let calls = await source.calls
|
||||
XCTAssertEqual(calls.filter { $0.name == "task" }.count, 2)
|
||||
await retry.release()
|
||||
try await waitUntil { self.isReady(controller) }
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
}
|
||||
|
||||
/// 目录分页和未缓存正文显示进度;缓存切换无额外正文请求或进度闪烁。
|
||||
func testDirectoryPaginationAndCachedSectionReuse() async throws {
|
||||
let page = TrainingCourseLoadingGate()
|
||||
let body = TrainingCourseLoadingGate()
|
||||
defer { Task { await page.release(); await body.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure {
|
||||
$0.sectionsHandler = { cursor in
|
||||
if cursor != nil {
|
||||
await page.wait()
|
||||
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s3", order: 3, title: "后续小节")], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||
}
|
||||
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s1", order: 1, title: "首节"), TrainingSectionInfo(id: "s2", order: 2, title: "第二节")], nextCursor: "next", hasMore: true, serverTime: nil)
|
||||
}
|
||||
$0.sectionHandler = { id in
|
||||
if id == "s2" { await body.wait() }
|
||||
return TrainingSectionContent(id: id, order: id == "s1" ? 1 : 2, title: id, contentHTML: "<p>\(id)</p>")
|
||||
}
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { self.isReady(controller) }
|
||||
let picker = try await openPicker("training.reading.sections", controller: controller, rows: 3)
|
||||
selectRow(2, in: picker.table)
|
||||
selectRow(2, in: picker.table)
|
||||
try await waitUntil { await page.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
await page.release()
|
||||
try await waitUntil { self.rowTitle(2, in: picker.table) == "3. 后续小节" && !GlobalLoadingManager.shared.isShowing }
|
||||
selectRow(1, in: picker.table)
|
||||
try await waitUntil { await body.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
await body.release()
|
||||
try await waitUntil { self.isReady(controller) && controller.presentedViewController == nil }
|
||||
let cached = try await openPicker("training.reading.sections", controller: controller, rows: 3)
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
selectRow(0, in: cached.table)
|
||||
try await waitUntil { controller.presentedViewController == nil && self.isReady(controller) }
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
let calls = await source.calls
|
||||
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 2)
|
||||
XCTAssertEqual(calls.filter { $0.name == "sections" && $0.cursor == "next" }.count, 1)
|
||||
}
|
||||
|
||||
/// 附件第一页、下一页和授权请求显示进度,复用目录及呈现 Safari 前已释放进度。
|
||||
func testAttachmentLoadingPaginationReuseAndAuthorization() async throws {
|
||||
let first = TrainingCourseLoadingGate()
|
||||
let next = TrainingCourseLoadingGate()
|
||||
let authorization = TrainingCourseLoadingGate()
|
||||
defer { Task { await first.release(); await next.release(); await authorization.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure {
|
||||
$0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 2, attachmentCount: 2) }
|
||||
$0.attachmentsHandler = { cursor in
|
||||
if cursor == nil { await first.wait() } else { await next.wait() }
|
||||
let id = cursor == nil ? "a1" : "a2"
|
||||
let item = TrainingAttachmentInfo(id: id, name: id, mimeType: "application/pdf", sizeBytes: 120,
|
||||
fileID: id, downloadURL: nil, expiresAt: nil)
|
||||
return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil)
|
||||
}
|
||||
$0.attachmentURLHandler = { id in
|
||||
await authorization.wait()
|
||||
return TrainingAttachmentLink(id: id, name: id, url: URL(string: "https://example.test/training.pdf")!, expiresAt: Date().addingTimeInterval(60))
|
||||
}
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { self.isReady(controller) }
|
||||
let attachments = try button("training.reading.attachments", in: controller.view)
|
||||
attachments.sendActions(for: .touchUpInside)
|
||||
attachments.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { await first.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
XCTAssertTrue(attachments.isEnabled)
|
||||
await first.release()
|
||||
let picker = try await currentPicker(controller, rows: 2)
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
selectRow(1, in: picker.table)
|
||||
try await waitUntil { await next.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
await next.release()
|
||||
try await waitUntil { self.rowTitle(1, in: picker.table) == "a2" && !GlobalLoadingManager.shared.isShowing }
|
||||
try activate(try XCTUnwrap(picker.navigation.topViewController?.navigationItem.rightBarButtonItem))
|
||||
try await waitUntil { controller.presentedViewController == nil && self.isReady(controller) }
|
||||
attachments.sendActions(for: .touchUpInside)
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
let reused = try await currentPicker(controller, rows: 2)
|
||||
let calls = await source.calls
|
||||
XCTAssertEqual(calls.filter { $0.name == "attachments" }.count, 2)
|
||||
selectRow(0, in: reused.table)
|
||||
try await waitUntil { await authorization.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
await authorization.release()
|
||||
try await waitUntil { controller.presentedViewController is SFSafariViewController }
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
}
|
||||
|
||||
/// 离页取消请求后清理原票据,迟到响应不能隐藏其它请求,返回会补载并渲染原选中正文。
|
||||
func testLeavingAndReturningRestoresCanceledSectionWithoutEndingOtherLoading() async throws {
|
||||
let body = TrainingCourseLoadingGate()
|
||||
defer { Task { await body.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure {
|
||||
$0.sectionHandler = { id in
|
||||
if id == "s2" { await body.wait() }
|
||||
return TrainingSectionContent(id: id, order: id == "s1" ? 1 : 2, title: id, contentHTML: "<p>visible-\(id)</p>")
|
||||
}
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { self.isReady(controller) }
|
||||
let picker = try await openPicker("training.reading.sections", controller: controller, rows: 2)
|
||||
selectRow(1, in: picker.table)
|
||||
try await waitUntil { await body.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
let navigation = try XCTUnwrap(controller.navigationController)
|
||||
try await waitUntil {
|
||||
controller.presentedViewController == nil && controller.transitionCoordinator == nil
|
||||
&& navigation.transitionCoordinator == nil && !picker.navigation.isBeingDismissed
|
||||
&& picker.navigation.transitionCoordinator == nil
|
||||
}
|
||||
let destination = UIViewController()
|
||||
navigation.pushViewController(destination, animated: false)
|
||||
// 正文响应仍被 gate 挂起;这里只等待 UIKit 完成真实离页与页面票据释放。
|
||||
try await waitUntil {
|
||||
navigation.topViewController === destination && destination.view.window === window
|
||||
&& navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil
|
||||
&& !GlobalLoadingManager.shared.isShowing
|
||||
}
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
let other = GlobalLoadingManager.shared.beginRequest()
|
||||
defer { GlobalLoadingManager.shared.endRequest(other) }
|
||||
await body.release()
|
||||
try await waitUntil { self.allViews(controller.view).compactMap { $0 as? UIButton }.allSatisfy { $0.isUserInteractionEnabled } }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
GlobalLoadingManager.shared.endRequest(other)
|
||||
navigation.popViewController(animated: false)
|
||||
try await waitUntil {
|
||||
navigation.topViewController === controller && controller.view.window === window
|
||||
&& navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil
|
||||
}
|
||||
let webView = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? WKWebView }.first)
|
||||
try await waitUntil {
|
||||
guard self.isReady(controller), !webView.isLoading else { return false }
|
||||
let text = try? await webView.evaluateJavaScript("document.body.textContent") as? String
|
||||
return text?.contains("visible-s2") == true
|
||||
}
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
let calls = await source.calls
|
||||
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 3)
|
||||
}
|
||||
|
||||
/// 正文就绪后的自动会话、暂停保存与恢复不显示进度,只有用户重试失败会话显示。
|
||||
func testReadingRetryShowsLoadingAndAutomaticSessionRequestsDoNot() async throws {
|
||||
let initial = TrainingCourseLoadingGate()
|
||||
let retry = TrainingCourseLoadingGate()
|
||||
let automatic = TrainingCourseLoadingGate()
|
||||
defer { Task { await initial.release(); await retry.release(); await automatic.release() } }
|
||||
var configuration = TrainingDataStub.Configuration()
|
||||
configuration.readingSeconds = 0
|
||||
configuration.startReadingHandler = { _ in
|
||||
await initial.wait()
|
||||
throw URLError(.timedOut)
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { await initial.requestCount == 1 }
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
await initial.release()
|
||||
let action = try button("training.reading.action", in: controller.view)
|
||||
try await waitUntil { action.isEnabled && action.configuration?.title == "重试保存并继续学习" }
|
||||
await source.configure {
|
||||
$0.startReadingHandler = { requestID in
|
||||
await retry.wait()
|
||||
return TrainingStudySession(sessionID: requestID, expiresAt: Date().addingTimeInterval(60), heartbeatIntervalSeconds: 5,
|
||||
maxHeartbeatGapSeconds: 15, progress: TrainingRemoteFixtures.progress(seconds: 0))
|
||||
}
|
||||
}
|
||||
action.sendActions(for: .touchUpInside)
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
XCTAssertTrue(action.isEnabled)
|
||||
action.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { await retry.requestCount == 1 }
|
||||
await retry.release()
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && !action.isEnabled && action.isUserInteractionEnabled }
|
||||
await source.configure {
|
||||
$0.startReadingHandler = { requestID in
|
||||
await automatic.wait()
|
||||
return TrainingStudySession(sessionID: requestID, expiresAt: Date().addingTimeInterval(60), heartbeatIntervalSeconds: 5,
|
||||
maxHeartbeatGapSeconds: 15, progress: TrainingRemoteFixtures.progress(seconds: 0))
|
||||
}
|
||||
}
|
||||
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||
try await waitUntil { await source.heartbeats.contains { $0.final } }
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
try await waitUntil { await automatic.requestCount == 1 }
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
await automatic.release()
|
||||
}
|
||||
|
||||
private func makeWindow(_ controller: TrainingCourseViewController) throws -> UIWindow {
|
||||
let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
|
||||
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
|
||||
let window = UIWindow(windowScene: scene)
|
||||
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
window.rootViewController = navigation
|
||||
window.makeKeyAndVisible()
|
||||
navigation.view.layoutIfNeeded()
|
||||
return window
|
||||
}
|
||||
|
||||
private func closeWindow(_ window: UIWindow, controller: TrainingCourseViewController) {
|
||||
controller.presentedViewController?.dismiss(animated: false)
|
||||
window.isHidden = true
|
||||
window.rootViewController = nil
|
||||
previousKeyWindow?.makeKey()
|
||||
previousKeyWindow = nil
|
||||
}
|
||||
|
||||
private func isReady(_ controller: TrainingCourseViewController) -> Bool {
|
||||
guard let sections = try? button("training.reading.sections", in: controller.view) else { return false }
|
||||
return sections.isEnabled && sections.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing
|
||||
}
|
||||
|
||||
private func openPicker(_ identifier: String, controller: TrainingCourseViewController, rows: Int) async throws -> (navigation: UINavigationController, table: UITableView) {
|
||||
try button(identifier, in: controller.view).sendActions(for: .touchUpInside)
|
||||
return try await currentPicker(controller, rows: rows)
|
||||
}
|
||||
|
||||
private func currentPicker(_ controller: TrainingCourseViewController, rows: Int) async throws -> (navigation: UINavigationController, table: UITableView) {
|
||||
try await waitUntil {
|
||||
guard let navigation = controller.presentedViewController as? UINavigationController,
|
||||
let picker = navigation.topViewController,
|
||||
!navigation.isBeingPresented, picker.transitionCoordinator == nil,
|
||||
let table = self.allViews(picker.view).compactMap({ $0 as? UITableView }).first else { return false }
|
||||
return table.numberOfRows(inSection: 0) == rows
|
||||
}
|
||||
let navigation = try XCTUnwrap(controller.presentedViewController as? UINavigationController)
|
||||
let picker = try XCTUnwrap(navigation.topViewController)
|
||||
let table = try XCTUnwrap(allViews(picker.view).compactMap { $0 as? UITableView }.first)
|
||||
return (navigation, table)
|
||||
}
|
||||
|
||||
private func selectRow(_ index: Int, in table: UITableView) {
|
||||
table.delegate?.tableView?(table, didSelectRowAt: IndexPath(row: index, section: 0))
|
||||
}
|
||||
|
||||
private func rowTitle(_ index: Int, in table: UITableView) -> String? {
|
||||
(table.cellForRow(at: IndexPath(row: index, section: 0))?.contentConfiguration as? UIListContentConfiguration)?.text
|
||||
}
|
||||
|
||||
private func activate(_ item: UIBarButtonItem) throws {
|
||||
let action = try XCTUnwrap(item.primaryAction)
|
||||
let dispatcher = UIButton(type: .system)
|
||||
dispatcher.addAction(action, for: .touchUpInside)
|
||||
dispatcher.sendActions(for: .touchUpInside)
|
||||
}
|
||||
|
||||
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } }
|
||||
|
||||
private func button(_ identifier: String, in view: UIView) throws -> UIButton {
|
||||
try XCTUnwrap(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(5))
|
||||
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||
let reached = await condition()
|
||||
XCTAssertTrue(reached, "未在期限内进入预期 UI / 请求状态")
|
||||
guard reached else { throw CancellationError() }
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ actor TrainingDataStub: TrainingDataServing {
|
||||
var sectionsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingSectionInfo>)?
|
||||
var sectionHandler: (@Sendable (String) async throws -> TrainingSectionContent)?
|
||||
var attachmentsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingAttachmentInfo>)?
|
||||
var attachmentURLHandler: (@Sendable (String) async throws -> TrainingAttachmentLink)?
|
||||
var startReadingHandler: (@Sendable (String) async throws -> TrainingStudySession)?
|
||||
var heartbeatHandler: (@Sendable (HeartbeatCall) async throws -> TrainingHeartbeatConfirmation)?
|
||||
var questionsHandler: (@Sendable (Int, Int) async throws -> TrainingQuestionPage)?
|
||||
@@ -151,6 +152,7 @@ actor TrainingDataStub: TrainingDataServing {
|
||||
/// 返回用于 Safari 的授权 HTTPS URL。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
||||
calls.append(Call(name: "attachmentURL", taskID: taskID))
|
||||
if let handler = configuration.attachmentURLHandler { return try await handler(attachmentID) }
|
||||
return TrainingAttachmentLink(id: attachmentID, name: "培训附件", url: URL(string: "https://example.test/training.pdf")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))
|
||||
}
|
||||
/// 只返回权威读时。
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UIKit
|
||||
@testable import suixinkan
|
||||
|
||||
/// 可控挂起成绩或解析请求,验证通用 Loading 覆盖真实等待区间。
|
||||
private actor TrainingResultLoadingGate {
|
||||
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、缓存及重试。
|
||||
@Suite("培训成绩请求 Loading", .serialized)
|
||||
@MainActor
|
||||
struct TrainingResultRequestLoadingTests {
|
||||
@Test("成绩重载合并请求,等待期间展示通用 Loading 且按钮外观不变")
|
||||
func reloadOwnsOneLoadingTokenAndKeepsButtonEnabled() async throws {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
defer { GlobalLoadingManager.shared.hideAll() }
|
||||
let gate = TrainingResultLoadingGate()
|
||||
defer { Task { await gate.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure { $0.attemptHandler = { _ in
|
||||
await gate.wait()
|
||||
return TrainingRemoteFixtures.result()
|
||||
} }
|
||||
let controller = makeController(source: source)
|
||||
controller.loadViewIfNeeded()
|
||||
let action = try #require(button("training.result.action", in: controller.view))
|
||||
let background = action.configuration?.baseBackgroundColor
|
||||
let foreground = action.configuration?.baseForegroundColor
|
||||
let request = Task { @MainActor in await controller.reload() }
|
||||
try await waitForGate(gate)
|
||||
let scene = try TrainingResultLoadingWindow(controller)
|
||||
defer { scene.close() }
|
||||
let joined = Task { @MainActor in await controller.reload() }
|
||||
action.sendActions(for: .touchUpInside)
|
||||
await Task.yield()
|
||||
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
#expect(action.isEnabled)
|
||||
#expect(!action.isUserInteractionEnabled)
|
||||
#expect(action.configuration?.baseBackgroundColor == background)
|
||||
#expect(action.configuration?.baseForegroundColor == foreground)
|
||||
#expect(await source.calls.filter { $0.name == "attempt" }.count == 1)
|
||||
#expect(await gate.requestCount == 1)
|
||||
|
||||
await gate.release()
|
||||
await request.value
|
||||
await joined.value
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && action.isUserInteractionEnabled }
|
||||
#expect(action.isEnabled)
|
||||
#expect(hasLabel("100", in: controller.view))
|
||||
}
|
||||
|
||||
@Test("成绩请求失败或取消后释放 Loading,按钮重试仍持有 Loading", arguments: [false, true])
|
||||
func summaryFailureCanRetryWithLoading(cancelled: Bool) async throws {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
defer { GlobalLoadingManager.shared.hideAll() }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure { $0.attemptHandler = { _ in
|
||||
if cancelled { throw CancellationError() }
|
||||
throw APIError.networkFailed("成绩查询离线")
|
||||
} }
|
||||
let controller = makeController(source: source)
|
||||
let scene = try TrainingResultLoadingWindow(controller)
|
||||
defer { scene.close() }
|
||||
try await waitUntil { self.button("training.result.action", in: controller.view)?.configuration?.title == "重新加载" }
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
let gate = TrainingResultLoadingGate()
|
||||
defer { Task { await gate.release() } }
|
||||
await source.configure { $0.attemptHandler = { _ in
|
||||
await gate.wait()
|
||||
return TrainingRemoteFixtures.result()
|
||||
} }
|
||||
let retry = try #require(button("training.result.action", in: controller.view))
|
||||
retry.sendActions(for: .touchUpInside)
|
||||
retry.sendActions(for: .touchUpInside)
|
||||
try await waitForGate(gate)
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
#expect(retry.isEnabled && !retry.isUserInteractionEnabled)
|
||||
#expect(await source.calls.filter { $0.name == "attempt" }.count == 2)
|
||||
await gate.release()
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel("100", in: controller.view) }
|
||||
#expect(retry.isUserInteractionEnabled)
|
||||
}
|
||||
|
||||
@Test("首次展开解析展示 Loading,交卷摘要和缓存展开收起均不请求或闪 Loading")
|
||||
func firstReviewsShowLoadingAndCachedTogglesDoNot() async throws {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
defer { GlobalLoadingManager.shared.hideAll() }
|
||||
let gate = TrainingResultLoadingGate()
|
||||
defer { Task { await gate.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure { $0.reviewsHandler = { _ in
|
||||
await gate.wait()
|
||||
return TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: nil, hasMore: false)
|
||||
} }
|
||||
let controller = makeController(source: source, initial: TrainingRemoteFixtures.result())
|
||||
let scene = try TrainingResultLoadingWindow(controller)
|
||||
defer { scene.close() }
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
#expect(await source.calls.isEmpty)
|
||||
let details = try #require(button("training.result.details", in: controller.view))
|
||||
details.sendActions(for: .touchUpInside)
|
||||
let waitingDetails = try #require(button("training.result.details", in: controller.view))
|
||||
waitingDetails.sendActions(for: .touchUpInside)
|
||||
try await waitForGate(gate)
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
#expect(waitingDetails.isEnabled)
|
||||
#expect(await source.calls.filter { $0.name == "reviews" }.count == 1)
|
||||
await gate.release()
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view) }
|
||||
|
||||
let collapse = try #require(button("training.result.details", in: controller.view))
|
||||
collapse.sendActions(for: .touchUpInside)
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
#expect(!hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view))
|
||||
let reopen = try #require(button("training.result.details", in: controller.view))
|
||||
reopen.sendActions(for: .touchUpInside)
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
#expect(hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view))
|
||||
await Task.yield()
|
||||
#expect(await source.calls.filter { $0.name == "reviews" }.count == 1)
|
||||
#expect(await source.calls.filter { $0.name == "attempt" }.isEmpty)
|
||||
}
|
||||
|
||||
@Test("解析首次失败可重试,成绩保持显示且 Loading 按请求结束")
|
||||
func firstReviewFailureRetriesWithLoading() async throws {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
defer { GlobalLoadingManager.shared.hideAll() }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure { $0.reviewsHandler = { _ in throw APIError.networkFailed("解析离线") } }
|
||||
let controller = makeController(source: source, initial: TrainingRemoteFixtures.result())
|
||||
let scene = try TrainingResultLoadingWindow(controller)
|
||||
defer { scene.close() }
|
||||
let details = try #require(button("training.result.details", in: controller.view))
|
||||
details.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { self.button("training.result.reviews.more", in: controller.view)?.configuration?.title == "重试加载解析" }
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
#expect(hasLabel("100", in: controller.view))
|
||||
let gate = TrainingResultLoadingGate()
|
||||
defer { Task { await gate.release() } }
|
||||
await source.configure { $0.reviewsHandler = { cursor in
|
||||
#expect(cursor == nil)
|
||||
await gate.wait()
|
||||
return TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: nil, hasMore: false)
|
||||
} }
|
||||
let retry = try #require(button("training.result.reviews.more", in: controller.view))
|
||||
retry.sendActions(for: .touchUpInside)
|
||||
retry.sendActions(for: .touchUpInside)
|
||||
try await waitForGate(gate)
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
#expect(retry.isEnabled)
|
||||
#expect(await source.calls.filter { $0.name == "reviews" }.count == 2)
|
||||
await gate.release()
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view) }
|
||||
#expect(button("training.result.reviews.more", in: controller.view) == nil)
|
||||
}
|
||||
|
||||
@Test("解析下一页失败和重试使用同一游标,各请求分别释放 Loading")
|
||||
func nextReviewPageFailureRetriesSameCursor() async throws {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
defer { GlobalLoadingManager.shared.hideAll() }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure { $0.reviewsHandler = { _ in
|
||||
TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: "next", hasMore: true)
|
||||
} }
|
||||
let controller = makeController(source: source, initial: TrainingRemoteFixtures.result())
|
||||
let scene = try TrainingResultLoadingWindow(controller)
|
||||
defer { scene.close() }
|
||||
let details = try #require(button("training.result.details", in: controller.view))
|
||||
details.sendActions(for: .touchUpInside)
|
||||
try await waitUntil { self.button("training.result.reviews.more", in: controller.view) != nil && !GlobalLoadingManager.shared.isShowing }
|
||||
let failureGate = TrainingResultLoadingGate()
|
||||
defer { Task { await failureGate.release() } }
|
||||
await source.configure { $0.reviewsHandler = { cursor in
|
||||
#expect(cursor == "next")
|
||||
await failureGate.wait()
|
||||
throw APIError.networkFailed("下一页离线")
|
||||
} }
|
||||
let more = try #require(button("training.result.reviews.more", in: controller.view))
|
||||
more.sendActions(for: .touchUpInside)
|
||||
try await waitForGate(failureGate)
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
await failureGate.release()
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.button("training.result.reviews.more", in: controller.view)?.configuration?.title == "重试加载解析" }
|
||||
#expect(hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view))
|
||||
let retryGate = TrainingResultLoadingGate()
|
||||
defer { Task { await retryGate.release() } }
|
||||
await source.configure { $0.reviewsHandler = { cursor in
|
||||
#expect(cursor == "next")
|
||||
await retryGate.wait()
|
||||
return TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review(2)], nextCursor: nil, hasMore: false)
|
||||
} }
|
||||
let retry = try #require(button("training.result.reviews.more", in: controller.view))
|
||||
retry.sendActions(for: .touchUpInside)
|
||||
try await waitForGate(retryGate)
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
await retryGate.release()
|
||||
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel(TrainingRemoteFixtures.review(2).stem, in: controller.view) }
|
||||
let calls = await source.calls.filter { $0.name == "reviews" }
|
||||
#expect(calls.map(\.cursor) == [nil, "next", "next"])
|
||||
}
|
||||
|
||||
@Test("离开成绩页或 hideAll 后,旧请求结束不关闭其它请求 Loading", arguments: [false, true])
|
||||
func leavingOrResettingLoadingCannotHideNewRequest(resetAll: Bool) async throws {
|
||||
GlobalLoadingManager.shared.hideAll()
|
||||
defer { GlobalLoadingManager.shared.hideAll() }
|
||||
let gate = TrainingResultLoadingGate()
|
||||
defer { Task { await gate.release() } }
|
||||
let source = TrainingDataStub()
|
||||
await source.configure { $0.attemptHandler = { _ in
|
||||
await gate.wait()
|
||||
return TrainingRemoteFixtures.result()
|
||||
} }
|
||||
let controller = makeController(source: source)
|
||||
let root = TrainingResultLoadingAppearanceController()
|
||||
let navigation = TrainingResultLoadingNavigationController(rootViewController: root)
|
||||
navigation.setViewControllers([root, controller], animated: false)
|
||||
let scene = try TrainingResultLoadingWindow(navigation: navigation)
|
||||
defer { scene.close() }
|
||||
try await waitForGate(gate)
|
||||
try await waitUntil {
|
||||
navigation.didAppear && navigation.topViewController === controller
|
||||
&& navigation.transitionCoordinator == nil
|
||||
}
|
||||
#expect(GlobalLoadingManager.shared.isShowing)
|
||||
if resetAll { GlobalLoadingManager.shared.hideAll() }
|
||||
else {
|
||||
navigation.popViewController(animated: false)
|
||||
try await waitUntil {
|
||||
root.didAppear && navigation.topViewController === root
|
||||
&& navigation.transitionCoordinator == nil
|
||||
}
|
||||
}
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
let newer = GlobalLoadingManager.shared.beginRequest()
|
||||
defer { GlobalLoadingManager.shared.endRequest(newer) }
|
||||
await gate.release()
|
||||
await controller.reload()
|
||||
#expect(GlobalLoadingManager.shared.isShowing, "旧结束回调只能归还原票据")
|
||||
GlobalLoadingManager.shared.endRequest(newer)
|
||||
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||
}
|
||||
|
||||
private func makeController(source: any TrainingDataServing, initial: TrainingAttemptDetail? = nil) -> TrainingResultViewController {
|
||||
TrainingResultViewController(taskID: "task_1", attemptID: "attempt_1", service: source, initialDetail: initial)
|
||||
}
|
||||
|
||||
private func waitForGate(_ gate: TrainingResultLoadingGate) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||
while await gate.requestCount == 0, ContinuousClock.now < deadline {
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
let count = await gate.requestCount
|
||||
try #require(count > 0)
|
||||
}
|
||||
|
||||
private func waitUntil(_ condition: () -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||
while !condition(), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||
try #require(condition())
|
||||
}
|
||||
|
||||
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap(allViews) }
|
||||
private func button(_ identifier: String, in view: UIView) -> UIButton? {
|
||||
allViews(view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == identifier }
|
||||
}
|
||||
private func hasLabel(_ text: String, in view: UIView) -> Bool {
|
||||
allViews(view).compactMap { $0 as? UILabel }.contains { $0.text == text }
|
||||
}
|
||||
}
|
||||
|
||||
/// 记录首次窗口展示已经完成,避免在导航仍进行 appearance 时立即移除请求页面。
|
||||
@MainActor
|
||||
private final class TrainingResultLoadingNavigationController: UINavigationController {
|
||||
private(set) var didAppear = false
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
didAppear = true
|
||||
}
|
||||
}
|
||||
|
||||
/// 用真实目标页面的 appearance 确认 pop 已结束,再检查离页释放的 Loading。
|
||||
@MainActor
|
||||
private final class TrainingResultLoadingAppearanceController: UIViewController {
|
||||
private(set) var didAppear = false
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
didAppear = true
|
||||
}
|
||||
}
|
||||
|
||||
/// 保留上一键窗口,关闭测试窗口时恢复,避免影响其它页面的 Loading 归属。
|
||||
@MainActor
|
||||
private final class TrainingResultLoadingWindow {
|
||||
let window: UIWindow
|
||||
private weak var previousKeyWindow: UIWindow?
|
||||
|
||||
convenience init(_ controller: UIViewController) throws {
|
||||
try self.init(navigation: UINavigationController(rootViewController: controller))
|
||||
}
|
||||
|
||||
init(navigation: UINavigationController) throws {
|
||||
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||
let scene = try #require(scenes.first { $0.activationState == .foregroundActive } ?? scenes.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.endEditing(true)
|
||||
window.isHidden = true
|
||||
window.rootViewController = nil
|
||||
previousKeyWindow?.makeKeyAndVisible()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user