完善搜索定位与内存监测回归验证

本次提交围绕搜索链路的稳定性、定位恢复体验以及长章节内存优化的验证能力进行了补强。

主要改动:

1. 调整阅读器搜索栏、搜索协调器与定位恢复逻辑,改善搜索结果跳转、状态同步与相关 UI 行为。

2. 补充内存探针接入点与上下文记录,便于跟踪阅读过程中的内存占用变化。

3. 更新 RDURLReaderController、ReaderContext 与工具视图相关实现,使调试与观测链路更完整。

4. 新增 MemoryFootprintTests,并同步更新 DemoReaderState 与 SearchTests,用 UI 测试覆盖搜索与内存相关回归场景。
This commit is contained in:
shenlei
2026-07-09 18:46:04 +09:00
parent c4be426299
commit 83dfa40299
11 changed files with 338 additions and 89 deletions
@@ -58,6 +58,7 @@ struct DemoReaderState {
var lastExternalURL: String? { decodedField("lastExternalURL") }
var lastError: String? { decodedField("lastError") }
var searchMatchText: String? { decodedField("searchMatchText") }
var footprintMB: Double? { fields["footprintMB"].flatMap(Double.init) }
}
extension XCUIApplication {
@@ -0,0 +1,147 @@
import XCTest
/// Quantitative memory-footprint harness for the long-chapter optimization
/// (Doc/LONG_CHAPTER_MEMORY_OPTIMIZATION_PLAN.md, P0-2 / P1-4 / P2). Reads
/// phys_footprint back through the demo state `footprintMB` field, so these
/// tests double as a decision tool: the recorded numbers are attached to the
/// result, and the assertions are deliberately loose upper bounds that only
/// catch gross regressions (e.g. each visible page pinning a full-chapter
/// copy), not few-MB noise.
final class MemoryFootprintTests: XCTestCase {
private let app = XCUIApplication()
private let largeBookQuery = "凡人修仙传"
/// Turning 20 pages must not grow footprint beyond this over the post-open
/// baseline. Sized to flag "per-page full-chapter copy" class leaks while
/// tolerating cache warmup and simulator noise.
private let pageTurnGrowthBudgetMB = 180.0
/// A settings change rebuilds display objects; peak may spike transiently
/// but must settle back within this of the pre-change reading.
private let settingsChangeGrowthBudgetMB = 220.0
override func setUpWithError() throws {
continueAfterFailure = false
}
func testFootprintStableAcrossTwentyPageTurns() throws {
app.launchAndOpenSampleBook(
bookTitleQuery: largeBookQuery,
displayType: "scroll",
resetsReaderState: true
)
app.waitForReader(timeout: 20)
app.waitForDemoReaderState(timeout: 8, description: "display=horizontalScroll") {
$0.display == "horizontalScroll"
}
let baseline = try requireFootprint(description: "打开长书后基线")
let paging = app.collectionViews[IDs.readerPaging]
XCTAssertTrue(paging.waitForExistence(timeout: 5), "分页滚动视图未出现")
var readings: [Double] = [baseline]
var lastPage = app.currentDemoReaderState()?.page ?? 0
var turnsMade = 0
for _ in 0..<20 {
paging.swipeLeft()
let state = app.waitForDemoReaderState(timeout: 8, description: "翻页后页码变化") { state in
guard let page = state.page else { return false }
return page != lastPage
}
guard let page = state.page, page != lastPage else { break }
lastPage = page
turnsMade += 1
if let footprint = state.footprintMB {
readings.append(footprint)
}
}
let peak = readings.max() ?? baseline
let final = readings.last ?? baseline
let growth = final - baseline
attachReport(
name: "page-turns",
lines: [
"turnsMade=\(turnsMade)",
"baselineMB=\(fmt(baseline))",
"peakMB=\(fmt(peak))",
"finalMB=\(fmt(final))",
"growthMB=\(fmt(growth))",
"budgetMB=\(fmt(pageTurnGrowthBudgetMB))",
"series=\(readings.map(fmt).joined(separator: ","))"
]
)
XCTAssertGreaterThan(turnsMade, 0, "未能翻动任何页,无法测量翻页内存")
XCTAssertLessThan(
growth, pageTurnGrowthBudgetMB,
"连续翻页后常驻内存增长 \(fmt(growth))MB 超出预算 \(fmt(pageTurnGrowthBudgetMB))MB(疑似每页驻留整章副本)"
)
}
func testFootprintSettlesAfterFontSizeChange() throws {
app.launchAndOpenSampleBook(
bookTitleQuery: largeBookQuery,
resetsReaderState: true
)
app.waitForReader(timeout: 20)
app.showReaderChromeIfNeeded()
let before = try requireFootprint(description: "改字号前")
XCTAssertTrue(app.buttons[IDs.readerSettings].waitForExistence(timeout: 5), "设置按钮不存在")
app.buttons[IDs.readerSettings].tap()
XCTAssertTrue(app.scrollViews[IDs.settingsScroll].waitForExistence(timeout: 5), "设置面板未出现")
XCTAssertTrue(app.buttons[IDs.settingsFontIncrease].waitForExistence(timeout: 3), "字号增大按钮不存在")
app.buttons[IDs.settingsFontIncrease].tap()
app.buttons[IDs.settingsFontIncrease].tap()
XCTAssertTrue(app.buttons[IDs.settingsDone].waitForExistence(timeout: 3), "完成按钮不存在")
app.buttons[IDs.settingsDone].tap()
// Allow repagination + display-cache rebuild to settle.
RunLoop.current.run(until: Date().addingTimeInterval(2.5))
let after = try requireFootprint(description: "改字号并重排后")
let growth = after - before
attachReport(
name: "font-size-change",
lines: [
"beforeMB=\(fmt(before))",
"afterMB=\(fmt(after))",
"growthMB=\(fmt(growth))",
"budgetMB=\(fmt(settingsChangeGrowthBudgetMB))"
]
)
XCTAssertLessThan(
growth, settingsChangeGrowthBudgetMB,
"改字号重排后常驻内存增长 \(fmt(growth))MB 超出预算 \(fmt(settingsChangeGrowthBudgetMB))MB(疑似旧显示对象未释放)"
)
}
// MARK: - Helpers
private func requireFootprint(description: String) throws -> Double {
let state = app.waitForDemoReaderState(timeout: 8, description: description) {
($0.footprintMB ?? 0) > 0
}
guard let footprint = state.footprintMB, footprint > 0 else {
throw XCTSkip("demo 状态未暴露 footprintMB,跳过内存测量:\(state.rawValue)")
}
return footprint
}
private func fmt(_ value: Double) -> String {
String(format: "%.1f", value)
}
private func attachReport(name: String, lines: [String]) {
let text = lines.joined(separator: "\n")
let attachment = XCTAttachment(string: text)
attachment.name = "memory-\(name)"
attachment.lifetime = .keepAlways
add(attachment)
print("[MemoryFootprintTests] \(name)\n\(text)")
}
}
@@ -209,7 +209,9 @@ final class SearchTests: XCTestCase {
XCTAssertFalse(searchBar.waitForExistence(timeout: 2), "关闭后搜索栏应消失")
}
// MARK: -
// MARK: -
// chrome
// chrome /
func testSearchBarHidesWhenToolbarsHide() {
app.launchAndOpenSampleBook(searchKeyword: "")
@@ -217,12 +219,15 @@ final class SearchTests: XCTestCase {
app.showReaderChromeIfNeeded()
let searchBar = app.otherElements[IDs.searchBar]
XCTAssertTrue(searchBar.waitForExistence(timeout: 10), "搜索应可见")
XCTAssertTrue(searchBar.waitForExistence(timeout: 10), "搜索面板应可见")
//
//
selectSearchResult(at: 0)
XCTAssertFalse(searchBar.waitForExistence(timeout: 2), "选中结果后搜索面板应关闭")
//
app.hideReaderChromeIfNeeded()
XCTAssertFalse(searchBar.waitForExistence(timeout: 2), "工具栏隐藏时搜索栏也应隐藏")
XCTAssertFalse(searchBar.waitForExistence(timeout: 2), "工具栏隐藏时搜索面板应保持关闭")
}
func testSearchBarRestoresWhenToolbarsShow() {
@@ -233,13 +238,14 @@ final class SearchTests: XCTestCase {
let searchBar = app.otherElements[IDs.searchBar]
XCTAssertTrue(searchBar.waitForExistence(timeout: 10))
//
//
selectSearchResult(at: 0)
app.hideReaderChromeIfNeeded()
XCTAssertFalse(searchBar.waitForExistence(timeout: 2))
//
//
app.showReaderChromeIfNeeded()
XCTAssertTrue(searchBar.waitForExistence(timeout: 3), "工具栏恢复时搜索也应恢复")
XCTAssertTrue(searchBar.waitForExistence(timeout: 3), "工具栏恢复时搜索面板也应恢复")
//
let countLabel = app.staticTexts[IDs.searchCount]
@@ -286,6 +292,9 @@ final class SearchTests: XCTestCase {
}
let rangeCFIBefore = stateBefore.rangeCFI
//
selectSearchResult(at: 0)
//
app.showReaderChromeIfNeeded()
let settingsButton = app.buttons[IDs.readerSettings]
@@ -304,8 +313,8 @@ final class SearchTests: XCTestCase {
}
Thread.sleep(forTimeInterval: 1)
//
app.showReaderChromeIfNeeded()
//
reopenSearchPanel()
let prevButton = app.buttons[IDs.searchPrevious]
let nextButton = app.buttons[IDs.searchNext]
if prevButton.waitForExistence(timeout: 3), prevButton.isEnabled {
@@ -349,6 +358,9 @@ final class SearchTests: XCTestCase {
return
}
//
selectSearchResult(at: 0)
//
app.showReaderChromeIfNeeded()
let settingsButton = app.buttons[IDs.readerSettings]
@@ -367,15 +379,9 @@ final class SearchTests: XCTestCase {
}
Thread.sleep(forTimeInterval: 1)
//
let nextButton = app.buttons[IDs.searchNext]
let prevButton = app.buttons[IDs.searchPrevious]
XCTAssertTrue(nextButton.waitForExistence(timeout: 3), "下一个按钮应存在")
XCTAssertTrue(prevButton.waitForExistence(timeout: 3), "上一个按钮应存在")
// 2
nextButton.tap()
Thread.sleep(forTimeInterval: 0.5)
// 2
reopenSearchPanel()
selectSearchResult(at: 1)
let stateMatch2 = app.waitForDemoReaderState(timeout: 5, description: "match 2 page") {
($0.page ?? 0) > 0 && $0.rangeCFI?.isEmpty == false
}
@@ -383,18 +389,11 @@ final class SearchTests: XCTestCase {
let rangeCFIAtMatch2 = stateMatch2.rangeCFI
//
let content = app.otherElements[IDs.readerContent].firstMatch
if content.waitForExistence(timeout: 3) {
for _ in 0..<4 {
content.swipeLeft()
Thread.sleep(forTimeInterval: 0.3)
}
Thread.sleep(forTimeInterval: 0.5)
}
swipeAwayFromCurrentPage()
// 3
nextButton.tap()
Thread.sleep(forTimeInterval: 0.5)
// 3
reopenSearchPanel()
selectSearchResult(at: 2)
let stateMatch3 = app.waitForDemoReaderState(timeout: 5, description: "match 3 page") {
($0.page ?? 0) > 0 && $0.rangeCFI?.isEmpty == false
}
@@ -402,17 +401,11 @@ final class SearchTests: XCTestCase {
let rangeCFIAtMatch3 = stateMatch3.rangeCFI
//
if content.waitForExistence(timeout: 3) {
for _ in 0..<4 {
content.swipeLeft()
Thread.sleep(forTimeInterval: 0.3)
}
Thread.sleep(forTimeInterval: 0.5)
}
swipeAwayFromCurrentPage()
// 2
prevButton.tap()
Thread.sleep(forTimeInterval: 0.5)
reopenSearchPanel()
selectSearchResult(at: 1)
let stateBack2 = app.waitForDemoReaderState(timeout: 5, description: "back to match 2") {
$0.page == pageAtMatch2 && $0.rangeCFI == rangeCFIAtMatch2
}
@@ -422,17 +415,11 @@ final class SearchTests: XCTestCase {
"重排后搜索跳回第 2 个匹配应命中同一段文本")
//
if content.waitForExistence(timeout: 3) {
for _ in 0..<4 {
content.swipeLeft()
Thread.sleep(forTimeInterval: 0.3)
}
Thread.sleep(forTimeInterval: 0.5)
}
swipeAwayFromCurrentPage()
// 3
nextButton.tap()
Thread.sleep(forTimeInterval: 0.5)
reopenSearchPanel()
selectSearchResult(at: 2)
let stateBack3 = app.waitForDemoReaderState(timeout: 5, description: "back to match 3") {
$0.page == pageAtMatch3 && $0.rangeCFI == rangeCFIAtMatch3
}
@@ -452,4 +439,39 @@ final class SearchTests: XCTestCase {
let searchBar = app.otherElements[IDs.searchBar]
XCTAssertTrue(searchBar.waitForExistence(timeout: 3), "搜索栏应出现")
}
///
private func selectSearchResult(at matchIndex: Int) {
let cell = app.cells["epub.reader.search.result.\(matchIndex)"].firstMatch
XCTAssertTrue(cell.waitForExistence(timeout: 10), "搜索结果第 \(matchIndex) 项应存在")
cell.tap()
RunLoop.current.run(until: Date().addingTimeInterval(0.5))
}
/// chrome
/// chrome
private func reopenSearchPanel() {
app.showReaderChromeIfNeeded()
let searchBar = app.otherElements[IDs.searchBar]
if searchBar.waitForExistence(timeout: 2) {
return
}
let searchButton = app.buttons[IDs.readerSearch]
XCTAssertTrue(searchButton.waitForExistence(timeout: 3), "搜索按钮应存在")
searchButton.tap()
XCTAssertTrue(searchBar.waitForExistence(timeout: 3), "搜索面板应重新打开")
}
/// chrome 使
private func swipeAwayFromCurrentPage() {
app.hideReaderChromeIfNeeded()
let content = app.otherElements[IDs.readerContent].firstMatch
if content.waitForExistence(timeout: 3) {
for _ in 0..<4 {
content.swipeLeft()
Thread.sleep(forTimeInterval: 0.3)
}
Thread.sleep(forTimeInterval: 0.5)
}
}
}