Files
ReadViewSDK/ReadViewDemo/ReadViewDemoUITests/ReaderUITests/PDFPageTurnBlankPageTests.swift
T
2026-10-23 19:29:45 +09:00

253 lines
11 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import XCTest
import UIKit
/// PDF 翻页后白页回归。
///
/// 判定方式:每次翻页稳定后截屏,统计画面中部的深色像素占比。正常 PDF 正文页
/// 含文字与线条,占比明显高于阈值;页面图片没有装配到视图上时几乎全白。
final class PDFPageTurnBlankPageTests: XCTestCase {
private let app = XCUIApplication()
/// 深色像素占比低于该值即视为白页。样张实测:白页为 0.0000,
/// 内容最少的扉页约 0.0020,正文页在 0.0100 以上。
private let blankInkRatioThreshold = 0.0005
override func setUpWithError() throws {
continueAfterFailure = false
}
func testPageCurlForwardTurnsRenderPageContent() {
openDictionaryPDF(displayType: "pagecurl")
assertForwardTurnsRenderContent(turns: 8, mode: "仿真翻页")
}
func testHorizontalScrollForwardTurnsRenderPageContent() {
openDictionaryPDF(displayType: "horizontalscroll")
assertForwardTurnsRenderContent(turns: 8, mode: "横向滚动")
}
/// 回翻同样依赖 `viewControllerBefore` 预建的页面视图,需要单独覆盖。
func testPageCurlBackwardTurnsRenderPageContent() {
openDictionaryPDF(displayType: "pagecurl")
assertForwardTurnsRenderContent(turns: 5, mode: "仿真翻页")
assertBackwardTurnsRenderContent(from: 6, turns: 5, mode: "仿真回翻")
}
// MARK: - 步骤
private func openDictionaryPDF(displayType: String, textSource: String? = nil) {
app.launchAndOpenSampleBook(
bookTitleQuery: "英汉大词典",
displayType: displayType,
resetsReaderState: true,
pdfTextSource: textSource
)
app.waitForReader(timeout: 30)
app.waitForReaderPage(1, timeout: 30)
// 首页首次渲染需要等待异步解码完成,避免把加载中误判成白页。
RunLoop.current.run(until: Date().addingTimeInterval(2.5))
}
private func assertForwardTurnsRenderContent(turns: Int, mode: String) {
var blankPages: [Int] = []
recordInk(page: 1, mode: mode, blankPages: &blankPages)
for step in 1...turns {
let expectedPage = step + 1
turnToNextPage()
app.waitForDemoReaderState(timeout: 15, description: "\(mode) page=\(expectedPage)") {
$0.page == expectedPage
}
// 翻页动画结束后再取样,排除卷页过程中的中间帧。
RunLoop.current.run(until: Date().addingTimeInterval(1.2))
recordInk(page: expectedPage, mode: mode, blankPages: &blankPages)
}
XCTAssertTrue(
blankPages.isEmpty,
"\(mode):翻页后出现白页,页码 \(blankPages.map(String.init).joined(separator: ", "))"
)
}
private func assertBackwardTurnsRenderContent(from startPage: Int, turns: Int, mode: String) {
var blankPages: [Int] = []
for step in 1...turns {
let expectedPage = startPage - step
guard expectedPage >= 1 else { break }
turnPage(forward: false)
app.waitForDemoReaderState(timeout: 15, description: "\(mode) page=\(expectedPage)") {
$0.page == expectedPage
}
RunLoop.current.run(until: Date().addingTimeInterval(1.2))
recordInk(page: expectedPage, mode: mode, blankPages: &blankPages)
}
XCTAssertTrue(
blankPages.isEmpty,
"\(mode):翻页后出现白页,页码 \(blankPages.map(String.init).joined(separator: ", "))"
)
}
private func turnToNextPage() { turnPage(forward: true) }
private func turnPage(forward: Bool) {
let content = app.otherElements[IDs.readerContent].firstMatch
let target: XCUIElement = content.exists ? content : app.windows.firstMatch
let leading = CGVector(dx: 0.08, dy: 0.5)
let trailing = CGVector(dx: 0.88, dy: 0.5)
let start = target.coordinate(withNormalizedOffset: forward ? trailing : leading)
let end = target.coordinate(withNormalizedOffset: forward ? leading : trailing)
start.press(forDuration: 0.05, thenDragTo: end)
}
private func recordInk(page: Int, mode: String, blankPages: inout [Int]) {
let screenshot = XCUIScreen.main.screenshot()
let ratio = inkRatio(of: screenshot.image)
let attachment = XCTAttachment(screenshot: screenshot)
attachment.name = "\(mode)-page-\(page)-ink-\(String(format: "%.4f", ratio))"
attachment.lifetime = .keepAlways
add(attachment)
if ratio < blankInkRatioThreshold {
blankPages.append(page)
}
}
/// 画面中部深色像素占比。裁掉上下边缘以排除状态栏、工具栏和页面外底色。
private func inkRatio(of image: UIImage) -> Double {
guard let cgImage = image.cgImage else { return 0 }
let cropRect = CGRect(
x: CGFloat(cgImage.width) * 0.12,
y: CGFloat(cgImage.height) * 0.16,
width: CGFloat(cgImage.width) * 0.76,
height: CGFloat(cgImage.height) * 0.68
).integral
guard let cropped = cgImage.cropping(to: cropRect) else { return 0 }
let side = 400
var pixels = [UInt8](repeating: 255, count: side * side)
guard let context = CGContext(
data: &pixels,
width: side,
height: side,
bitsPerComponent: 8,
bytesPerRow: side,
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: CGImageAlphaInfo.none.rawValue
) else { return 0 }
context.draw(cropped, in: CGRect(x: 0, y: 0, width: side, height: side))
let darkCount = pixels.reduce(into: 0) { partial, value in
if value < 150 { partial += 1 }
}
return Double(darkCount) / Double(side * side)
}
// MARK: - 主题切换:变换缓存失效正确性
//
// 回归点:`pageImageTransform` 结果现按 (页码, 主题 id) 缓存。若失效点漏接,
// 切主题 / 翻页 / 内存回收后会显示上一个主题算出的陈旧帧。此用例churn 页面并
// 在夜间/浅色间往返,确认没有陈旧帧、也没有因缓存导致的白页。
// 注:XCUITest 无法可靠地测毫秒级耗时;这里以“缓存正确性”作为性能修复的回归护栏。
func testDarkThemeSurvivesPageChurnWithoutStaleOrBlankFrames() {
openDictionaryPDF(displayType: "horizontalscroll", textSource: "none")
let lightRatio = currentInkRatio()
XCTAssertGreaterThan(lightRatio, blankInkRatioThreshold, "首页不应是白页")
XCTAssertLessThan(lightRatio, 0.35, "浅色主题下正文页不应接近全黑(ink=\(lightRatio))")
switchTheme(toIdentifier: 5) // 夜间:contentBackgroundColor 亮度 < 0.5 → 整页反相
let darkRatio = currentInkRatio()
XCTAssertGreaterThan(darkRatio, 0.5, "切到夜间主题后正文页应被反相为深色(ink=\(darkRatio))")
app.hideReaderChromeIfNeeded()
// 前翻 3 页:每页首次 configure 命中/回填变换缓存;翻页同时触发
// trimPageDescriptorCache 的 renderedImageCache 失效路径。
for page in 2...4 {
turnPageAndWait(toPage: page, forward: true)
let r = currentInkRatio()
XCTAssertGreaterThan(r, blankInkRatioThreshold, "夜间主题前翻后出现白页(page \(page),ink=\(r))")
XCTAssertGreaterThan(r, 0.4, "夜间主题前翻后出现未反相的浅色帧(page \(page),ink=\(r))")
}
for page in stride(from: 3, through: 1, by: -1) {
turnPageAndWait(toPage: page, forward: false)
let r = currentInkRatio()
XCTAssertGreaterThan(r, 0.4, "夜间主题回翻后出现未反相的浅色帧(page \(page),ink=\(r))")
}
switchTheme(toIdentifier: 0) // 浅色
let restoredLight = currentInkRatio()
XCTAssertLessThan(
restoredLight, 0.35,
"切回浅色主题后应立即用浅色帧;陈旧的深色变换缓存未随 apply(theme) 清除(ink=\(restoredLight))"
)
}
// MARK: - 朗读预取遇到暂时无图的页,不应把该页永久变白
//
// 回归点:`speechTextRuns(at:)` 之前会无条件把 provider 返回的 descriptor 写进
// `pageDescriptors`,即使 `image == nil`。之后翻到该页时 `configure` 的
// `guard descriptor == nil else { … return }` 短路,页面永久白屏、也不重试。
// 修复:仅在 `descriptor.image != nil` 时写缓存。
func testSpeechPrefetchDoesNotBlankPageWhenImageArrivesLate() {
// probe=3:宿主 Provider 首次被请求 index 3(第 4 页)时返回 image=nil,
// 之后返回真实图;阅读器加载后用 speechTextRuns 预取到 index 4。
app.launchAndOpenSampleBook(
bookTitleQuery: "英汉大词典",
displayType: "horizontalscroll",
resetsReaderState: true,
pdfTextSource: "none",
pdfSpeechWhitePageProbe: 3
)
app.waitForReader(timeout: 30)
app.waitForReaderPage(1, timeout: 30)
_ = app.waitForDemoReaderState(timeout: 30, description: "朗读预取完成") { $0["speechProbe"] == "done" }
app.hideReaderChromeIfNeeded()
// 翻到第 4 页(index 3)——被预取“污染”的那一页。
for page in 2...4 {
turnPageAndWait(toPage: page, forward: true)
}
let ratio = currentInkRatio()
XCTAssertGreaterThan(
ratio, blankInkRatioThreshold,
"朗读预取到暂时无图的页后,翻到该页仍是白页(ink=\(ratio))——speechTextRuns 不应缓存无图 descriptor"
)
}
// MARK: - 辅助
private func currentInkRatio() -> Double {
RunLoop.current.run(until: Date().addingTimeInterval(0.4))
return inkRatio(of: XCUIScreen.main.screenshot().image)
}
private func turnPageAndWait(toPage page: Int, forward: Bool) {
turnPage(forward: forward)
app.waitForDemoReaderState(timeout: 15, description: "page=\(page)") { $0.page == page }
// 翻页动画 + 异步页面图装配完成后再取样。
RunLoop.current.run(until: Date().addingTimeInterval(1.2))
}
private func switchTheme(toIdentifier identifier: Int) {
app.showReaderChromeIfNeeded()
let settings = app.buttons[IDs.readerSettings]
XCTAssertTrue(settings.waitForExistence(timeout: 5), "设置按钮应存在")
settings.tap()
let themeButton = app.buttons[IDs.settingsTheme(identifier)]
XCTAssertTrue(themeButton.waitForExistence(timeout: 5), "主题按钮 \(identifier) 应存在")
themeButton.tap()
let done = app.buttons[IDs.settingsDone]
if done.waitForExistence(timeout: 3) { done.tap() }
// 面板关闭动画 + 当前页按新主题重绘。
RunLoop.current.run(until: Date().addingTimeInterval(1.0))
}
}