354 lines
19 KiB
Swift
354 lines
19 KiB
Swift
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() }
|
|
}
|
|
}
|