import Foundation import Testing import UIKit @testable import suixinkan /// 可控挂起成绩或解析请求,验证通用 Loading 覆盖真实等待区间。 private actor TrainingResultLoadingGate { private var continuations: [CheckedContinuation] = [] 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() } }