Skip to content

armgit / peach

Public Imported from GitHub
0

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

test(web): 加入真浏览器冒烟层,界面通用不变量由测试入口执行

longmeidaoa6b3c6143491
diff --git a/.claude/skills/peach-web-ui/SKILL.md b/.claude/skills/peach-web-ui/SKILL.md
index 1e6567f79..3f5d639ae 100644
--- a/.claude/skills/peach-web-ui/SKILL.md
+++ b/.claude/skills/peach-web-ui/SKILL.md
@@ -5,7 +5,7 @@ description: 在新增、修改或复核 Peach 页面、控件、提示、错误
# Peach Web UI 复用门槛
-最后复核:2026-09-08
+最后复核:2026-09-15
## 开工顺序
@@ -84,7 +84,8 @@ description: 在新增、修改或复核 Peach 页面、控件、提示、错误
1. 为语义、DOM、ARIA、复用模块和响应式规则补页面源测试;数据语义变更另补 API/数据层测试。
2. Windows 从隔离 worktree 根运行 `& .\scripts\test.ps1`,默认 `auto`;按影响域补测,规则见 `peach-worktree`。
-3. 在本地预览检查桌面与 390×844:页面宽度不大于视口、弹层不越界、菜单内部滚动、键盘 focus 可见、控制台无错误。托盘服务发的是主检出的 `web/`,看不到 worktree 里的改动:从 worktree 根另起一个实例再验收,`python -m peach serve --host 127.0.0.1 --port 8099 --no-mdns --no-ledger-sync`(`PYTHONPATH=<worktree>/src`),验完停掉,托盘那个不动。点第一下之前先把 `peach.settings.v1` 的 `detailAutoplay` 置 false:用户就在这台机器旁,任何一次点进详情都会出声,无论这轮验收的是不是播放器。
-4. 接口字段、sidecar 取值和锚点算术走 Python 严格 HTTPS(项目 CA 加 `ProxyHandler({})`)核对,不进浏览器。浏览器只留给布局后才成立的事实:`getComputedStyle`、真实裁切几何、hover/focus 态和实际像素;用读源码顶替这几样是降精度。
-5. 一轮验收要读的页面状态先列全,再合成一次 `javascript_tool` 调用取回。私有网络主机(`.local` 与 `10.`/`172.16-31.`/`192.168.` 段的局域网 IP 归同一类)在桌面应用里只能逐次授权,站点级放行只给只读工具,点击与执行 JS 拿不到常驻许可,每多发一次调用就多一次弹窗。
-6. 按 `peach-surfaces` 报告数据层、API、页面、契约、测试与文档各影响面;未部署不得称为生产已生效。
+3. 桌面与 390×844 的通用不变量(无横向溢出、无越出视口的元素、等待态会结束、控制台无错误、无失败请求)由 `web` 域的 `tests/test_web_e2e.py` 执行,不再逐页手测;新路由加进 `frontend/e2e/smoke.test.ts` 的 `ROUTES`。浏览器里发现的可判定问题(几何、computed style、状态切换),先在 `frontend/e2e/` 写出失败用例再修。
+4. Browser 面板只留给用例表达不了的:新布局首次成形、对齐外部参考、hover/focus 与观感判断。托盘服务发的是主检出的 `web/`:从 worktree 根另起实例,`python -m peach serve --host 127.0.0.1 --port 8099 --no-mdns --no-ledger-sync`(`PYTHONPATH=<worktree>/src`),验完停掉。点第一下之前先把 `peach.settings.v1` 的 `detailAutoplay` 置 false:用户就在这台机器旁,点进详情会出声。
+5. 接口字段、sidecar 取值和锚点算术走 Python 严格 HTTPS(项目 CA 加 `ProxyHandler({})`)核对,不进浏览器。浏览器只留给布局后才成立的事实:`getComputedStyle`、真实裁切几何、hover/focus 态和实际像素;用读源码顶替这几样是降精度。
+6. 一轮验收要读的页面状态先列全,再合成一次 `javascript_tool` 调用取回。私有网络主机(`.local` 与 `10.`/`172.16-31.`/`192.168.` 段的局域网 IP 归同一类)在桌面应用里只能逐次授权,站点级放行只给只读工具,点击与执行 JS 拿不到常驻许可,每多发一次调用就多一次弹窗。
+7. 按 `peach-surfaces` 报告数据层、API、页面、契约、测试与文档各影响面;未部署不得称为生产已生效。
diff --git a/docs/FRONTEND.md b/docs/FRONTEND.md
index 1b7db6696..a8647dcc8 100644
--- a/docs/FRONTEND.md
+++ b/docs/FRONTEND.md
@@ -111,6 +111,14 @@ npm --prefix frontend run typecheck
它的门槛在 CI 的 `web-bundle` job:`npm run build` 之后 `git diff --exit-code -- web/dist`。
**改了 `frontend/src` 就必须重新构建并把 `web/dist/` 一起提交**,否则 CI 会红。
+同一个域里还有真浏览器冒烟 `tests/test_web_e2e.py`:它在临时数据根上生成 12 条合成演示库、
+起回环 `peach serve --no-auth`,再跑 `npm --prefix frontend run e2e`。用例在
+`frontend/e2e/smoke.test.ts`,每条主路由在桌面与 390×844 下断言:无页面异常与 `console.error`、
+无同源 4xx/5xx 与失败请求、`aria-busy` 与 `data-skeleton` 会消失、无横向溢出、无越出视口的元素。
+浏览器取本机 Google Chrome(`PEACH_E2E_CHROME` 可指定),短片由 ffmpeg 编码;缺 npm、
+`playwright-core`、ffmpeg 或 Chrome 时显式跳过。声明根是 Windows 形态,目前只在 Windows 上执行。界面验收里发现的同类问题,
+先在这里补一条用例再修。
+
## 挂载契约
```js
@@ -227,6 +235,7 @@ vendor 到 `web/vendor/` 的四个包(video.js、swiper、lucide-static、heal
| `typescript` | 类型即契约:注册表、props 与端点响应都靠它在编译期拦住漂移 |
| `vitest` | 前端测试运行器。与 Vite 共用同一份配置解析,不必再维护第二套转译 |
| `happy-dom` | vitest 的 DOM 环境。断言的是真实 DOM 结构,比 jsdom 轻且启动快 |
+| `playwright-core` | `frontend/e2e/` 的浏览器驱动,只驱动本机 Chrome、不下载浏览器。happy-dom 没有布局,横向溢出、等待态卡住这类事实只有真浏览器测得出;不用 `@playwright/test`,用例跑在 `node:test` 上,与 docu.md(`markdown-viewer/markdown-viewer-extension` 的 `test/helpers/browser-render-harness.ts`)同一做法 |
| `react`、`react-dom` | React 子树的渲染层。BoardUI 源码是 React 组件,交互建在 React Aria 上,Preact 的兼容层不在 React Aria 的支持范围内 |
| `react-aria-components` | BoardUI 输入框与勾选框的交互和无障碍语义:标签关联、键盘操作、`aria-invalid` |
| `tailwind-merge` | BoardUI 的 `cx()` 合并类名时去掉互相冲突的工具类 |
diff --git a/frontend/e2e/harness.ts b/frontend/e2e/harness.ts
new file mode 100644
index 000000000..156c56780
--- /dev/null
+++ b/frontend/e2e/harness.ts
@@ -0,0 +1,126 @@
+/* 真浏览器冒烟的夹具:打开页面、收集运行期问题、测布局几何。
+ *
+ * 只用 playwright-core 驱动本机已装的 Chrome,不下载浏览器;路径由
+ * `tests/test_web_e2e.py` 探测后经 PEACH_E2E_CHROME 传进来。服务、账本和演示库
+ * 也归 Python 那一侧准备,这里只认 PEACH_E2E_ORIGIN。
+ *
+ * 用例只写语义断言(没有横向溢出、等待态会结束、控制台无错误),不做截图比对:
+ * 单人部署里维护基线图的成本高于它能拦住的问题。 */
+import { chromium, type Browser, type BrowserContext, type Page } from 'playwright-core';
+
+export interface Viewport {
+ name: string;
+ width: number;
+ height: number;
+ mobile: boolean;
+}
+
+export const VIEWPORTS: readonly Viewport[] = [
+ { name: 'desktop', width: 1280, height: 800, mobile: false },
+ { name: 'mobile', width: 390, height: 844, mobile: true },
+];
+
+export interface Visit {
+ page: Page;
+ /** 页面异常、console.error、同源 4xx/5xx 与失败请求,按发生顺序。 */
+ problems: string[];
+ close(): Promise<void>;
+}
+
+export interface Layout {
+ viewportWidth: number;
+ scrollWidth: number;
+ /** 右边缘越出视口、且没有被任何祖先横向裁切的可见元素,最多列 5 个。 */
+ offenders: string[];
+}
+
+export function requiredEnv(name: string): string {
+ const value = process.env[name];
+ if (!value) throw new Error(`${name} 未设置:用 \`tests/test_web_e2e.py\` 起服务后再跑`);
+ return value;
+}
+
+export async function launch(): Promise<Browser> {
+ return chromium.launch({ headless: true, executablePath: requiredEnv('PEACH_E2E_CHROME') });
+}
+
+/** 等待态以 `aria-busy="true"` 与 `data-skeleton` 为准;超时就是等待态卡住了。 */
+async function settle(page: Page): Promise<void> {
+ await page.waitForLoadState('networkidle');
+ await page.waitForFunction(
+ () => !document.querySelector('[aria-busy="true"],[data-skeleton]'),
+ undefined, { timeout: 15_000 });
+}
+
+export async function visit(browser: Browser, path: string, viewport: Viewport): Promise<Visit> {
+ const origin = requiredEnv('PEACH_E2E_ORIGIN');
+ const context: BrowserContext = await browser.newContext({
+ viewport: { width: viewport.width, height: viewport.height },
+ isMobile: viewport.mobile,
+ hasTouch: viewport.mobile,
+ reducedMotion: 'reduce',
+ });
+ // 详情页默认自动播放;这台机器旁边有人,冒烟不出声。
+ await context.addInitScript(() => {
+ localStorage.setItem('peach.settings.v1', JSON.stringify({ detailAutoplay: false }));
+ });
+ const page = await context.newPage();
+ const problems: string[] = [];
+ page.on('pageerror', (error) => problems.push(`pageerror ${error.message}`));
+ page.on('console', (message) => {
+ if (message.type() === 'error') problems.push(`console ${message.text()}`);
+ });
+ page.on('response', (response) => {
+ if (response.url().startsWith(origin) && response.status() >= 400) {
+ problems.push(`${response.status()} ${response.url().slice(origin.length)}`);
+ }
+ });
+ page.on('requestfailed', (request) => {
+ const reason = request.failure()?.errorText ?? '';
+ if (request.url().startsWith(origin) && !reason.includes('ERR_ABORTED')) {
+ problems.push(`failed ${request.url().slice(origin.length)} ${reason}`);
+ }
+ });
+ await page.goto(origin + path, { waitUntil: 'load' });
+ await settle(page);
+ return { page, problems, close: () => context.close() };
+}
+
+/* 越界名单只报根因:页面一旦被撑宽,移动视口跟着变宽,`fixed` 的顶栏、Toast 会一起
+ * 伸出去,按文档顺序截前几个就只剩这些症状。所以跳过 `fixed` 及其后代,并且只留
+ * 父元素自己没越界的那一层。 */
+export async function layout(page: Page): Promise<Layout> {
+ return page.evaluate(() => {
+ const width = document.documentElement.clientWidth;
+ const excused = (element: Element): boolean => {
+ if (getComputedStyle(element).position === 'fixed') return true;
+ for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
+ const style = getComputedStyle(parent);
+ if (style.overflowX !== 'visible' || style.position === 'fixed') return true;
+ }
+ return false;
+ };
+ const label = (element: Element): string => {
+ const id = element.id ? `#${element.id}` : '';
+ const classes = [...element.classList].slice(0, 2).map((name) => `.${name}`).join('');
+ return `${element.tagName.toLowerCase()}${id}${classes}`;
+ };
+ const overflowing = new Set<Element>();
+ for (const element of document.body.querySelectorAll('*')) {
+ const box = element.getBoundingClientRect();
+ if (box.width === 0 || box.height === 0 || box.right <= width + 1) continue;
+ const style = getComputedStyle(element);
+ if (style.visibility === 'hidden' || style.display === 'none' || excused(element)) continue;
+ overflowing.add(element);
+ }
+ const offenders = [...overflowing]
+ .filter((element) => !element.parentElement || !overflowing.has(element.parentElement))
+ .slice(0, 5)
+ .map((element) => `${label(element)} right=${Math.round(element.getBoundingClientRect().right)}`);
+ return {
+ viewportWidth: width,
+ scrollWidth: Math.max(document.documentElement.scrollWidth, document.body.scrollWidth),
+ offenders,
+ };
+ });
+}
diff --git a/frontend/e2e/smoke.test.ts b/frontend/e2e/smoke.test.ts
new file mode 100644
index 000000000..d3bc44b61
--- /dev/null
+++ b/frontend/e2e/smoke.test.ts
@@ -0,0 +1,54 @@
+/* 每条主路由在桌面与 390×844 下都要守住的不变量。
+ *
+ * 这些是界面验收里每一轮都要重测的几何与运行期事实:写成用例之后由测试入口执行,
+ * 浏览器面板只留给新布局首次成形和观感判断。新发现的同类问题先在这里补一条再修。 */
+import assert from 'node:assert/strict';
+import { after, before, describe, it } from 'node:test';
+
+import type { Browser } from 'playwright-core';
+
+import { layout, launch, requiredEnv, visit, VIEWPORTS } from './harness.ts';
+
+const ROUTES = [
+ '/',
+ '/performers',
+ '/studios',
+ '/tags',
+ '/playlists',
+ '/follow',
+ '/stats',
+ '/review',
+ '/data-cleanup',
+ '/configuration',
+ '/activity',
+ `/item/${requiredEnv('PEACH_E2E_ITEM')}`,
+];
+
+describe('路由冒烟', () => {
+ let browser: Browser;
+
+ before(async () => {
+ browser = await launch();
+ });
+
+ after(async () => {
+ await browser.close();
+ });
+
+ for (const viewport of VIEWPORTS) {
+ for (const route of ROUTES) {
+ it(`${route} @ ${viewport.name}`, async () => {
+ const opened = await visit(browser, route, viewport);
+ try {
+ assert.deepEqual(opened.problems, [], '页面报错或有失败请求');
+ const box = await layout(opened.page);
+ assert.ok(box.scrollWidth <= box.viewportWidth,
+ `横向溢出:scrollWidth ${box.scrollWidth} > 视口 ${box.viewportWidth}`);
+ assert.deepEqual(box.offenders, [], '有元素越出视口右边缘');
+ } finally {
+ await opened.close();
+ }
+ });
+ }
+ }
+});
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index f4612256e..5a799f7ac 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -21,6 +21,7 @@
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"happy-dom": "20.14.0",
+ "playwright-core": "1.63.0",
"tailwindcss": "4.3.3",
"typescript": "7.0.2",
"vite": "8.2.2",
@@ -2070,6 +2071,19 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/playwright-core": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 4cde300b7..6f6c48a66 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -11,7 +11,8 @@
"build": "vite build && vite build -c vite.react.config.ts",
"typecheck": "tsc --noEmit && tsc --noEmit -p src/react",
"test": "vitest run",
- "test:watch": "vitest"
+ "test:watch": "vitest",
+ "e2e": "node --test --test-reporter=tap \"e2e/**/*.test.ts\""
},
"dependencies": {
"@preact/signals": "2.11.1",
@@ -29,6 +30,7 @@
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"happy-dom": "20.14.0",
+ "playwright-core": "1.63.0",
"tailwindcss": "4.3.3",
"typescript": "7.0.2",
"vite": "8.2.2",
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 969bbafa8..76a5b930b 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -106,7 +106,8 @@ SCOPES: dict[str, tuple[str, ...]] = {
# 后面七个文件的主体不在这一层,但各有一段断言读 `web/` 或 `frontend/` 的源码,
# 所以本域也要登记它们:改了 `web/app.js` 却漏跑读它的测试,`test_test_planning.py`
# 的域映射门槛会在本地就红。
- "web": ("test_frontend_build.py", "test_web_ui.py", "test_web_js.py", "test_legacy_shell_routes.py",
+ "web": ("test_frontend_build.py", "test_web_ui.py", "test_web_js.py", "test_web_e2e.py",
+ "test_legacy_shell_routes.py",
"test_web_perf.py", "test_copy_final_state.py",
"test_agency_entity.py", "test_dependency_policy.py", "test_desktop_settings.py",
"test_fastapi_api.py", "test_follow_assets.py", "test_follow_web.py",
diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.py
new file mode 100644
index 000000000..7ebd53d0d
--- /dev/null
+++ b/tests/test_web_e2e.py
@@ -0,0 +1,194 @@
+# -*- coding: utf-8 -*-
+"""真浏览器冒烟:临时数据根上的合成演示库,交给 `frontend/e2e` 的 playwright-core 用例。
+
+页面源断言守不住布局之后才成立的事实(横向溢出、等待态卡住、控制台报错、失败请求),
+靠手动开浏览器逐轮重测的话,既费时又不稳定。这里把它们固定成确定性的用例:Python 这一侧准备
+数据与服务,Node 那一侧只认 `PEACH_E2E_ORIGIN`。
+
+数据全在临时目录:`scripts/demo_dataset.py` 生成 SFW 合成库,账本来自迁移模板,
+设置文件把 `local` 的声明根直接写成演示库目录。Windows 上 `[media.mounts]` 不参与
+路径翻译,声明根若沿用内建默认,process 读到的就是这台机器的真实媒体目录。
+
+短片由 ffmpeg 编码成真能解码的 2 秒片段:详情页的播放器会预加载源,占位字节只会让
+`/stream` 返回 503。缺 npm、`playwright-core`、ffmpeg 或本机 Chrome 时显式跳过,与 vitest
+同一口径;浏览器不另外下载,`PEACH_E2E_CHROME` 可以指定可执行文件。
+"""
+from __future__ import annotations
+
+import importlib.util
+import os
+import shutil
+import socket
+import sqlite3
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+import urllib.error
+import urllib.request
+from contextlib import closing
+from pathlib import Path
+
+from peach import settings_file
+from peach.config import FFMPEG_DIR
+from peach.ffmpeg import FFmpegResolver
+from peach.library_processing import process_library
+from support.conditions import windows_ledger_roots
+from support.ledger import fresh_ledger
+
+ROOT = Path(__file__).resolve().parents[1]
+FRONTEND = ROOT / "frontend"
+SERVER_START_SECONDS = 60
+E2E_SECONDS = 600
+
+
+def chrome_executable() -> str | None:
+ """本机 Chrome 的可执行文件;找不到返回 None。"""
+ explicit = os.environ.get("PEACH_E2E_CHROME", "").strip()
+ if explicit:
+ return explicit if Path(explicit).is_file() else None
+ candidates: list[Path] = []
+ if os.name == "nt":
+ for variable in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"):
+ base = os.environ.get(variable)
+ if base:
+ candidates.append(Path(base) / "Google" / "Chrome" / "Application" / "chrome.exe")
+ elif sys.platform == "darwin":
+ candidates.append(Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"))
+ else:
+ for name in ("google-chrome", "google-chrome-stable"):
+ found = shutil.which(name)
+ if found:
+ candidates.append(Path(found))
+ return next((str(path) for path in candidates if path.is_file()), None)
+
+
+def load_demo_script():
+ path = ROOT / "scripts" / "demo_dataset.py"
+ spec = importlib.util.spec_from_file_location("peach_script_demo_dataset_e2e", path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def free_port() -> int:
+ with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as probe:
+ probe.bind(("127.0.0.1", 0))
+ return probe.getsockname()[1]
+
+
+def refuse_network(*args, **kwargs):
+ raise AssertionError("演示库的 process 不应向任何外部来源发请求")
+
+
+@windows_ledger_roots
+class WebE2ESmokeTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ npm = shutil.which("npm")
+ if npm is None:
+ raise unittest.SkipTest("跳过 e2e:本机没有 npm。装 Node 24+ 后 `-Scope web` 会带上它")
+ if not (FRONTEND / "node_modules" / "playwright-core").is_dir():
+ raise unittest.SkipTest("跳过 e2e:frontend/node_modules 还没装,先 `npm --prefix frontend ci`")
+ ffmpeg = FFmpegResolver(FFMPEG_DIR).ffmpeg()
+ if ffmpeg is None:
+ raise unittest.SkipTest("跳过 e2e:没找到 ffmpeg,演示库的短片编码不出来")
+ chrome = chrome_executable()
+ if chrome is None:
+ raise unittest.SkipTest("跳过 e2e:没找到 Chrome;装 Google Chrome 或用 PEACH_E2E_CHROME 指定")
+ cls.npm, cls.ffmpeg, cls.chrome = npm, str(ffmpeg.path), chrome
+ cls.root = Path(tempfile.mkdtemp(prefix="peach-e2e-")).resolve()
+ cls.server = None
+ try:
+ cls._build_library()
+ cls._start_server()
+ except BaseException:
+ cls.tearDownClass()
+ raise
+
+ @classmethod
+ def tearDownClass(cls):
+ server = getattr(cls, "server", None)
+ if server is not None and server.poll() is None:
+ server.terminate()
+ try:
+ server.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ server.kill()
+ server.wait(timeout=10)
+ if getattr(cls, "log", None) is not None:
+ cls.log.close()
+ shutil.rmtree(cls.root, ignore_errors=True)
+
+ @classmethod
+ def _build_library(cls):
+ media = cls.root / "media"
+ load_demo_script().generate(media, count=12, seed=7, video="ffmpeg", duration=2,
+ ffmpeg=cls.ffmpeg)
+ data = cls.root / "peach-data"
+ (data / "database").mkdir(parents=True)
+ cls.db = fresh_ledger(data / "database")
+ cls.port = free_port()
+ config = settings_file.PeachConfig(
+ data, data / settings_file.SETTINGS_FILENAME, present=True, data_root_found=True,
+ locations={"local": (str(media),)},
+ server=settings_file.ServerSettings(port=cls.port),
+ )
+ settings_file.write(config)
+ generated = config.directory("generated")
+ result = process_library(config, cls.db, generated, generated / "covers",
+ provider_factory=refuse_network)
+ if result["status"] != "complete":
+ raise AssertionError(f"演示库 process 没有完成:{result}")
+ with closing(sqlite3.connect(cls.db)) as connection:
+ row = connection.execute(
+ "SELECT id FROM asset WHERE medium='video' ORDER BY id LIMIT 1").fetchone()
+ if row is None:
+ raise AssertionError("演示库 process 之后账本里没有视频")
+ cls.data, cls.item = data, row[0]
+
+ @classmethod
+ def _start_server(cls):
+ env = dict(os.environ, PEACH_DATA_ROOT=str(cls.data), PYTHONIOENCODING="utf-8")
+ cls.log = (cls.root / "serve.log").open("w", encoding="utf-8")
+ cls.server = subprocess.Popen(
+ [sys.executable, "-X", "utf8", "-m", "peach", "serve", "--host", "127.0.0.1",
+ "--port", str(cls.port), "--db", str(cls.db),
+ "--no-auth", "--no-mdns", "--no-ledger-sync"],
+ cwd=str(ROOT), env=env, stdout=cls.log, stderr=subprocess.STDOUT)
+ cls.origin = f"http://127.0.0.1:{cls.port}"
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ deadline = time.monotonic() + SERVER_START_SECONDS
+ while time.monotonic() < deadline:
+ if cls.server.poll() is not None:
+ raise AssertionError(f"服务提前退出:{cls._server_log()}")
+ try:
+ with opener.open(f"{cls.origin}/healthz", timeout=2) as response:
+ if response.status == 200:
+ return
+ except (urllib.error.URLError, OSError):
+ time.sleep(0.5)
+ raise AssertionError(f"{SERVER_START_SECONDS} 秒内 /healthz 没有就绪:{cls._server_log()}")
+
+ @classmethod
+ def _server_log(cls) -> str:
+ cls.log.flush()
+ return (cls.root / "serve.log").read_text(encoding="utf-8", errors="replace")[-4000:]
+
+ def test_every_route_holds_the_layout_and_runtime_invariants(self):
+ env = dict(os.environ, PEACH_E2E_ORIGIN=self.origin, PEACH_E2E_ITEM=str(self.item),
+ PEACH_E2E_CHROME=self.chrome)
+ completed = subprocess.run(
+ [self.npm, "--prefix", str(FRONTEND), "run", "e2e", "--silent"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
+ cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)
+ output = f"{completed.stdout}\n{completed.stderr}"
+ self.assertEqual(completed.returncode, 0, f"{output}\n--- serve.log ---\n{self._server_log()}")
+ self.assertRegex(output, r"# pass [1-9]\d*", output)
+ self.assertRegex(output, r"# fail 0\b", output)
+
+
+if __name__ == "__main__":
+ unittest.main()