feat(training): 支持课程附件预览与整页阅读
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Not a ZIP document
|
||||
@@ -0,0 +1,2 @@
|
||||
培训课程 GB18030
|
||||
中文内容正常显示。
|
||||
Binary file not shown.
@@ -0,0 +1,18 @@
|
||||
# 培训课程
|
||||
|
||||
这是 **Markdown** 附件内容。
|
||||
|
||||
- 服务规范
|
||||
- 现场安全
|
||||
|
||||
| 项目 | 要求 |
|
||||
|---|---|
|
||||
| 阅读 | 完整阅读 |
|
||||
|
||||
[外部资料](https://example.com/training)
|
||||
|
||||

|
||||
|
||||
<script>alert(1)</script>
|
||||
|
||||
[恶意链接](javascript:alert(1))
|
||||
@@ -0,0 +1,32 @@
|
||||
%PDF-1.4
|
||||
1 0 obj
|
||||
<< /Type /Catalog /Pages 2 0 R >>
|
||||
endobj
|
||||
2 0 obj
|
||||
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
|
||||
endobj
|
||||
3 0 obj
|
||||
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 440] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>
|
||||
endobj
|
||||
4 0 obj
|
||||
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
|
||||
endobj
|
||||
5 0 obj
|
||||
<< /Length 109 >>
|
||||
stream
|
||||
BT /F1 20 Tf 28 380 Td (Training Course PDF) Tj 0 -32 Td /F1 12 Tf (Read the complete course document.) Tj ET
|
||||
endstream
|
||||
endobj
|
||||
xref
|
||||
0 6
|
||||
0000000000 65535 f
|
||||
0000000009 00000 n
|
||||
0000000058 00000 n
|
||||
0000000115 00000 n
|
||||
0000000241 00000 n
|
||||
0000000311 00000 n
|
||||
trailer
|
||||
<< /Size 6 /Root 1 0 R >>
|
||||
startxref
|
||||
471
|
||||
%%EOF
|
||||
@@ -0,0 +1,4 @@
|
||||
培训课程
|
||||
这是一份 UTF-8 文本附件。
|
||||
<script>alert(1)</script>
|
||||
第二段正文。
|
||||
Binary file not shown.
@@ -1,4 +1,3 @@
|
||||
import SafariServices
|
||||
import UIKit
|
||||
import WebKit
|
||||
import XCTest
|
||||
@@ -45,7 +44,7 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
await source.configure {
|
||||
$0.taskHandler = { _ in await first.wait(); throw URLError(.timedOut) }
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { await first.requestCount == 1 }
|
||||
@@ -72,133 +71,70 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
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>")
|
||||
}
|
||||
/// 下载错误保留原生课程信息;用户重试重新授权文件并保持全局进度与防重复请求。
|
||||
func testDocumentDownloadFailureAndRetryKeepMetadataAndLoading() async throws {
|
||||
let download = TrainingCourseLoadingGate()
|
||||
let retry = TrainingCourseLoadingGate()
|
||||
defer { Task { await download.release(); await retry.release() } }
|
||||
let loader = TrainingFixtureDocumentLoader { _, _ in
|
||||
await download.wait()
|
||||
if await download.requestCount == 1 { throw URLError(.networkConnectionLost) }
|
||||
await retry.wait()
|
||||
return try TrainingDocumentTestFixtures.document()
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let source = TrainingDataStub()
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: loader)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { await download.requestCount == 1 }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
await download.release()
|
||||
let action = try button("training.reading.action", in: controller.view)
|
||||
try await waitUntil { action.isEnabled && action.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing }
|
||||
XCTAssertEqual(action.configuration?.title, "重新加载附件")
|
||||
let labels = allViews(controller.view).compactMap { $0 as? UILabel }
|
||||
XCTAssertEqual(labels.first { $0.accessibilityIdentifier == "training.reading.taskTitle" }?.text, "一线服务规范学习")
|
||||
XCTAssertEqual(labels.first { $0.accessibilityIdentifier == "training.reading.courseName" }?.text, "景区服务规范")
|
||||
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 pendingCalls = await source.calls
|
||||
XCTAssertEqual(pendingCalls.filter { $0.name == "attachmentURL" }.count, 2)
|
||||
XCTAssertEqual(pendingCalls.filter { $0.name == "task" }.count, 1)
|
||||
await retry.release()
|
||||
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)
|
||||
let downloadCount = await download.requestCount
|
||||
XCTAssertEqual(downloadCount, 2)
|
||||
}
|
||||
|
||||
/// HTTP 附件分页和授权显示进度,复用目录及呈现 Safari 前已释放进度。
|
||||
func testHTTPAttachmentLoadingPaginationReuseAndAuthorization() 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: "http://example.test/training.pdf?Signature=a%2Bb%3D")!, 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 {
|
||||
/// 离页取消请求后清理原票据,迟到响应不能隐藏其它请求,返回会重新加载课程。
|
||||
func testLeavingAndReturningRestoresCanceledCourseWithoutEndingOtherLoading() 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 loader = TrainingFixtureDocumentLoader { _, _ in
|
||||
await body.wait()
|
||||
return try TrainingDocumentTestFixtures.document()
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: loader)
|
||||
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
|
||||
controller.transitionCoordinator == nil && navigation.transitionCoordinator == nil
|
||||
}
|
||||
let destination = UIViewController()
|
||||
navigation.pushViewController(destination, animated: false)
|
||||
// 正文响应仍被 gate 挂起;这里只等待 UIKit 完成真实离页与页面票据释放。
|
||||
// 文件下载仍被 gate 挂起;这里只等待 UIKit 完成真实离页与页面票据释放。
|
||||
try await waitUntil {
|
||||
navigation.topViewController === destination && destination.view.window === window
|
||||
&& navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil
|
||||
@@ -208,7 +144,8 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
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 } }
|
||||
let action = try button("training.reading.action", in: controller.view)
|
||||
try await waitUntil { action.isUserInteractionEnabled }
|
||||
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||
GlobalLoadingManager.shared.endRequest(other)
|
||||
navigation.popViewController(animated: false)
|
||||
@@ -220,11 +157,14 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
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
|
||||
return text?.contains("这是一份 UTF-8 文本附件。") == true
|
||||
}
|
||||
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||
let calls = await source.calls
|
||||
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 3)
|
||||
XCTAssertEqual(calls.filter { $0.name == "attachmentURL" }.count, 2)
|
||||
let downloadCount = await body.requestCount
|
||||
XCTAssertEqual(downloadCount, 2)
|
||||
XCTAssertFalse(calls.contains { ["section", "sections"].contains($0.name) })
|
||||
}
|
||||
|
||||
/// 正文就绪后的自动会话、暂停保存与恢复不显示进度,只有用户重试失败会话显示。
|
||||
@@ -240,7 +180,7 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
throw URLError(.timedOut)
|
||||
}
|
||||
let source = TrainingDataStub(configuration: configuration)
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window, controller: controller) }
|
||||
try await waitUntil { await initial.requestCount == 1 }
|
||||
@@ -299,42 +239,11 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
}
|
||||
|
||||
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)
|
||||
let views = allViews(controller.view)
|
||||
guard let step = views.first(where: { $0 is TrainingStepView }), !step.isHidden,
|
||||
let preview = views.compactMap({ $0 as? TrainingDocumentPreviewView }).first,
|
||||
let action = try? button("training.reading.action", in: controller.view) else { return false }
|
||||
return preview.isReady && action.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing
|
||||
}
|
||||
|
||||
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } }
|
||||
@@ -344,7 +253,7 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||
}
|
||||
|
||||
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
|
||||
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||
let reached = await condition()
|
||||
XCTAssertTrue(reached, "未在期限内进入预期 UI / 请求状态")
|
||||
|
||||
@@ -20,6 +20,11 @@ enum TrainingRemoteFixtures {
|
||||
static func progress(seconds: Int = 20, completed: Bool = false) -> TrainingProgressSnapshot {
|
||||
TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, readingCompleted: seconds >= 20, learnerStatus: completed ? .completed : .pendingExam, completedAt: completed ? now : nil, hasDraft: false, canViewCourse: true, canStudy: seconds < 20 && !completed, canStartExam: seconds >= 20 && !completed, canRetry: !completed, blockReason: completed ? "completed" : seconds < 20 ? "reading_required" : nil, serverTime: now)
|
||||
}
|
||||
/// 轻量课程文档,默认使用可由本地替身稳定预览的纯文本。
|
||||
static func attachment(id: String = "file_1", name: String = "培训资料.txt", mimeType: String = "text/plain") -> TrainingAttachmentInfo {
|
||||
TrainingAttachmentInfo(id: id, name: name, mimeType: mimeType, sizeBytes: 1024,
|
||||
fileID: id, downloadURL: nil, expiresAt: nil)
|
||||
}
|
||||
/// 单次已提交成绩。
|
||||
static func attempt(id: String = "attempt_1", passed: Bool = true, questionCount: Int = 30, reviewAvailable: Bool = true) -> TrainingAttemptSummary {
|
||||
TrainingAttemptSummary(id: id, taskID: "task_1", taskTitle: "一线服务规范学习", courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", submittedAt: now, scoreHundredths: passed ? 10000 : 5000, correctCount: passed ? questionCount : questionCount / 2, questionCount: questionCount, passScore: 80, passed: passed, reviewAvailable: reviewAvailable)
|
||||
@@ -44,6 +49,7 @@ actor TrainingDataStub: TrainingDataServing {
|
||||
var cursor: String? = nil
|
||||
var offset: Int? = nil
|
||||
var limit: Int? = nil
|
||||
var resourceID: String? = nil
|
||||
}
|
||||
/// 心跳的固定幂等负载。
|
||||
struct HeartbeatCall: Equatable, Sendable {
|
||||
@@ -129,7 +135,7 @@ actor TrainingDataStub: TrainingDataServing {
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo {
|
||||
calls.append(Call(name: "course", taskID: taskID))
|
||||
if let handler = configuration.courseHandler { return try await handler() }
|
||||
return TrainingCourseInfo(id: id, title: "景区服务规范", introduction: "正式课程简介", sectionCount: 2, attachmentCount: 0)
|
||||
return TrainingCourseInfo(id: id, title: "景区服务规范", introduction: "正式课程简介", sectionCount: 2, attachmentCount: 1)
|
||||
}
|
||||
/// 小节目录,仅含标题与序号。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> {
|
||||
@@ -147,13 +153,13 @@ actor TrainingDataStub: TrainingDataServing {
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> {
|
||||
calls.append(Call(name: "attachments", taskID: taskID, cursor: cursor, limit: limit))
|
||||
if let handler = configuration.attachmentsHandler { return try await handler(cursor) }
|
||||
return TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||
return TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||
}
|
||||
/// 返回用于 Safari 的授权 HTTPS URL。
|
||||
/// 返回供文档加载替身读取的授权 HTTPS URL。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
||||
calls.append(Call(name: "attachmentURL", taskID: taskID))
|
||||
calls.append(Call(name: "attachmentURL", taskID: taskID, resourceID: attachmentID))
|
||||
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))
|
||||
return TrainingAttachmentLink(id: attachmentID, name: "培训资料.txt", url: URL(string: "https://example.test/training.txt")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))
|
||||
}
|
||||
/// 只返回权威读时。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot {
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
import PDFKit
|
||||
import UIKit
|
||||
import WebKit
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 真机使用正式预览组件读取本地文件,验证实际内容与渲染成功事件。
|
||||
@MainActor
|
||||
final class TrainingDocumentPreviewTests: XCTestCase {
|
||||
private var previousKeyWindow: UIWindow?
|
||||
|
||||
/// PDF 经 PDFKit 显示并保留可阅读的页内容。
|
||||
func testPDFFileRendersWithPDFKit() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
try await showDocument(.pdf, in: preview)
|
||||
let pdf = try XCTUnwrap(allViews(preview).compactMap { $0 as? TrainingPDFDocumentView }.first)
|
||||
XCTAssertFalse(pdf.isHidden)
|
||||
XCTAssertEqual(pdf.document?.pageCount, 1)
|
||||
XCTAssertTrue(pdf.document?.string?.contains("Training Course PDF") == true)
|
||||
let image = UIGraphicsImageRenderer(size: preview.bounds.size).image { _ in
|
||||
preview.drawHierarchy(in: preview.bounds, afterScreenUpdates: true)
|
||||
}
|
||||
record(image, name: "课程附件-PDF真机预览")
|
||||
}
|
||||
|
||||
/// 文件已装入但预览仍隐藏时不得发 ready;可见页真实绘制后才打开门禁。
|
||||
func testPDFDoesNotBecomeReadyUntilVisiblePageIsDrawn() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
preview.isHidden = true
|
||||
let id = UUID()
|
||||
var readyID: UUID?
|
||||
preview.onReady = { readyID = $0 }
|
||||
preview.show(try TrainingDocumentTestFixtures.document(kind: .pdf), requestID: id)
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
XCTAssertNil(readyID)
|
||||
XCTAssertFalse(preview.isReady)
|
||||
preview.isHidden = false
|
||||
try await waitUntil { readyID == id }
|
||||
XCTAssertTrue(preview.isReady)
|
||||
}
|
||||
|
||||
/// 祖先滚动区域裁剪掉 PDF 时,即使图层已排版也不能开始读时。
|
||||
func testPDFWaitsUntilItsDrawnPageEntersOuterViewport() async throws {
|
||||
let controller = UIViewController()
|
||||
let scroll = UIScrollView(frame: CGRect(x: 0, y: 80, width: 390, height: 600))
|
||||
scroll.clipsToBounds = true
|
||||
scroll.contentInsetAdjustmentBehavior = .never
|
||||
scroll.contentSize = CGSize(width: 390, height: 1600)
|
||||
let preview = TrainingDocumentPreviewView()
|
||||
preview.frame = CGRect(x: 12, y: 850, width: 366, height: 550)
|
||||
controller.view.addSubview(scroll)
|
||||
scroll.addSubview(preview)
|
||||
let window = try makeWindow(controller)
|
||||
defer { closeWindow(window) }
|
||||
let id = UUID()
|
||||
var readyID: UUID?
|
||||
preview.onReady = { readyID = $0 }
|
||||
preview.show(try TrainingDocumentTestFixtures.document(kind: .pdf), requestID: id)
|
||||
_ = UIGraphicsImageRenderer(size: preview.bounds.size).image { _ in
|
||||
preview.drawHierarchy(in: preview.bounds, afterScreenUpdates: true)
|
||||
}
|
||||
preview.notifyIfRenderedAndVisible()
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
XCTAssertNil(readyID)
|
||||
XCTAssertFalse(preview.isReady)
|
||||
scroll.setContentOffset(CGPoint(x: 0, y: 800), animated: false)
|
||||
controller.view.layoutIfNeeded()
|
||||
preview.notifyIfRenderedAndVisible()
|
||||
try await waitUntil { readyID == id }
|
||||
XCTAssertTrue(preview.isReady)
|
||||
}
|
||||
|
||||
/// 切到 PDF 后,旧 WebView 进程退出不能把当前 PDF 当成预览失败。
|
||||
func testOldWebProcessTerminationDoesNotInvalidateCurrentPDF() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
try await showDocument(.docx, in: preview)
|
||||
let oldWeb = try documentWebView(in: preview)
|
||||
try await showDocument(.pdf, in: preview)
|
||||
var failure: String?
|
||||
preview.onFailure = { _, message in failure = message }
|
||||
preview.webViewWebContentProcessDidTerminate(oldWeb)
|
||||
XCTAssertNil(failure)
|
||||
XCTAssertTrue(preview.isReady)
|
||||
XCTAssertFalse(try XCTUnwrap(allViews(preview).compactMap { $0 as? TrainingPDFDocumentView }.first).isHidden)
|
||||
}
|
||||
|
||||
/// DOCX 必须通过正式本地 JS 解析器产生段落与表格,不能只报告页面加载完成。
|
||||
func testDOCXFileRendersRealParagraphAndTable() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
try await showDocument(.docx, in: preview)
|
||||
let web = try documentWebView(in: preview)
|
||||
let text = try await web.evaluateJavaScript("document.getElementById('document').textContent") as? String
|
||||
XCTAssertTrue(text?.contains("培训课程 DOCX") == true)
|
||||
XCTAssertTrue(text?.contains("这是 Word 文档正文,包含中文内容。") == true)
|
||||
XCTAssertTrue(text?.contains("服务规范") == true)
|
||||
let tableCount = try await web.evaluateJavaScript("document.querySelectorAll('#document table').length") as? Int
|
||||
XCTAssertEqual(tableCount, 1)
|
||||
record(try await web.takeSnapshot(configuration: nil), name: "课程附件-DOCX真机预览")
|
||||
}
|
||||
|
||||
/// TXT 显示原文字面量,不能把文件里的 HTML 片段执行成网页。
|
||||
func testTXTFileRendersPlainText() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
try await showDocument(.txt, in: preview)
|
||||
let web = try documentWebView(in: preview)
|
||||
let text = try await web.evaluateJavaScript("document.querySelector('#document pre').textContent") as? String
|
||||
XCTAssertTrue(text?.contains("这是一份 UTF-8 文本附件。") == true)
|
||||
XCTAssertTrue(text?.contains("<script>alert(1)</script>") == true)
|
||||
let scriptCount = try await web.evaluateJavaScript("document.querySelectorAll('#document script').length") as? Int
|
||||
XCTAssertEqual(scriptCount, 0)
|
||||
record(try await web.takeSnapshot(configuration: nil), name: "课程附件-TXT真机预览")
|
||||
}
|
||||
|
||||
/// Markdown 渲染成标题、强调和表格,外部图片与危险链接不能进入有效属性。
|
||||
func testMarkdownFileRendersFormattedContent() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
try await showDocument(.md, in: preview)
|
||||
let web = try documentWebView(in: preview)
|
||||
let heading = try await web.evaluateJavaScript("document.querySelector('#document h1').textContent") as? String
|
||||
let strong = try await web.evaluateJavaScript("document.querySelector('#document strong').textContent") as? String
|
||||
let tableCount = try await web.evaluateJavaScript("document.querySelectorAll('#document table').length") as? Int
|
||||
let unsafeCount = try await web.evaluateJavaScript("document.querySelectorAll('#document script, #document img[src], #document a[href^=\"javascript:\"]').length") as? Int
|
||||
XCTAssertEqual(heading, "培训课程")
|
||||
XCTAssertEqual(strong, "Markdown")
|
||||
XCTAssertEqual(tableCount, 1)
|
||||
XCTAssertEqual(unsafeCount, 0)
|
||||
record(try await web.takeSnapshot(configuration: nil), name: "课程附件-Markdown真机预览")
|
||||
}
|
||||
|
||||
/// ZIP 损坏必须通过失败回调回到原生重试状态,不能累计阅读。
|
||||
func testBrokenDOCXFailsWithoutReadyEvent() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
let requestID = UUID()
|
||||
var readyID: UUID?
|
||||
var failureID: UUID?
|
||||
var failureMessage: String?
|
||||
preview.onReady = { readyID = $0 }
|
||||
preview.onFailure = { failureID = $0; failureMessage = $1 }
|
||||
preview.show(try TrainingDocumentTestFixtures.document(kind: .docx, resource: "training-preview-broken"), requestID: requestID)
|
||||
try await waitUntil { failureID != nil || readyID != nil }
|
||||
XCTAssertEqual(failureID, requestID)
|
||||
XCTAssertNil(readyID)
|
||||
XCTAssertNotNil(failureMessage)
|
||||
XCTAssertFalse(preview.isReady)
|
||||
}
|
||||
|
||||
/// 旧 DOC 文件明确拒绝,即使服务器错误地声明为 DOCX MIME。
|
||||
func testLegacyDOCIsRejectedBeforeDownload() async throws {
|
||||
let url = try XCTUnwrap(URL(string: "https://example.test/legacy.doc"))
|
||||
for mime in ["application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] {
|
||||
XCTAssertThrowsError(try TrainingDocumentKind.resolve(name: "旧版文档.doc", mimeType: mime, url: url)) { error in
|
||||
XCTAssertEqual(error.localizedDescription, TrainingDocumentError.unsupported.localizedDescription)
|
||||
}
|
||||
}
|
||||
let attachment = TrainingRemoteFixtures.attachment(name: "旧版文档.doc", mimeType: "application/msword")
|
||||
let link = TrainingAttachmentLink(id: attachment.id, name: attachment.name, url: url,
|
||||
expiresAt: Date().addingTimeInterval(60))
|
||||
do {
|
||||
_ = try await TrainingFixtureDocumentLoader().load(attachment: attachment, link: link)
|
||||
XCTFail("旧 DOC 不应被当作 DOCX 或文本加载")
|
||||
} catch {
|
||||
XCTAssertEqual(error.localizedDescription, TrainingDocumentError.unsupported.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
/// 课程元信息只出现在 UIKit 标签中,WebView DOM 只包含附件文件内容。
|
||||
func testCourseMetadataIsNativeAndAbsentFromDocument() async throws {
|
||||
let source = TrainingDataStub()
|
||||
await source.configure {
|
||||
$0.taskHandler = { _ in
|
||||
TrainingTaskDetail(summary: TrainingRemoteFixtures.task(title: "NATIVE_TASK_ONLY"), requiredReadingSeconds: 20,
|
||||
readingRule: "course_duration", scoring: "equal-percentage-v1", serverTime: TrainingRemoteFixtures.now)
|
||||
}
|
||||
$0.courseHandler = {
|
||||
TrainingCourseInfo(id: "course_1", title: "NATIVE_COURSE_ONLY", introduction: "NATIVE_INTRODUCTION_ONLY", sectionCount: 1, attachmentCount: 1)
|
||||
}
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
let window = try makeWindow(UINavigationController(rootViewController: controller))
|
||||
defer { closeWindow(window) }
|
||||
try await waitUntil {
|
||||
self.allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first?.isReady == true
|
||||
}
|
||||
let labels = allViews(controller.view).compactMap { $0 as? UILabel }
|
||||
let expected = ["training.reading.taskTitle": "NATIVE_TASK_ONLY", "training.reading.courseName": "NATIVE_COURSE_ONLY",
|
||||
"training.reading.examInfo": "学习 + 考试 · 30 题 · 80 分及格", "training.reading.introduction": "NATIVE_INTRODUCTION_ONLY"]
|
||||
for (identifier, value) in expected {
|
||||
XCTAssertEqual(labels.first { $0.accessibilityIdentifier == identifier }?.text, value)
|
||||
}
|
||||
let web = try documentWebView(in: controller.view)
|
||||
let content = try await web.evaluateJavaScript("document.body.textContent") as? String
|
||||
let text = try XCTUnwrap(content)
|
||||
XCTAssertTrue(text.contains("这是一份 UTF-8 文本附件。"))
|
||||
for value in expected.values { XCTAssertFalse(text.contains(value)) }
|
||||
let calls = await source.calls
|
||||
XCTAssertFalse(calls.contains { ["sections", "section"].contains($0.name) })
|
||||
}
|
||||
|
||||
/// 长文件由课程页面统一滚动,原生信息随正文离屏,换为短文件后不残留空白高度。
|
||||
func testLongTextUsesOuterPageScrollingAndShrinksForNextDocument() async throws {
|
||||
let lines = (1...120).map { "第 \($0) 行:这是完整课程阅读内容,向上滑动时标题和正文应一同移动。" }
|
||||
let document = try temporaryDocument(text: (lines + ["END_OF_LONG_COURSE"]).joined(separator: "\n"), kind: .txt)
|
||||
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
|
||||
let (controller, preview, scroll, window) = try await makeCourseWindow(document: document)
|
||||
defer { closeWindow(window) }
|
||||
let web = try documentWebView(in: preview)
|
||||
try await waitUntil { scroll.contentSize.height > scroll.bounds.height * 3 }
|
||||
XCTAssertFalse(web.scrollView.isScrollEnabled)
|
||||
let title = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UILabel }
|
||||
.first { $0.accessibilityIdentifier == "training.reading.taskTitle" })
|
||||
let initialTitleY = title.convert(title.bounds, to: controller.view).minY
|
||||
scrollToBottom(scroll)
|
||||
controller.view.layoutIfNeeded()
|
||||
let movedTitle = title.convert(title.bounds, to: controller.view)
|
||||
XCTAssertLessThan(movedTitle.maxY, scroll.frame.minY)
|
||||
XCTAssertLessThan(movedTitle.minY, initialTitleY - scroll.bounds.height)
|
||||
let documentBottom = web.convert(CGPoint(x: 0, y: web.bounds.maxY), to: scroll).y
|
||||
XCTAssertLessThanOrEqual(documentBottom, scroll.bounds.maxY + 3)
|
||||
XCTAssertGreaterThan(documentBottom, scroll.bounds.minY)
|
||||
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
|
||||
let originalHeight = preview.preferredContentHeight
|
||||
let shortDocument = try temporaryDocument(text: "新的短文档,只有一行。", kind: .txt)
|
||||
defer { try? FileManager.default.removeItem(at: shortDocument.fileURL.deletingLastPathComponent()) }
|
||||
preview.show(shortDocument, requestID: UUID())
|
||||
try await waitUntil { preview.isReady && preview.preferredContentHeight < originalHeight / 4 }
|
||||
controller.view.layoutIfNeeded()
|
||||
XCTAssertLessThan(scroll.contentSize.height, scroll.bounds.height)
|
||||
XCTAssertEqual(scroll.contentOffset.y, -scroll.adjustedContentInset.top, accuracy: 1)
|
||||
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
|
||||
XCTAssertTrue(title.convert(title.bounds, to: controller.view).intersects(scroll.frame))
|
||||
}
|
||||
|
||||
/// 异步排版变化和宽度重排会撑开或缩回卡片,不能依赖固定 WebView 高度。
|
||||
func testMarkdownAndDOCXTrackLateLayoutAndWidthChanges() async throws {
|
||||
let (preview, window) = try makePreviewWindow()
|
||||
defer { closeWindow(window) }
|
||||
preview.onContentHeightChange = { [weak preview] height in
|
||||
guard let preview else { return }
|
||||
preview.frame.size.height = height
|
||||
preview.layoutIfNeeded()
|
||||
}
|
||||
for kind in [TrainingDocumentKind.md, .docx] {
|
||||
preview.frame.size.width = 366
|
||||
try await showDocument(kind, in: preview)
|
||||
let web = try documentWebView(in: preview)
|
||||
let baseline = preview.preferredContentHeight
|
||||
_ = try await web.evaluateJavaScript("""
|
||||
(() => {
|
||||
const section = document.createElement('section');
|
||||
section.id = 'late-course-content';
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const paragraph = document.createElement('p');
|
||||
paragraph.textContent = '动态课程段落应完整排版,字体与宽度变化后,页面仍能读到最后一行。'.repeat(4);
|
||||
section.appendChild(paragraph);
|
||||
}
|
||||
document.getElementById('document').appendChild(section);
|
||||
})();
|
||||
""")
|
||||
try await waitUntil { preview.preferredContentHeight > baseline + 500 }
|
||||
let wideHeight = preview.preferredContentHeight
|
||||
preview.frame.size.width = 220
|
||||
preview.layoutIfNeeded()
|
||||
try await waitUntil { preview.preferredContentHeight > wideHeight + 100 }
|
||||
XCTAssertFalse(web.scrollView.isScrollEnabled)
|
||||
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
|
||||
_ = try await web.evaluateJavaScript("document.getElementById('late-course-content').remove()")
|
||||
preview.frame.size.width = 366
|
||||
preview.layoutIfNeeded()
|
||||
try await waitUntil { abs(preview.preferredContentHeight - baseline) < 5 }
|
||||
XCTAssertEqual(preview.bounds.height, preview.preferredContentHeight, accuracy: 1)
|
||||
XCTAssertTrue(preview.isReady)
|
||||
}
|
||||
}
|
||||
|
||||
/// 文内目录定位使用外层页面偏移,WebView 自己不能跳到目标而截断顶部内容。
|
||||
func testDocumentAnchorScrollsOuterPageWithoutMovingInnerWebView() async throws {
|
||||
let document = try TrainingDocumentTestFixtures.document(kind: .md)
|
||||
let (controller, preview, scroll, window) = try await makeCourseWindow(document: document)
|
||||
defer { closeWindow(window) }
|
||||
let web = try documentWebView(in: preview)
|
||||
_ = try await web.evaluateJavaScript("""
|
||||
(() => {
|
||||
const content = document.getElementById('document');
|
||||
const link = document.createElement('a');
|
||||
link.id = 'course-directory-link'; link.href = '#course-last-heading'; link.textContent = '跳到课程结尾';
|
||||
content.prepend(link);
|
||||
for (let i = 0; i < 55; i++) {
|
||||
const paragraph = document.createElement('p');
|
||||
paragraph.textContent = '课程学习段落 ' + i + ':继续阅读服务规范。'; content.appendChild(paragraph);
|
||||
}
|
||||
const target = document.createElement('h2');
|
||||
target.id = 'course-last-heading'; target.textContent = 'COURSE_ANCHOR_DESTINATION'; content.appendChild(target);
|
||||
const footer = document.createElement('div'); footer.style.height = '700px'; content.appendChild(footer);
|
||||
})();
|
||||
""")
|
||||
try await waitUntil { preview.preferredContentHeight > 2500 }
|
||||
_ = try await web.evaluateJavaScript("document.getElementById('course-directory-link').click()")
|
||||
try await waitUntil { scroll.contentOffset.y > 1000 && !scroll.isDecelerating && !scroll.isDragging }
|
||||
let targetResult = try await web.evaluateJavaScript("document.getElementById('course-last-heading').getBoundingClientRect().top") as? Double
|
||||
let targetY = try XCTUnwrap(targetResult)
|
||||
try await waitUntil {
|
||||
let position = web.convert(CGPoint(x: 0, y: CGFloat(targetY)), to: scroll).y - scroll.bounds.minY
|
||||
return abs(position - scroll.adjustedContentInset.top) < 5
|
||||
}
|
||||
XCTAssertFalse(web.scrollView.isScrollEnabled)
|
||||
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
|
||||
let innerOffset = try await web.evaluateJavaScript("window.scrollY") as? Double
|
||||
XCTAssertEqual(innerOffset ?? -1, 0, accuracy: 1)
|
||||
record(UIGraphicsImageRenderer(size: controller.view.bounds.size).image { _ in
|
||||
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
|
||||
}, name: "课程附件-文内锚点整页定位")
|
||||
}
|
||||
|
||||
/// 多页 PDF 完整撑高,最后一页可通过课程页面滚动抵达,不再嵌套 PDFKit 滚动容器。
|
||||
func testMultipagePDFReachesLastPageUsingOuterScrollView() async throws {
|
||||
let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 300, height: 450))
|
||||
let headingFont = try XCTUnwrap(UIFont(name: "Helvetica", size: 18))
|
||||
let markerFont = try XCTUnwrap(UIFont(name: "Helvetica", size: 14))
|
||||
let data = renderer.pdfData { context in
|
||||
for page in 1...6 {
|
||||
context.beginPage()
|
||||
("Training PDF page \(page) of 6" as NSString).draw(at: CGPoint(x: 24, y: 28), withAttributes: [.font: headingFont])
|
||||
("PDF_PAGE_END_\(page)" as NSString).draw(at: CGPoint(x: 24, y: 410), withAttributes: [.font: markerFont])
|
||||
}
|
||||
}
|
||||
let fixture = try XCTUnwrap(PDFDocument(data: data))
|
||||
// 页身份保存在 PDF 自身的注解中,避免把字体字形映射的文本抽取能力混入滚动回归。
|
||||
for index in 0..<fixture.pageCount {
|
||||
let page = try XCTUnwrap(fixture.page(at: index))
|
||||
let identity = PDFAnnotation(bounds: CGRect(x: 0, y: 0, width: 1, height: 1), forType: .link, withProperties: nil)
|
||||
identity.contents = "COURSE_PAGE_\(index + 1)"
|
||||
identity.url = URL(string: "https://example.test/course-page/\(index + 1)")
|
||||
page.addAnnotation(identity)
|
||||
}
|
||||
let serialized = try XCTUnwrap(fixture.dataRepresentation())
|
||||
let document = try temporaryDocument(data: serialized, kind: .pdf)
|
||||
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
|
||||
let (controller, preview, scroll, window) = try await makeCourseWindow(document: document)
|
||||
defer { closeWindow(window) }
|
||||
let pdf = try XCTUnwrap(allViews(preview).compactMap { $0 as? TrainingPDFDocumentView }.first)
|
||||
XCTAssertEqual(pdf.document?.pageCount, 6)
|
||||
let lastPage = try XCTUnwrap(pdf.document?.page(at: 5))
|
||||
XCTAssertEqual(lastPage.annotations.compactMap(\.contents), ["COURSE_PAGE_6"])
|
||||
XCTAssertTrue(allViews(pdf).compactMap { $0 as? UIScrollView }.isEmpty)
|
||||
XCTAssertGreaterThan(preview.preferredContentHeight, scroll.bounds.height * 4)
|
||||
XCTAssertEqual(preview.bounds.height, preview.preferredContentHeight, accuracy: 1)
|
||||
scrollToBottom(scroll)
|
||||
controller.view.layoutIfNeeded()
|
||||
let pdfBottom = pdf.convert(CGPoint(x: 0, y: pdf.bounds.maxY), to: scroll).y
|
||||
XCTAssertLessThanOrEqual(pdfBottom, scroll.bounds.maxY + 3)
|
||||
XCTAssertGreaterThan(pdfBottom, scroll.bounds.minY)
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
record(UIGraphicsImageRenderer(size: controller.view.bounds.size).image { _ in
|
||||
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
|
||||
}, name: "课程附件-多页PDF整页滑至末页")
|
||||
}
|
||||
|
||||
private func temporaryDocument(text: String, kind: TrainingDocumentKind) throws -> TrainingLocalDocument {
|
||||
try temporaryDocument(data: Data(text.utf8), kind: kind)
|
||||
}
|
||||
|
||||
private func temporaryDocument(data: Data, kind: TrainingDocumentKind) throws -> TrainingLocalDocument {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("training-scroll-test-\(UUID().uuidString)")
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let file = directory.appendingPathComponent("course.\(kind.rawValue)")
|
||||
try data.write(to: file)
|
||||
return TrainingLocalDocument(fileURL: file, kind: kind, name: file.lastPathComponent, temporaryDirectory: nil)
|
||||
}
|
||||
|
||||
private func makeCourseWindow(document: TrainingLocalDocument) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
|
||||
let source = TrainingDataStub()
|
||||
let name = document.name
|
||||
let mime: String
|
||||
switch document.kind {
|
||||
case .pdf: mime = "application/pdf"
|
||||
case .docx: mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
case .txt: mime = "text/plain"
|
||||
case .md: mime = "text/markdown"
|
||||
}
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(name: name, mimeType: mime)], nextCursor: nil, hasMore: false, serverTime: nil) }
|
||||
}
|
||||
let controller = TrainingCourseViewController(taskID: "task_1", service: source,
|
||||
documentLoader: TrainingFixtureDocumentLoader { _, _ in document })
|
||||
let window = try makeWindow(UINavigationController(rootViewController: controller))
|
||||
do {
|
||||
let preview = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first)
|
||||
try await waitUntil { preview.isReady }
|
||||
let scroll = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIScrollView }
|
||||
.first { $0.accessibilityIdentifier == "training.reading.scroll" })
|
||||
return (controller, preview, scroll, window)
|
||||
} catch {
|
||||
closeWindow(window)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func scrollToBottom(_ scroll: UIScrollView) {
|
||||
let bottom = max(-scroll.adjustedContentInset.top,
|
||||
scroll.contentSize.height - scroll.bounds.height + scroll.adjustedContentInset.bottom)
|
||||
scroll.setContentOffset(CGPoint(x: 0, y: bottom), animated: false)
|
||||
}
|
||||
|
||||
private func showDocument(_ kind: TrainingDocumentKind, in preview: TrainingDocumentPreviewView) async throws {
|
||||
let id = UUID()
|
||||
var readyID: UUID?
|
||||
var failure: String?
|
||||
preview.onReady = { readyID = $0 }
|
||||
preview.onFailure = { _, message in failure = message }
|
||||
preview.show(try TrainingDocumentTestFixtures.document(kind: kind), requestID: id)
|
||||
try await waitUntil { readyID != nil || failure != nil }
|
||||
XCTAssertNil(failure)
|
||||
XCTAssertEqual(readyID, id)
|
||||
XCTAssertTrue(preview.isReady)
|
||||
guard preview.isReady else { throw TrainingDocumentError.invalidFile }
|
||||
}
|
||||
|
||||
private func makePreviewWindow() throws -> (TrainingDocumentPreviewView, UIWindow) {
|
||||
let controller = UIViewController()
|
||||
let preview = TrainingDocumentPreviewView()
|
||||
controller.view.addSubview(preview)
|
||||
preview.frame = CGRect(x: 12, y: 80, width: 366, height: 640)
|
||||
return (preview, try makeWindow(controller))
|
||||
}
|
||||
|
||||
private func makeWindow(_ controller: UIViewController) 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)
|
||||
window.rootViewController = controller
|
||||
window.makeKeyAndVisible()
|
||||
controller.view.layoutIfNeeded()
|
||||
return window
|
||||
}
|
||||
|
||||
private func closeWindow(_ window: UIWindow) {
|
||||
window.isHidden = true
|
||||
window.rootViewController = nil
|
||||
previousKeyWindow?.makeKey()
|
||||
previousKeyWindow = nil
|
||||
}
|
||||
|
||||
private func documentWebView(in view: UIView) throws -> WKWebView {
|
||||
try XCTUnwrap(allViews(view).compactMap { $0 as? WKWebView }.first)
|
||||
}
|
||||
|
||||
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } }
|
||||
|
||||
private func record(_ image: UIImage, name: String) {
|
||||
let attachment = XCTAttachment(image: image)
|
||||
attachment.name = name
|
||||
attachment.lifetime = .keepAlways
|
||||
add(attachment)
|
||||
}
|
||||
|
||||
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
|
||||
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||
let reached = await condition()
|
||||
XCTAssertTrue(reached, "文档未在期限内完成真实渲染或返回失败事件")
|
||||
guard reached else { throw CancellationError() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
@testable import suixinkan
|
||||
|
||||
/// 定位测试 target 的附件资源,避免依赖开发机文件路径或真实网络。
|
||||
enum TrainingDocumentTestFixtures {
|
||||
/// 返回已打包的本地文档,资源不会由预览器删除。
|
||||
static func document(kind: TrainingDocumentKind = .txt, resource: String = "training-preview-sample") throws -> TrainingLocalDocument {
|
||||
let bundle = Bundle(for: TrainingDocumentBundleMarker.self)
|
||||
let file = bundle.url(forResource: resource, withExtension: kind.rawValue)
|
||||
?? bundle.url(forResource: resource, withExtension: kind.rawValue, subdirectory: "Fixtures/TrainingDocuments")
|
||||
guard let file else { throw CocoaError(.fileNoSuchFile) }
|
||||
return TrainingLocalDocument(fileURL: file, kind: kind, name: "\(resource).\(kind.rawValue)", temporaryDirectory: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// 给 Bundle 定位测试资源使用的普通 NSObject 类型。
|
||||
private final class TrainingDocumentBundleMarker: NSObject {}
|
||||
|
||||
/// 注入真实本地文件,可在下载入口挂起或失败,仍通过正式渲染器展示。
|
||||
struct TrainingFixtureDocumentLoader: TrainingDocumentLoading {
|
||||
/// 可覆盖一次下载过程;默认依据授权附件类型读取测试文件。
|
||||
var handler: (@Sendable (TrainingAttachmentInfo, TrainingAttachmentLink) async throws -> TrainingLocalDocument)?
|
||||
|
||||
/// 创建无网络的文档加载器,允许测试控制请求的完成时机。
|
||||
init(handler: (@Sendable (TrainingAttachmentInfo, TrainingAttachmentLink) async throws -> TrainingLocalDocument)? = nil) {
|
||||
self.handler = handler
|
||||
}
|
||||
|
||||
/// 保留正式格式识别规则,只替换文件获取路径。
|
||||
func load(attachment: TrainingAttachmentInfo, link: TrainingAttachmentLink) async throws -> TrainingLocalDocument {
|
||||
if let handler { return try await handler(attachment, link) }
|
||||
let kind = try TrainingDocumentKind.resolve(name: attachment.name, mimeType: attachment.mimeType, url: link.url)
|
||||
return try TrainingDocumentTestFixtures.document(kind: kind)
|
||||
}
|
||||
}
|
||||
@@ -24,33 +24,35 @@ struct TrainingRemoteReadingTests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 百节课程首次只读一页目录和一节正文,明确选择过的正文才缓存。
|
||||
@Test("首次不遍历百节正文,目录主动分页,正文按选择复用")
|
||||
private func loadRendered(_ model: TrainingRemoteReadingViewModel) async {
|
||||
await model.load()
|
||||
if let id = model.currentAttachmentID, let previewID = model.attachmentPreviewID {
|
||||
#expect(model.markAttachmentRendered(id: id, previewID: previewID))
|
||||
}
|
||||
}
|
||||
|
||||
/// 首屏只读取一页附件并授权首项,不请求已经停用的小节 HTML。
|
||||
@Test("首次仅请求附件第一页并授权首项,不加载小节 HTML")
|
||||
func lazyCourseResources() async {
|
||||
let source = source()
|
||||
await source.configure {
|
||||
$0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 100, attachmentCount: 20) }
|
||||
$0.sectionsHandler = { cursor in
|
||||
let range = cursor == nil ? 1...20 : 21...40
|
||||
return TrainingCursorPage(items: range.map { TrainingSectionInfo(id: "s\($0)", order: $0, title: "小节\($0)") },
|
||||
nextCursor: cursor == nil ? "next" : "last", hasMore: true, serverTime: nil)
|
||||
$0.attachmentsHandler = { _ in
|
||||
TrainingCursorPage(items: (1...20).map { TrainingRemoteFixtures.attachment(id: "file_\($0)") },
|
||||
nextCursor: "next", hasMore: true, serverTime: nil)
|
||||
}
|
||||
}
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
var calls = await source.calls
|
||||
#expect(model.sections.count == 20)
|
||||
#expect(calls.filter { $0.name == "sections" }.count == 1)
|
||||
#expect(calls.first { $0.name == "sections" }?.limit == 20)
|
||||
#expect(calls.filter { $0.name == "section" }.count == 1)
|
||||
#expect(!calls.contains { ["attachments", "paper", "questions", "draft", "attempts"].contains($0.name) })
|
||||
await model.loadMoreSections()
|
||||
#expect(model.sections.count == 40)
|
||||
await model.selectSection(id: "s2")
|
||||
await model.selectSection(id: "s1")
|
||||
calls = await source.calls
|
||||
#expect(calls.filter { $0.name == "section" }.count == 2)
|
||||
#expect(calls.filter { $0.name == "sections" }.last?.cursor == "next")
|
||||
let calls = await source.calls
|
||||
#expect(model.attachments.count == 20)
|
||||
#expect(model.currentAttachmentID == "file_1")
|
||||
#expect(model.currentAttachmentLink?.id == "file_1")
|
||||
#expect(calls.filter { $0.name == "attachments" }.count == 1)
|
||||
#expect(calls.first { $0.name == "attachments" }?.limit == 20)
|
||||
#expect(calls.filter { $0.name == "attachmentURL" }.map(\.resourceID) == ["file_1"])
|
||||
#expect(!calls.contains { ["sections", "section", "paper", "questions", "draft", "attempts"].contains($0.name) })
|
||||
#expect(!model.isAttachmentRendered)
|
||||
}
|
||||
|
||||
/// 倒计时本地刷新,五秒合并网络上报,最后一个片段关闭会话。
|
||||
@@ -58,7 +60,7 @@ struct TrainingRemoteReadingTests {
|
||||
func batchedHeartbeatAndCompletion() async {
|
||||
let source = source()
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
|
||||
#expect(await source.heartbeats.isEmpty)
|
||||
@@ -78,7 +80,7 @@ struct TrainingRemoteReadingTests {
|
||||
func historyAndSessionAreSeparate() async {
|
||||
let source = source(seconds: 12)
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...8 { await model.recordVisibleTime(at: Double(second)) }
|
||||
let calls = await source.heartbeats
|
||||
@@ -93,7 +95,7 @@ struct TrainingRemoteReadingTests {
|
||||
func pauseDoesNotCountBackgroundTime() async {
|
||||
let source = source()
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
|
||||
model.pauseReading()
|
||||
@@ -120,7 +122,7 @@ struct TrainingRemoteReadingTests {
|
||||
let server = TrainingReadingReplyController(loseCreateResponse: true)
|
||||
await bind(server, to: source)
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
#expect(model.readingErrorMessage != nil)
|
||||
await model.startReading(at: 10)
|
||||
@@ -138,7 +140,7 @@ struct TrainingRemoteReadingTests {
|
||||
let server = TrainingReadingReplyController(loseHeartbeatResponse: true)
|
||||
await bind(server, to: source)
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
|
||||
#expect(model.progress?.readingSeconds == 0)
|
||||
@@ -158,7 +160,7 @@ struct TrainingRemoteReadingTests {
|
||||
let server = TrainingReadingReplyController(loseHeartbeatResponse: true)
|
||||
await bind(server, to: source)
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
|
||||
model.pauseReading()
|
||||
@@ -184,7 +186,7 @@ struct TrainingRemoteReadingTests {
|
||||
let gate = TrainingReadingHeartbeatGate()
|
||||
await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } }
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
|
||||
let operation = Task { await model.recordVisibleTime(at: 5) }
|
||||
@@ -216,7 +218,7 @@ struct TrainingRemoteReadingTests {
|
||||
return try await server.confirm(call)
|
||||
} }
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
|
||||
let closing = Task { await model.flush(final: true) }
|
||||
@@ -246,7 +248,7 @@ struct TrainingRemoteReadingTests {
|
||||
func notWritableRefreshesReadOnlyState() async {
|
||||
let source = source()
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
let saved = TrainingRemoteFixtures.progress(seconds: 7)
|
||||
let readOnly = TrainingProgressSnapshot(taskID: saved.taskID, readingSeconds: saved.readingSeconds,
|
||||
@@ -263,7 +265,7 @@ struct TrainingRemoteReadingTests {
|
||||
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
|
||||
#expect(!model.canStudy)
|
||||
#expect(model.progress?.blockReason == "closed")
|
||||
#expect(model.currentSection != nil)
|
||||
#expect(model.currentAttachmentLink != nil)
|
||||
await model.startReading(at: 100)
|
||||
#expect(await source.startReadingRequests.count == 1)
|
||||
#expect(!model.isReading)
|
||||
@@ -277,14 +279,14 @@ struct TrainingRemoteReadingTests {
|
||||
func accessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async {
|
||||
let source = source()
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
await source.configure { $0.heartbeatHandler = { _ in throw failure } }
|
||||
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
|
||||
#expect(model.isInvalidated)
|
||||
#expect(model.currentSection == nil)
|
||||
#expect(model.currentAttachmentLink == nil)
|
||||
#expect(model.progress == nil)
|
||||
#expect(model.sections.isEmpty)
|
||||
#expect(model.attachments.isEmpty)
|
||||
#expect(!model.isReading)
|
||||
}
|
||||
|
||||
@@ -298,7 +300,7 @@ struct TrainingRemoteReadingTests {
|
||||
let server = TrainingReadingReplyController(nextFailure: failure)
|
||||
await bind(server, to: source)
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
|
||||
#expect(model.isReading)
|
||||
@@ -314,12 +316,12 @@ struct TrainingRemoteReadingTests {
|
||||
#expect((await source.calls).filter { $0.name == "progress" }.count >= 2)
|
||||
}
|
||||
|
||||
/// 正文请求挂起时切身份,旧正文不能回到已经关闭的学员页面。
|
||||
@Test("身份切换丢弃迟到正文和权威进度")
|
||||
func identityChangeDiscardsLateBody() async {
|
||||
/// 授权请求挂起时切身份,旧短链不能重新打开已经关闭的页面。
|
||||
@Test("身份切换丢弃迟到附件授权和权威进度")
|
||||
func identityChangeDiscardsLateAttachment() async {
|
||||
let source = source()
|
||||
let gate = TrainingReadingBodyGate()
|
||||
await source.configure { $0.sectionHandler = { _ in await gate.body() } }
|
||||
let gate = TrainingReadingAttachmentGate()
|
||||
await source.configure { $0.attachmentURLHandler = { _ in await gate.link() } }
|
||||
let model = model(source)
|
||||
let operation = Task { await model.load() }
|
||||
await gate.waitUntilRequested()
|
||||
@@ -328,37 +330,251 @@ struct TrainingRemoteReadingTests {
|
||||
await operation.value
|
||||
#expect(model.isInvalidated)
|
||||
#expect(model.task == nil)
|
||||
#expect(model.currentSection == nil)
|
||||
#expect(model.currentAttachment == nil)
|
||||
#expect(model.currentAttachmentLink == nil)
|
||||
#expect(model.attachmentPreviewID == nil)
|
||||
#expect(model.progress == nil)
|
||||
#expect(model.sections.isEmpty)
|
||||
#expect(model.attachments.isEmpty)
|
||||
}
|
||||
|
||||
/// 元信息不提前授权文件,用户点击附件时才申请短期可打开链接。
|
||||
@Test("附件目录按需分页,点击才获取授权地址")
|
||||
/// 后续附件页需要用户主动读取,分页不能提前授权其余文档。
|
||||
@Test("附件目录主动分页且只在选择时授权后续附件")
|
||||
func attachmentsAreLazyAndAuthorized() async {
|
||||
let source = source(seconds: 20)
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { cursor in
|
||||
let id = cursor == nil ? "file_1" : "file_2"
|
||||
let item = TrainingAttachmentInfo(id: id, name: "培训.pdf", mimeType: "application/pdf", sizeBytes: 1024,
|
||||
fileID: id, downloadURL: nil, expiresAt: nil)
|
||||
return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil,
|
||||
return TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(id: id)],
|
||||
nextCursor: cursor == nil ? "next" : nil,
|
||||
hasMore: cursor == nil, serverTime: nil)
|
||||
}
|
||||
}
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
#expect(!(await source.calls).contains { $0.name == "attachments" })
|
||||
await model.loadAttachments()
|
||||
await model.loadAttachments()
|
||||
#expect((await source.calls).filter { $0.name == "attachments" }.count == 1)
|
||||
#expect(!(await source.calls).contains { $0.name == "attachmentURL" })
|
||||
#expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1)
|
||||
await model.loadAttachments(loadMore: true)
|
||||
#expect(model.attachments.count == 2)
|
||||
let link = await model.authorizeAttachment(id: "file_1")
|
||||
#expect(link?.url.scheme == "https")
|
||||
#expect(link?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600))
|
||||
#expect((await source.calls).filter { $0.name == "attachments" }.last?.cursor == "next")
|
||||
#expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1)
|
||||
await model.selectAttachment(id: "file_2")
|
||||
#expect(model.currentAttachmentID == "file_2")
|
||||
#expect(model.currentAttachmentLink?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600))
|
||||
#expect((await source.calls).filter { $0.name == "attachmentURL" }.map(\.resourceID) == ["file_1", "file_2"])
|
||||
#expect(!model.isAttachmentRendered)
|
||||
}
|
||||
|
||||
/// 分页失败只提示列表错误,不能把已显示文件变成失败态或丢弃已累计秒数。
|
||||
@Test("附件分页失败可重试,当前文档继续阅读且成功后清提示")
|
||||
func attachmentPaginationErrorDoesNotInterruptReading() async throws {
|
||||
let source = source()
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { _ in
|
||||
TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: "next", hasMore: true, serverTime: nil)
|
||||
}
|
||||
}
|
||||
let model = model(source)
|
||||
await loadRendered(model)
|
||||
let previewID = try #require(model.attachmentPreviewID)
|
||||
let link = try #require(model.currentAttachmentLink)
|
||||
await model.startReading(at: 0)
|
||||
await model.recordVisibleTime(at: 1)
|
||||
await source.configure { $0.attachmentsHandler = { _ in throw URLError(.timedOut) } }
|
||||
await model.loadAttachments(loadMore: true)
|
||||
#expect(model.attachmentListErrorMessage != nil)
|
||||
#expect(model.attachmentErrorMessage == nil && model.errorMessage == nil)
|
||||
#expect(model.isAttachmentRendered && model.isReading && model.canStudy)
|
||||
#expect(model.currentAttachmentLink == link && model.attachmentPreviewID == previewID)
|
||||
#expect(model.attachments.count == 1 && model.hasMoreAttachments)
|
||||
#expect(model.markAttachmentRendered(id: "file_1", previewID: previewID))
|
||||
await model.recordVisibleTime(at: 2)
|
||||
#expect(model.activeSecondsTotal == 2)
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { _ in
|
||||
TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(id: "file_2")], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||
}
|
||||
}
|
||||
await model.loadAttachments(loadMore: true)
|
||||
#expect(model.attachmentListErrorMessage == nil && model.errorMessage == nil)
|
||||
#expect(model.attachments.map(\.id) == ["file_1", "file_2"])
|
||||
#expect(!model.hasMoreAttachments)
|
||||
#expect(model.currentAttachmentLink == link && model.attachmentPreviewID == previewID)
|
||||
#expect(model.isAttachmentRendered && model.isReading)
|
||||
await model.recordVisibleTime(at: 3)
|
||||
model.pauseReading()
|
||||
await model.flush()
|
||||
let heartbeats = await source.heartbeats
|
||||
#expect(heartbeats.count == 1)
|
||||
#expect(heartbeats.first?.activeSecondsTotal == 3 && heartbeats.first?.final == true)
|
||||
#expect(await source.startReadingRequests.count == 1)
|
||||
let calls = await source.calls
|
||||
#expect(calls.filter { $0.name == "attachments" }.map(\.cursor) == [nil, "next", "next"])
|
||||
#expect(calls.filter { $0.name == "attachmentURL" }.count == 1)
|
||||
}
|
||||
|
||||
/// 授权被撤回不是普通分页故障,必须清理已经可读的文件并立即停止学习。
|
||||
@Test("附件分页返回账号或权限失效时仍清内容退出", arguments: [
|
||||
TrainingRemoteError.accountInvalid("account no longer eligible"),
|
||||
TrainingRemoteError.forbidden("assignment revoked")
|
||||
])
|
||||
func attachmentPaginationAccessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async {
|
||||
let source = source()
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { _ in
|
||||
TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: "next", hasMore: true, serverTime: nil)
|
||||
}
|
||||
}
|
||||
let model = model(source)
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
await source.configure { $0.attachmentsHandler = { _ in throw failure } }
|
||||
await model.loadAttachments(loadMore: true)
|
||||
#expect(model.isInvalidated)
|
||||
#expect(!model.isReading && !model.isAttachmentRendered)
|
||||
#expect(model.attachments.isEmpty && model.currentAttachmentLink == nil)
|
||||
#expect(model.attachmentListErrorMessage == nil)
|
||||
}
|
||||
|
||||
/// 只有文档下载与渲染都结束并由页面确认后才建立学习会话。
|
||||
@Test("附件授权不代表已展示,渲染确认前不能累计读时")
|
||||
func authorizedAttachmentWaitsForRendering() async throws {
|
||||
let source = source()
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
#expect(model.currentAttachmentLink != nil)
|
||||
await model.startReading(at: 0)
|
||||
await model.recordVisibleTime(at: 100)
|
||||
#expect(await source.startReadingRequests.isEmpty)
|
||||
#expect(await source.heartbeats.isEmpty)
|
||||
let previewID = try #require(model.attachmentPreviewID)
|
||||
#expect(!model.markAttachmentRendered(id: "another-file", previewID: previewID))
|
||||
#expect(!model.markAttachmentRendered(id: "file_1", previewID: UUID()))
|
||||
#expect(model.markAttachmentRendered(id: "file_1", previewID: previewID))
|
||||
await model.startReading(at: 200)
|
||||
await model.recordVisibleTime(at: 201)
|
||||
#expect(model.isReading)
|
||||
#expect(model.activeSecondsTotal == 1)
|
||||
#expect(await source.startReadingRequests.count == 1)
|
||||
}
|
||||
|
||||
/// 没有课程文档时保留元信息空态,不请求 HTML,也不能通过空白页获得进度。
|
||||
@Test("无附件保留课程元信息但不建立会话或回退 HTML")
|
||||
func missingAttachmentDoesNotCountReading() async {
|
||||
let source = source()
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { _ in TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil) }
|
||||
}
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await model.startReading(at: 0)
|
||||
await model.recordVisibleTime(at: 1000)
|
||||
#expect(model.task != nil && model.course != nil && model.progress != nil)
|
||||
#expect(model.hasLoadedAttachments)
|
||||
#expect(model.currentAttachment == nil)
|
||||
#expect(model.currentAttachmentLink == nil)
|
||||
#expect(!model.isAttachmentRendered)
|
||||
#expect(!model.markAttachmentRendered(id: "file_1", previewID: UUID()))
|
||||
#expect(!(await source.calls).contains { ["section", "sections", "attachmentURL", "startReading", "heartbeat"].contains($0.name) })
|
||||
}
|
||||
|
||||
/// 授权失败仍展示课程规则和附件名,重试成功后也要等待实际渲染。
|
||||
@Test("授权失败可重试同一附件,课程元信息不丢失")
|
||||
func authorizationFailureKeepsMetadataForRetry() async throws {
|
||||
let source = source()
|
||||
await source.configure { $0.attachmentURLHandler = { _ in throw URLError(.timedOut) } }
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
#expect(model.task != nil && model.course != nil && model.progress != nil)
|
||||
#expect(model.currentAttachmentID == "file_1")
|
||||
#expect(model.currentAttachmentLink == nil)
|
||||
#expect(model.attachmentErrorMessage != nil)
|
||||
await model.startReading(at: 0)
|
||||
#expect(await source.startReadingRequests.isEmpty)
|
||||
let failedPreviewID = try #require(model.attachmentPreviewID)
|
||||
await source.configure { $0.attachmentURLHandler = nil }
|
||||
await model.selectAttachment(id: "file_1")
|
||||
let nextPreviewID = try #require(model.attachmentPreviewID)
|
||||
#expect(nextPreviewID != failedPreviewID)
|
||||
#expect(model.currentAttachmentLink != nil)
|
||||
#expect(model.attachmentErrorMessage == nil)
|
||||
#expect(!model.markAttachmentRendered(id: "file_1", previewID: failedPreviewID))
|
||||
#expect(model.markAttachmentRendered(id: "file_1", previewID: nextPreviewID))
|
||||
}
|
||||
|
||||
/// 预览失败停止当前片段,进度刷新不得误清错误或恢复读时。
|
||||
@Test("附件预览失败停止读时,错误跨进度刷新保留")
|
||||
func previewFailureStopsReadingAndSurvivesProgressRefresh() async throws {
|
||||
let source = source()
|
||||
let model = model(source)
|
||||
await loadRendered(model)
|
||||
let previewID = try #require(model.attachmentPreviewID)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
|
||||
model.reportAttachmentFailure(id: "file_1", previewID: previewID, message: "文档加载失败")
|
||||
#expect(!model.isReading && !model.isAttachmentRendered)
|
||||
await model.flush()
|
||||
await model.refreshProgress()
|
||||
#expect(model.attachmentErrorMessage == "文档加载失败")
|
||||
#expect(model.errorMessage == "文档加载失败")
|
||||
#expect(!model.markAttachmentRendered(id: "file_1", previewID: previewID))
|
||||
await model.startReading(at: 100)
|
||||
await model.recordVisibleTime(at: 101)
|
||||
let calls = await source.heartbeats
|
||||
#expect(calls.count == 1)
|
||||
#expect(calls.first?.activeSecondsTotal == 3 && calls.first?.final == true)
|
||||
#expect(await source.startReadingRequests.count == 1)
|
||||
#expect(model.progress?.readingSeconds == 3)
|
||||
}
|
||||
|
||||
/// 切文档关闭旧片段,旧下载成功或失败回调都不能改变新文档。
|
||||
@Test("切附件先 final 保存,旧预览回调无效,新文档重新计时")
|
||||
func switchingAttachmentClosesReadingAndRejectsLatePreview() async throws {
|
||||
let source = source()
|
||||
await source.configure {
|
||||
$0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(), TrainingRemoteFixtures.attachment(id: "file_2")], nextCursor: nil, hasMore: false, serverTime: nil) }
|
||||
}
|
||||
let model = model(source)
|
||||
await loadRendered(model)
|
||||
let oldPreviewID = try #require(model.attachmentPreviewID)
|
||||
await model.startReading(at: 0)
|
||||
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
|
||||
await model.selectAttachment(id: "file_2")
|
||||
let calls = await source.heartbeats
|
||||
#expect(calls.count == 1)
|
||||
#expect(calls.first?.activeSecondsTotal == 3 && calls.first?.final == true)
|
||||
#expect(!model.isReading && !model.isAttachmentRendered)
|
||||
#expect(!model.markAttachmentRendered(id: "file_1", previewID: oldPreviewID))
|
||||
model.reportAttachmentFailure(id: "file_1", previewID: oldPreviewID, message: "迟到错误")
|
||||
#expect(model.attachmentErrorMessage == nil)
|
||||
await model.startReading(at: 100)
|
||||
#expect(await source.startReadingRequests.count == 1)
|
||||
let previewID = try #require(model.attachmentPreviewID)
|
||||
#expect(model.markAttachmentRendered(id: "file_2", previewID: previewID))
|
||||
await model.startReading(at: 200)
|
||||
await model.recordVisibleTime(at: 201)
|
||||
#expect(model.activeSecondsTotal == 1)
|
||||
#expect(await source.startReadingRequests.count == 2)
|
||||
#expect(model.progress?.readingSeconds == 3)
|
||||
}
|
||||
|
||||
/// 不能显示服务端错误返回的另一份附件,即使地址本身和有效期合法。
|
||||
@Test("附件授权响应必须匹配所选附件标识")
|
||||
func mismatchedAttachmentAuthorizationIsRejected() async {
|
||||
let source = source()
|
||||
await source.configure { $0.attachmentURLHandler = { _ in
|
||||
TrainingAttachmentLink(id: "other-file", name: "另一份文档.txt",
|
||||
url: URL(string: "https://example.test/other.txt")!,
|
||||
expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(60))
|
||||
} }
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
#expect(model.currentAttachmentID == "file_1")
|
||||
#expect(model.currentAttachmentLink == nil)
|
||||
#expect(model.attachmentErrorMessage != nil)
|
||||
await model.startReading(at: 0)
|
||||
#expect(await source.startReadingRequests.isEmpty)
|
||||
}
|
||||
|
||||
/// 两种网页协议都能打开,带签名的查询参数不在客户端改写。
|
||||
@@ -414,10 +630,10 @@ struct TrainingRemoteReadingTests {
|
||||
func readOnlyDoesNotStartSession() async {
|
||||
let source = source(seconds: 20)
|
||||
let model = model(source)
|
||||
await model.load()
|
||||
await loadRendered(model)
|
||||
await model.startReading(at: 0)
|
||||
await model.recordVisibleTime(at: 1000)
|
||||
#expect(model.currentSection != nil)
|
||||
#expect(model.currentAttachmentLink != nil)
|
||||
#expect(await source.startReadingRequests.isEmpty)
|
||||
#expect(await source.heartbeats.isEmpty)
|
||||
#expect(!model.isReading)
|
||||
@@ -473,13 +689,13 @@ private actor TrainingReadingReplyController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 不使用固定延时的正文响应闸门,精确控制身份切换和迟到响应的先后顺序。
|
||||
private actor TrainingReadingBodyGate {
|
||||
private var response: CheckedContinuation<TrainingSectionContent, Never>?
|
||||
/// 不使用固定延时的附件授权响应闸门,控制身份切换和迟到响应顺序。
|
||||
private actor TrainingReadingAttachmentGate {
|
||||
private var response: CheckedContinuation<TrainingAttachmentLink, Never>?
|
||||
private var waiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
/// 等待测试明确释放正文,通知等待请求已发出的测试代码。
|
||||
func body() async -> TrainingSectionContent {
|
||||
/// 等待测试释放短链,通知测试请求已挂起。
|
||||
func link() async -> TrainingAttachmentLink {
|
||||
await withCheckedContinuation {
|
||||
response = $0
|
||||
waiters.forEach { $0.resume() }
|
||||
@@ -487,15 +703,17 @@ private actor TrainingReadingBodyGate {
|
||||
}
|
||||
}
|
||||
|
||||
/// 不轮询地等待正文请求已经挂起。
|
||||
/// 等待授权请求已经挂起。
|
||||
func waitUntilRequested() async {
|
||||
if response != nil { return }
|
||||
await withCheckedContinuation { waiters.append($0) }
|
||||
}
|
||||
|
||||
/// 在身份已变化后返回旧账号正文。
|
||||
/// 在身份变化后返回旧任务附件地址。
|
||||
func release() {
|
||||
response?.resume(returning: TrainingSectionContent(id: "s1", order: 1, title: "旧正文", contentHTML: "<p>旧账号课程</p>"))
|
||||
response?.resume(returning: TrainingAttachmentLink(id: "file_1", name: "旧文档.txt",
|
||||
url: URL(string: "https://example.test/training.txt")!,
|
||||
expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600)))
|
||||
response = nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import UIKit
|
||||
import WebKit
|
||||
@testable import suixinkan
|
||||
|
||||
#if DEBUG
|
||||
@@ -66,17 +67,24 @@ struct TrainingUIRenderingTests {
|
||||
let model = TrainingRemoteExamViewModel(taskID: "task_1", context: context,
|
||||
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { context })
|
||||
let source = TrainingDataStub()
|
||||
let course = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let course = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
let exam = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||
for (controller, selectedTitle) in [(course as UIViewController, "1 课程学习"), (exam, "2 在线考试")] {
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
let window = try makeWindow(navigation, width: width)
|
||||
defer { window.isHidden = true }
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||
while (!allViews(controller.view).contains { $0 is TrainingStepView }
|
||||
|| (controller === exam && !model.canEdit)), ContinuousClock.now < deadline {
|
||||
let isReady: () -> Bool = {
|
||||
guard self.allViews(controller.view).contains(where: { $0 is TrainingStepView && !$0.isHidden }) else { return false }
|
||||
if controller === course {
|
||||
return self.allViews(controller.view).compactMap({ $0 as? TrainingDocumentPreviewView }).first?.isReady == true
|
||||
}
|
||||
return model.canEdit
|
||||
}
|
||||
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
|
||||
while !isReady(), ContinuousClock.now < deadline {
|
||||
try await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
#expect(isReady())
|
||||
let steps = allViews(controller.view).compactMap { $0 as? TrainingStepView }
|
||||
#expect(steps.count == 1)
|
||||
let step = try #require(steps.first)
|
||||
@@ -91,6 +99,34 @@ struct TrainingUIRenderingTests {
|
||||
#expect(labels.filter { $0.accessibilityTraits.contains(.selected) }.map(\.text) == [selectedTitle])
|
||||
#expect(labels.first { $0.text == selectedTitle }?.textColor == TrainingUI.primary)
|
||||
#expect(step.bounds.height >= 44)
|
||||
if controller === course {
|
||||
let buttons = allViews(controller.view).compactMap { $0 as? UIButton }
|
||||
#expect(!buttons.contains { $0.accessibilityIdentifier == "training.reading.sections" || $0.accessibilityIdentifier == "training.reading.attachments" })
|
||||
#expect(!buttons.contains { $0.configuration?.title == "章节目录" || $0.configuration?.title == "课程附件" })
|
||||
let frame = step.convert(step.bounds, to: controller.view)
|
||||
#expect(abs(frame.minY - controller.view.safeAreaInsets.top - 8) < 1)
|
||||
let preview = try #require(allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first)
|
||||
let scroll = try #require(preview.superview?.superview as? UIScrollView)
|
||||
#expect(abs(scroll.frame.minY - frame.maxY - 8) < 1)
|
||||
let metadataLabels = allViews(controller.view).compactMap { $0 as? UILabel }.filter {
|
||||
["training.reading.taskTitle", "training.reading.courseName", "training.reading.examInfo", "training.reading.introduction"].contains($0.accessibilityIdentifier ?? "")
|
||||
}
|
||||
#expect(metadataLabels.count == 4)
|
||||
for label in metadataLabels {
|
||||
let labelFrame = label.convert(label.bounds, to: scroll)
|
||||
#expect(labelFrame.minX >= 0 && labelFrame.maxX <= scroll.bounds.width + 1)
|
||||
#expect(label.numberOfLines == 0)
|
||||
}
|
||||
let web = try #require(allViews(preview).compactMap { $0 as? WKWebView }.first)
|
||||
if width == 390 {
|
||||
let webImage = try await web.takeSnapshot(configuration: nil)
|
||||
let image = UIGraphicsImageRenderer(size: navigation.view.bounds.size).image { _ in
|
||||
navigation.view.drawHierarchy(in: navigation.view.bounds, afterScreenUpdates: true)
|
||||
webImage.draw(in: web.convert(web.bounds, to: navigation.view))
|
||||
}
|
||||
Attachment.record(image, named: "课程页原生信息与附件正文", as: .png)
|
||||
}
|
||||
}
|
||||
Attachment.record(render(step), named: "\(Int(width))点-\(selectedTitle)", as: .png)
|
||||
|
||||
if width == 320 {
|
||||
@@ -119,8 +155,8 @@ struct TrainingUIRenderingTests {
|
||||
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: false) } }
|
||||
let attempt = TrainingRemoteFixtures.attempt(passed: false)
|
||||
let center = TrainingCenterViewController(service: source)
|
||||
let course = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||
let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source)
|
||||
let course = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
let navigation = UINavigationController()
|
||||
navigation.setViewControllers([center, course, result], animated: false)
|
||||
let window = try makeWindow(navigation)
|
||||
@@ -164,7 +200,7 @@ struct TrainingUIRenderingTests {
|
||||
await result.reload()
|
||||
#expect(action.configuration?.title == "完成,返回培训中心")
|
||||
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: true) } }
|
||||
let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source)
|
||||
let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source, documentLoader: TrainingFixtureDocumentLoader())
|
||||
navigation.setViewControllers([center, passedResult], animated: false)
|
||||
try await settleTransitions(in: navigation)
|
||||
await passedResult.reload()
|
||||
|
||||
Reference in New Issue
Block a user