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("") == 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 testContinuousCourseScrollingKeepsCountdownRunning() async throws {
let document = try temporaryDocument(text: (1...120).map { "第 \($0) 行:滑动阅读时仍应累计有效读时。" }.joined(separator: "\n"), kind: .txt)
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
let (controller, _, scroll, window) = try await makeCourseWindow(document: document, readingSeconds: 0)
defer { closeWindow(window) }
let action = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIButton }
.first { $0.accessibilityIdentifier == "training.reading.action" })
func remainingSeconds() -> Int? {
guard let title = action.configuration?.title, let start = title.lastIndex(of: "("),
let end = title.range(of: "s)")?.lowerBound else { return nil }
return Int(title[title.index(after: start).. 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.. 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, readingSeconds: Int = 20) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
var configuration = TrainingDataStub.Configuration()
configuration.readingSeconds = readingSeconds
let source = TrainingDataStub(configuration: configuration)
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() }
}
}
/// 精确挂起课程心跳响应,确保超时或断言失败后也能释放所有等待。
private actor TrainingCourseHeartbeatGate {
private var releasedSequences: Set = []
private var didReleaseAll = false
private var waiters: [Int: [CheckedContinuation]] = [:]
func wait(sequence: Int) async {
guard !didReleaseAll, !releasedSequences.contains(sequence) else { return }
await withCheckedContinuation { waiters[sequence, default: []].append($0) }
}
func release(sequence: Int) {
releasedSequences.insert(sequence)
waiters.removeValue(forKey: sequence)?.forEach { $0.resume() }
}
func releaseAll() {
didReleaseAll = true
let pending = waiters.values.flatMap { $0 }
waiters.removeAll()
pending.forEach { $0.resume() }
}
}