示例工程 59-capstone-polish-and-animation
59-capstone-polish-and-animation/Tests/Ch59KitTests/PolishTests.swift
import Foundation
import SwiftUI
import Testing
@testable import Ch59Kit
@Suite("搜索排序")
struct SearchRankerTests {
private let items = [
RankedBookmark(title: "OpenCode", url: "https://opencode.ai", tags: ["工具"], score: 0),
RankedBookmark(
title: "SwiftData", url: "https://developer.apple.com", tags: ["Swift"], score: 0),
RankedBookmark(title: "Swift 文档", url: "https://swift.org", tags: ["语言"], score: 0),
]
@Test func titlePrefixScoresHighest() {
let ranked = SearchRanker.rank(items, query: "swift")
#expect(ranked.first?.title == "Swift 文档" || ranked.first?.title == "SwiftData")
#expect((ranked.first?.score ?? 0) >= 100)
}
@Test func tagOnlyMatchScoresLower() {
let score = SearchRanker.score(
title: "OpenCode",
url: "https://opencode.ai",
tags: ["swift"],
query: "swift"
)
#expect(score == 40)
}
@Test func urlOnlyMatchScoresLowest() {
let score = SearchRanker.score(
title: "Doc",
url: "https://swift.org",
tags: [],
query: "swift"
)
#expect(score == 20)
}
@Test func emptyQueryKeepsAll() {
#expect(SearchRanker.rank(items, query: " ").count == items.count)
}
@Test func nonMatchingFilteredOut() {
#expect(SearchRanker.rank(items, query: "zzz").isEmpty)
}
@Test func tiesSortByTitle() {
let tied = [
RankedBookmark(title: "B", url: "b", tags: ["x"], score: 40),
RankedBookmark(title: "A", url: "a", tags: ["x"], score: 40),
]
#expect(SearchRanker.rank(tied, query: "x").first?.title == "A")
}
}
@Suite("动效与文案")
struct PolishTests {
@Test func reducedMotionKeepsFade() {
let mode = MotionMode.resolve(reduceMotion: true)
#expect(mode == .reduced)
#expect(mode.listInsertion.contains("淡入"))
#expect(mode.duration < MotionMode.full.duration)
}
@Test func rowLabelIncludesTags() {
#expect(
RowAccessibility.label(title: "Swift", url: "swift.org", tags: ["语言"])
== "Swift,swift.org,标签 语言"
)
}
@Test func emptyTagsFallback() {
#expect(RowAccessibility.label(title: "A", url: "a", tags: []).contains("未分类"))
}
@Test func shortcutRequiresExactModifiers() {
#expect(Shortcut.resolve(key: "f", command: true) == "搜索")
#expect(Shortcut.resolve(key: "f", command: false) == nil)
#expect(Shortcut.resolve(key: "backspace", command: false) == "删除")
}
}
@Suite("视图")
struct PolishViewTests {
@Test @MainActor func boardRendersAtFixedSize() throws {
let image = try #require(ImageRenderer(content: PolishBoard()).cgImage)
#expect(image.width == 360)
#expect(image.height > 120)
}
}
@Suite("截图")
struct ScreenshotTests {
@MainActor
private func writeShot(
_ view: some View,
name: String,
expectedWidth: Int,
minHeight: Int
) throws {
let renderer = ImageRenderer(content: view)
renderer.scale = 2
let image = try #require(renderer.cgImage)
#expect(image.width == expectedWidth)
#expect(image.height >= minHeight)
let url = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("shots/\(name)")
guard !FileManager.default.fileExists(atPath: url.path) else { return }
let data = try #require(
NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
)
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try data.write(to: url)
}
@Test @MainActor func boardShot() throws {
try writeShot(PolishBoard(), name: "polish-board.png", expectedWidth: 720, minHeight: 300)
}
@Test @MainActor func reducedMotionShot() throws {
try writeShot(
ReducedMotionBoard(), name: "polish-reduced.png", expectedWidth: 680, minHeight: 200)
}
@Test @MainActor func accessibilityShot() throws {
try writeShot(
AccessibilityBoard(), name: "polish-accessibility.png", expectedWidth: 680,
minHeight: 240)
}
@Test @MainActor func shortcutsShot() throws {
try writeShot(
ShortcutBoard(), name: "polish-shortcuts.png", expectedWidth: 680, minHeight: 200)
}
}
@Suite("性能")
struct PerformanceTests {
@Test func rank1000ItemsWithinBudget() throws {
let items = (0..<1_000).map {
RankedBookmark(
title: "Item \($0)",
url: "https://example.com/\($0)",
tags: ["tag"],
score: 0
)
}
let clock = ContinuousClock()
var samples: [Duration] = []
for _ in 0..<21 {
let start = clock.now
_ = SearchRanker.rank(items, query: "item")
samples.append(start.duration(to: clock.now))
}
let median = samples.sorted()[samples.count / 2]
#expect(median < .milliseconds(500))
let url = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("expected/perf.txt")
guard !FileManager.default.fileExists(atPath: url.path) else { return }
let milliseconds =
Double(median.components.seconds) * 1_000
+ Double(median.components.attoseconds) / 1e15
let text = """
# ch59 性能参考(非硬门禁;±30% 漂移仅告警)
rank_1000_items_median_ms: \(String(format: "%.3f", milliseconds))
method: SearchRanker.rank on 1000 items, 21 rounds, median, Debug(swift test)
note: Release -O 通常更快;本文件只记录一次参考值,不在 verify 中比对
"""
try text.write(to: url, atomically: true, encoding: .utf8)
}
}