Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

test: 源码文本断言按文件计数只减不增

longmeidao92c64c426336
diff --git a/AGENTS.md b/AGENTS.md
index 54d18af61..c12b4c58b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -70,6 +70,7 @@
- **工作树**:并发改代码时主检出只做集成。每个智能体在 `scripts/agent_worktree.py create` 建于 `peach-worktrees/` 的隔离工作树里干活;提交前 `git rev-parse --show-toplevel` 必须不是主检出(`scripts/githooks/` 拒收主检出 master 上的直接提交与手工 merge),工作者只交分支、从不自己合并。细节见 `peach-worktree`。
- **仓库整洁**:`peach-worktrees/` 与 `.claude/worktrees/` 下都不得留未在 `git worktree list` 注册的目录(`tests/test_repo_hygiene.py`);`prune --apply` 扫空目录,有文件的报出来等人看。不用 `git add .`、`git add -A`、目录路径或 glob,只暂存本任务拥有的文件再核对 `git diff --cached --name-status`;实现与它的测试原子提交。交付提交须署名(`scripts/co_author.py`)。
- **文案只写最终状态**:界面字串、注释、docstring、测试名与文档不写改动前后对比,例外逐行加 `copy-lint-disable-line`(`tests/test_copy_final_state.py`)。
+- **测试写法**:读仓库文件再 `assertIn` 一段写法的源码文本断言按文件计数只减不增(`tests/test_source_assertion_ratchet.py`);行为、设计决定各归何处见 `docs/TESTING.md`「写什么测试」。
- **依赖策略**:Python 依赖精确固定版本,每个被 import 的外部模块要有声明的归属,前端清单与实际 vendored 路径一致,所有清单都进 Dependabot(`tests/test_dependency_policy.py`)。
## 常犯错误(没有自动拦截,都是真实重犯过的)
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index 464f99d9b..62cb253f9 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -133,7 +133,7 @@ shuffle_key 改变随机浏览的序列语义,先测关系筛选收益再决
- 桌面:换 EXE 两条路径(`replace_windows_tray.py` + `windows_update` 内联备份,与 `windows_restart.swap_tray_binary`)留校验更强的后者;`test_runner.py` 把「记录无效」与「用例失败」分成不同退出码(第 33 条的根因);`sync.py` 的 `PUSH_INTERVAL_SECONDS`/`push_if_needed`/`interval` 生产只传 0;`scripts/manage_tray_startup.ps1` 已由 `desktop_startup.py` 接管(同时改 ADR-0011 与 `docs/OPERATIONS.md`);三张「哪些路径算运行时」清单合成一处。
- 领域层:`catalog_rules` 里站名交替串、TLD 列表各写两份;`transcodes.requires_conversion`/`browser_path` 是同一段缓存逻辑;`code_variants` 在 `jav_cover_fetch` 与 `catalog_rules` 各一份;`library_processing` 是第三条 r18 请求路径且跨模块拿私有 `_fetch`;`metadata_seesaa.RoutedMetadataProvider` 只有 `scrape_codes.py` 用,内联。
- scripts:`audit_creator_attributions.py`(查的 `legacy:asset` 已无写入者)、`apply_metadata_tags.py`(绕过 `/review`)、`creator_tags.py --apply-review`(与 `web_review` 判据不同的第二条写路,`--export-review` 要留)建议删;`backfill_rule34_tag_types.py` 2026-09-08 已跑完全部待补条目,连接器早已在入库时取类型,脚本可删;7 处绕开 `scripting.open_for_write`、5 处自拼只读 URI、5 处手写线性重试要接上共享实现;`audit_video_endcards.py`、`audit_fc2_similarity.py`、`localize_series_names.py`、`find_ads.py` 还会用但文档没登记,归到 `peach-batch-jobs` 或 `docs/SOURCING.md`。
- - tests:约 3 700 条源码文本断言集中在 `test_web_ui.py`(近 90 天 20% 的提交都在改它)与 `test_follow_web.py`;页面断言设施两处各写一份;`test_fastapi_api.BASE_SCHEMA` 手写 22 张表,与 `migrations/*.sql` 的漂移未取得;31 个文件手写 `CREATE TABLE`,`tests/support/ledger.py` 有 22 个在用。方向是触碰时迁到 `test_web_js.py` 与 `fresh_ledger()`,不整体重写;`check_copy_final_state.py` 的词表不拦「过去/此前」。
+ - tests:约 5 200 条源码文本断言,4 593 条在 `test_web_ui.py`(近 90 天 20% 的提交都在改它),`test_follow_web.py` 的关注管理页部分已换成 vitest 与 e2e,全文件剩 354 条;棘轮 `test_source_assertion_ratchet.py` 只许减少,换法见 `docs/TESTING.md`「写什么测试」;页面断言设施两处各写一份;`test_fastapi_api.BASE_SCHEMA` 手写 22 张表,与 `migrations/*.sql` 的漂移未取得;31 个文件手写 `CREATE TABLE`,`tests/support/ledger.py` 有 22 个在用。方向是触碰时迁到 `test_web_js.py` 与 `fresh_ledger()`,不整体重写;`check_copy_final_state.py` 的词表不拦「过去/此前」。
- 前端:11 处 `await import('/dist/peach-ui.js')` 与文件顶部静态 import 并存(`test_frontend_build.py` 与 `test_web_ui.py` 钉住了这种写法,要同改);`wireNavigationDrag` 与 `ui-components.wireDragReorder` 双实现;`.fnote` 在 21 与 22 号 CSS 互相覆盖。
- 文档:同一条规则最多写在 19 个文件里(测试入口);`CLAUDE.md` 正文与 AGENTS、worktree 技能重复;本文件的操作 28 与 30 同题,另有一节评审记录。
36. 归一后要用户判的 10 张厂牌标识:AttractiveLLC ×3、C-more_Entertainment ×3、Bambi_Promotion ×2、Deep_s、Tameike_Goro。补到内容外接圆这条规则在「设计上就出血到边」的标识上会把内容推离边缘,逐张判词在 `peach-data/review/refit-review-20260908.csv`,原图在 `peach-data/archive/logos-pre-refit-20260908/`,对比页 `build/logo_compare.html` 的第一节。占宽和圆外损失都分不开 C-more(0.98/0.97)与 MARRION(0.95/0.94),所以没加窄化条件——先由用户定还原哪几张,再按定下来的形状写判据和测试。
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 0373671b3..941f95e94 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -50,6 +50,17 @@ Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及
人名对照等业务测试保留:修改相关域时执行,主线全量也执行。测试数据库从真实迁移生成模板,各用例复制独立临时库;迁移测试直接执行迁移。重试测试注入 sleeper 并断言退避序列。重复继承的测试只保留一份。
+## 写什么测试
+
+测试要能在实现写错时变红。「某段字符串在某个仓库文件里」做不到:关注管理页有 596 条这样的断言,改写成渲染后的行为用例时当场查出三处缺陷,旧断言全都放行——查找链接时等待提示仍说「按名字查」;点下检查后、重读回来前,上一趟的终态被当成这一趟的回执;任务在第一次重读前跑完时,这一趟的结果被丢掉。
+
+- 行为(点了发出什么请求、状态怎么变、算出什么值)写 vitest(`frontend/test/`)或 `tests/test_web_js.py`;后端调用真函数或真接口。
+- 用户定过的设计决定写 `frontend/e2e/design.test.ts`,读 `getComputedStyle`;布局与运行期不变量进 `smoke.test.ts`。
+- 源码文本断言只减不增,由 `tests/test_source_assertion_ratchet.py` 按文件计数拦截;触碰到旧断言时按上面两条换掉,并把基线改小。
+- 先列失败模式再写用例。上面后两处缺陷只在「请求还在路上」时出现,假 fetch 在同一个 `act` 里就回话会把它们盖住;异步流程至少放一条用手动放行的 Promise 卡住中间态的用例。
+- 修缺陷先写一条会失败的用例,看它红了再修;没有行为缺口的改动(文案、纯样式)不补回归用例。
+- 不写同义反复的用例:断言常量等于它自己、mock 掉被测对象再断言 mock 被调用,都证明不了什么。
+
## 正式入口
Windows 按影响域验证:
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 29181b204..61f6223e9 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -27,10 +27,11 @@ if not __package__:
__package__ = "scripts"
from . import test_evidence
-COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py")
+COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py",
+ "test_source_assertion_ratchet.py")
SCOPES: dict[str, tuple[str, ...]] = {
"checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py",
- "test_complexity_ratchet.py"),
+ "test_complexity_ratchet.py", "test_source_assertion_ratchet.py"),
"follow": ("test_follow*.py", "test_http.py", "test_migrations.py"),
"catalog": ("test_ad_judgement.py", "test_composite_name_split.py", "test_media_libraries.py",
"test_content_region.py",
diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.py
new file mode 100644
index 000000000..2fe03de5d
--- /dev/null
+++ b/tests/test_source_assertion_ratchet.py
@@ -0,0 +1,278 @@
+"""源码文本断言棘轮:「某段字符串在某个仓库文件里」这类断言只许减少,不许增加。
+
+这类断言读出 `web/app.js`、样式表或文档的原文,再 `assertIn` 一段写法。它守住的是
+「这几个字符还在」,不是「功能是对的」:换一种等价写法就红,把条件写反了照样绿。
+2026-08-01 到 2026-09-23,`tests/test_web_ui.py` 被 670 个提交改过,净增约 1.3 万行,
+几乎每次界面修复都在同步改这些断言;同期 `docs/PRODUCT_BACKLOG.md` 第 35 项盘出约
+3 700 条这样的断言。改一处样式要同时改它的测试,测试就只是在复述实现。
+
+要守的东西换成能跑的验收:
+- 行为(点了提交什么、状态怎么变、算出什么值)写 vitest(`frontend/test/`)或
+ `tests/test_web_js.py`,后端写调用真函数或真接口的测试;
+- 用户定过的设计决定写 `frontend/e2e/design.test.ts`,读 `getComputedStyle`;
+- 布局与运行期不变量进 `frontend/e2e/smoke.test.ts`;
+- 全仓都该成立的写法约定写成扫描器或 lint(如 `test_complexity_ratchet.py`),
+ 一条规则一个检查,而不是一处写法一条断言。
+
+计数是纯 AST:一个断言调用点算 1——`assertIn`/`assertNotIn` 的被查对象、
+`assertRegex`/`assertNotRegex` 的文本、`assertTrue(x in 文本)` 的右侧,只要来自
+`read_text()` 读出的仓库文件就算;模块里自己定义的、内部读了这种文本的 `assert*`
+辅助方法(如 `assertPageContains`)每次调用也算 1。仓库文件指路径表达式里出现
+`__file__` 的那些,临时目录里造的文件不算。
+
+基线只能降:删掉一条就把基线改小,降到 0 就把那一行删掉。一个文件的计数超过基线
+时,别改写成别的断言绕过去,按上面的去向换成行为验收。
+"""
+import ast
+import pathlib
+import unittest
+
+TESTS = pathlib.Path(__file__).resolve().parent
+
+#: 键是测试文件名,值是这个文件里源码文本断言的调用点数。
+BASELINE: dict[str, int] = {
+ "test_agency_entity.py": 2,
+ "test_buildinfo.py": 3,
+ "test_cloudflared_packaging.py": 2,
+ "test_dependency_policy.py": 26,
+ "test_desktop_settings.py": 17,
+ "test_face_detect.py": 3,
+ "test_fastapi_api.py": 4,
+ "test_follow_assets.py": 2,
+ "test_follow_web.py": 354,
+ "test_frontend_build.py": 86,
+ "test_job_status.py": 3,
+ "test_metadata_library.py": 7,
+ "test_repo_hygiene.py": 2,
+ "test_scripts.py": 33,
+ "test_social_avatar_harvest.py": 2,
+ "test_studio_icon_variants.py": 7,
+ "test_studio_site_harvest.py": 1,
+ "test_subprocess_encoding.py": 2,
+ "test_tray.py": 3,
+ "test_web_e2e.py": 2,
+ "test_web_js.py": 1,
+ "test_web_settings.py": 8,
+ "test_web_ui.py": 4593,
+ "test_windows_update.py": 3,
+}
+
+MEMBERSHIP = {"assertIn", "assertNotIn"}
+PATTERN = {"assertRegex", "assertNotRegex"}
+TRUTH = {"assertTrue", "assertFalse"}
+READS = {"read_text", "read_bytes"}
+
+
+def _outermost_functions(body):
+ for node in body:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ yield node
+ elif isinstance(node, ast.ClassDef):
+ yield from _outermost_functions(node.body)
+
+
+class _Taint:
+ """一个模块里的污点表:哪些名字是仓库路径、哪些是读出来的仓库文本。"""
+
+ def __init__(self, tree: ast.Module):
+ self.path_attrs: set[str] = set()
+ self.text_attrs: set[str] = set()
+ self.helpers: set[str] = set()
+ self.assert_helpers: set[str] = set()
+ # 只取最外层的函数与方法;嵌套函数随外层一起遍历,单列会把它的断言数两遍。
+ self.functions = list(_outermost_functions(tree.body))
+ # 模块级只看顶层语句:函数里的局部名字不是模块级的仓库路径。
+ top = [node for node in tree.body
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))]
+ self.envs: dict[ast.AST, tuple[set[str], set[str]]] = {}
+ for _ in range(10):
+ before = (len(self.path_attrs), len(self.text_attrs), len(self.helpers),
+ len(self.assert_helpers))
+ self.module_env = self._env(top, ({"__file__"}, set()))
+ for function in self.functions:
+ env = self._env(function.body, self.module_env)
+ self.envs[function] = env
+ self._learn(function, env)
+ if before == (len(self.path_attrs), len(self.text_attrs), len(self.helpers),
+ len(self.assert_helpers)):
+ break
+
+ def _self_attr(self, node: ast.AST) -> str | None:
+ if (isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name)
+ and node.value.id in {"self", "cls"}):
+ return node.attr
+ return None
+
+ def is_path(self, node: ast.AST, env) -> bool:
+ paths, _ = env
+ for child in ast.walk(node):
+ if isinstance(child, ast.Name) and child.id in paths:
+ return True
+ if isinstance(child, ast.Attribute) and child.attr == "__file__":
+ return True
+ if self._self_attr(child) in self.path_attrs:
+ return True
+ return False
+
+ def is_text(self, node: ast.AST, env) -> bool:
+ _, texts = env
+ for child in ast.walk(node):
+ if isinstance(child, ast.Name) and child.id in texts:
+ return True
+ if self._self_attr(child) in self.text_attrs:
+ return True
+ if isinstance(child, ast.Call):
+ func = child.func
+ if (isinstance(func, ast.Attribute) and func.attr in READS
+ and self.is_path(func.value, env)):
+ return True
+ if isinstance(func, ast.Name) and func.id in self.helpers:
+ return True
+ if self._self_attr(func) in self.helpers:
+ return True
+ return False
+
+ def _env(self, body, base):
+ """在 `body` 里按赋值、循环与推导式传播污点,直到不再变化。"""
+ paths, texts = set(base[0]), set(base[1])
+ bindings = []
+ for statement in body:
+ for node in ast.walk(statement):
+ if isinstance(node, ast.Assign):
+ bindings.extend((target, node.value) for target in node.targets)
+ elif isinstance(node, (ast.AnnAssign, ast.AugAssign)) and node.value:
+ bindings.append((node.target, node.value))
+ elif isinstance(node, (ast.For, ast.AsyncFor, ast.comprehension)):
+ bindings.append((node.target, node.iter))
+ elif isinstance(node, ast.withitem) and node.optional_vars is not None:
+ bindings.append((node.optional_vars, node.context_expr))
+ changed = True
+ while changed:
+ changed = False
+ env = (paths, texts)
+ for target, value in bindings:
+ path, text = self.is_path(value, env), self.is_text(value, env)
+ if not (path or text):
+ continue
+ for name in ast.walk(target):
+ if isinstance(name, ast.Name):
+ if path and name.id not in paths:
+ paths.add(name.id)
+ changed = True
+ if text and name.id not in texts:
+ texts.add(name.id)
+ changed = True
+ return paths, texts
+
+ def _learn(self, function, env):
+ """从一个函数里学到:它写进 self/cls 的属性、它是不是返回文本的辅助函数。"""
+ for node in ast.walk(function):
+ if isinstance(node, ast.Assign):
+ for target in node.targets:
+ attr = self._self_attr(target)
+ if attr is None:
+ continue
+ if self.is_text(node.value, env):
+ self.text_attrs.add(attr)
+ elif self.is_path(node.value, env):
+ self.path_attrs.add(attr)
+ elif (isinstance(node, ast.Return) and node.value is not None
+ and self.is_text(node.value, env)):
+ self.helpers.add(function.name)
+ if function.name.startswith("assert") and any(
+ isinstance(node, ast.expr) and self.is_text(node, env)
+ for node in ast.walk(function)):
+ self.assert_helpers.add(function.name)
+
+ def count(self) -> int:
+ total = 0
+ for function in self.functions:
+ if function.name in self.assert_helpers:
+ continue
+ env = self.envs[function]
+ for node in ast.walk(function):
+ if isinstance(node, ast.Call) and self._counts(node, env):
+ total += 1
+ return total
+
+ def _counts(self, call: ast.Call, env) -> bool:
+ name = self._self_attr(call.func)
+ if name is None:
+ return False
+ if name in self.assert_helpers:
+ return True
+ args = call.args
+ if name in MEMBERSHIP and len(args) >= 2:
+ return self.is_text(args[1], env)
+ if name in PATTERN and args:
+ return self.is_text(args[0], env)
+ if name in TRUTH and args and isinstance(args[0], ast.Compare):
+ compare = args[0]
+ return (any(isinstance(op, (ast.In, ast.NotIn)) for op in compare.ops)
+ and any(self.is_text(side, env) for side in compare.comparators))
+ return False
+
+
+def source_assertions(source: str) -> int:
+ """一段测试源码里源码文本断言的调用点数。"""
+ return _Taint(ast.parse(source)).count()
+
+
+def survey() -> dict[str, int]:
+ found = {}
+ for path in sorted(TESTS.glob("test_*.py")):
+ count = source_assertions(path.read_text(encoding="utf-8"))
+ if count:
+ found[path.name] = count
+ return found
+
+
+class SourceAssertionRatchetTests(unittest.TestCase):
+ def test_the_counter_tells_repository_text_from_runtime_output(self):
+ source = (
+ "import pathlib, unittest\n"
+ "ROOT = pathlib.Path(__file__).resolve().parents[1]\n"
+ "def stylesheet():\n"
+ " return (ROOT / 'web' / 'a.css').read_text()\n"
+ "class T(unittest.TestCase):\n"
+ " @classmethod\n"
+ " def setUpClass(cls):\n"
+ " cls.page = (ROOT / 'web' / 'app.js').read_text()\n"
+ " def assertPageContains(self, needle):\n"
+ " self.assertTrue(needle in self.page)\n"
+ " def test_source(self):\n"
+ " app = (ROOT / 'web' / 'app.js').read_text()\n"
+ " body = app[app.index('a'):]\n"
+ " self.assertIn('x', body)\n" # 1:切片仍是源码
+ " self.assertNotIn('y', stylesheet())\n" # 2:辅助函数返回源码
+ " self.assertRegex(self.page, 'z')\n" # 3:setUpClass 读的属性
+ " self.assertPageContains('w')\n" # 4:自带的源码断言辅助
+ " for key in ('a', 'b'):\n"
+ " self.assertIn(key, app)\n" # 5:调用点只算一次
+ " joined = ''.join(p.read_text() for p in (ROOT / 'web').glob('*.js'))\n"
+ " self.assertTrue('q' in joined)\n" # 6:推导式读的也算
+ " def test_behaviour(self, tmp='t'):\n"
+ " out = pathlib.Path(tmp) / 'x.txt'\n"
+ " self.assertIn('x', out.read_text())\n" # 临时文件不算
+ " self.assertIn('ok', run(ROOT / 'scripts' / 's.py'))\n" # 跑出来的输出不算
+ )
+ self.assertEqual(source_assertions(source), 6)
+
+ def test_no_test_file_grew_past_its_baseline(self):
+ grown = sorted(f"{name}: {count}(基线 {BASELINE.get(name, 0)})"
+ for name, count in survey().items() if count > BASELINE.get(name, 0))
+ self.assertEqual(grown, [],
+ "这些测试文件的源码文本断言多了。别改写成别的断言绕过,按本文件开头的"
+ "去向换成行为验收:\n " + "\n ".join(grown))
+
+ def test_the_baseline_only_ratchets_down(self):
+ current = survey()
+ stale = sorted(f"{name}: 现在 {current.get(name, 0)},基线 {value}"
+ for name, value in BASELINE.items() if current.get(name, 0) < value)
+ self.assertEqual(stale, [],
+ "基线落后于测试:删掉断言后把这里改小,降到 0 就删掉那一行,"
+ "不给将来的增长留余量:\n " + "\n ".join(stale))
+
+
+if __name__ == "__main__":
+ unittest.main()