This article is a complete tutorial for the matery theme’s automated testing system, paired with the other 4 feature test articles (Content Tags / Interaction & Visual / Layout & Pages / Markdown Syntax) — those 4 are the “test arena”, this one is the “test engine”.
Authoritative sources:tools/tests/release-test.sh(137 lines of pure orchestration) +tools/tests/layers/manifest(the single authoritative 13-layer list),docs/superpowers/specs/2026-08-06-layout-test-cases.md.How to read: every command shows its Output (what a real terminal looks like) first, then the Corresponding command (the one line that produced it). See an output you want to reproduce — copy the command right below it; want parameters — jump straight to the “Full parameters” table.
When to Read This Article?
| You are… | Read this section | What you get |
|---|---|---|
| User (wondering if a feature works) | Appendix “Test ↔ Feature Map” | Find the test file by feature name, confirm “this feature has automated verification” |
| Contributor (adding/modifying a test) | §12 “How to Add a Test Case” | Complete zero-to-gate steps with code templates |
| Maintainer (running the gate before release) | §2 “release-test.sh Usage” | Commands for local iteration / release gate / visual assertions |
| Debugging (gate shows red) | §5 “External Dependency Retry” + §6 “Third-Party Interception” + ⚠️ Known Pitfalls | Distinguish “environment noise” from “real bug” |
1. Testing Pyramid Overview
Purpose: see at a glance what each of the 13 gate layers verifies and what it depends on, so you know which tier to run.
Learning path: read the layer list → see three typical outputs → check the layer table → remember the execution-order pitfall
1.1 Minimal usage
Output (verbatim from manifest — these are all 13 layers of the pyramid, line order = execution order):
# 门禁层清单 —— 唯一权威(行序 = 执行顺序)
# 格式:ID<TAB>脚本文件<TAB>入口函数<TAB>描述
# 消费者:tools/tests/release-test.sh(source + 调用)、tools/tests/gen-tc-index.js(层清单)
L10 L10_smoke.sh run_L10 发版前 SW 冒烟(远程测试域;--local 跳过)
L01 L01_build.sh run_L01 构建验证
L02 L02_urls.sh run_L02 URL 与链接完整性
L03_05 L03_05_static.sh run_L03_05 静态资源与页面渲染(L3-L6)
L07 L07_core.sh run_L07 核心功能
L08 L08_enhanced.sh run_L08 增强功能
L09 L09_sw.sh run_L09 Service Worker
L11 L11_integration.sh run_L11 Playwright 集成
L12 L12_local.sh run_L12 本地化资源 + 多语言一致性
L2i L2i_seo.sh run_L2i SEO 结构化数据
L13 L13_units.sh run_L13 全量单测门禁
L13a L13a_cov.sh run_L13a 覆盖率阈值
L14 L14_visual.sh run_L14 视觉断言Corresponding command:
cat tools/tests/layers/manifestStacked by “dependency cost”, the table becomes the pyramid shape:
┌──────────────┐
│ L2 Prod URL │ After release: 20 pages HTTP 200 + feature markers (curl)
│ L9/L10 SW │ Before release: Vercel test domain SW smoke (playwright)
├──────────────┤
│ L11 Playwright Integration │ Real browser: effects/wordcloud/lazyload/read mode, 18 items
├──────────────┤
│ L14 Visual Assertions │ visual-assert precise values: 12 suites (production-blocking, skipped locally by default)
├──────────────┤
│ L13/L13a Units │ node direct: 15 .test.js + search integration + 4 shell unit tests + tutorial-structure gate; L13a then scans unit/** coverage
├──────────────┤
│ L1 Build Verify │ hexo g Success + artifact complete (index.html > 1000B)
└──────────────┘1.2 Common options
① The top layer (build) output, live
Output:
🔨 L1: 构建验证
✅ 构建成功 (hexo g Success)
✅ public/index.html 存在 (123456 字节)Corresponding command:
tools/tests/release-test.sh # L1 由其内部调用 cicd.sh -d 产出② The middle layer (unit tests) output, live — one ✅ per file
Output:
🧪 L13: 全量单元/集成测试门禁(node tools/tests/*.test.js)
✅ 单测 unit-toc.test.js
✅ 单测 unit-search.test.js
✅ 单测 unit-css-architecture.test.sh(CSS 架构)Corresponding command:
node tools/tests/unit/unit-toc.test.js # 单跑其中一个,看它自己的输出③ The browser layer (L11) output, live — the output carries the extracted PASS count
Output:
✅ 词云/去jQuery/防闪烁集成测试(PASS=8)
✅ 内容宽度统一测试(PASS=5)Corresponding command:
node tools/tests/wordcloud.test.js④ The bottom layer (visual assertions) output, live — summarized per suite
Output:
🎯 L14: 视觉断言(visual-assert)
✅ L14 layout-checks:18 项全部通过
✅ L14 dark-mode:4 项全部通过
⏱️ L14 总计:12 文件通过, 0 文件失败(299s)Corresponding command:
node tools/visual-assert.js run --local tools/visual-assert/dark-mode.json1.3 Full parameters
| Layer | Name | How It Runs | Dependencies |
|---|---|---|---|
| L1 | Build verification | hexo generate + artifact check | none |
| L13 | Full unit test gate | node tools/tests/*.test.js + shell unit tests | no chromium |
| L11 | Playwright integration | real browser + local server | chromium + server |
| L2/L2b/L2x/L2y/L2i | Production URL assertions | curl + grep | production/local server |
| L3-L8 | Feature marker checks | curl + static assertions | production/local server |
| L9 | Static assets + SW smoke | curl + playwright | production domain |
| L13a | Coverage statistics | node --experimental-test-coverage scans unit/** | none |
| L14 | Visual assertions | node tools/visual-assert.js run (12 suites) | chromium + server |
| L10 | SW smoke (test domain) | playwright | Vercel test domain blog2.17lai.site |
1.4 Boundaries & pitfalls
- Execution order is not documentation order:
manifestline order = execution order, and L10 runs first (before L1). Old docs often put L1 on the first line — that is a documentation habit, not the execution fact. - A layer script cannot be executed directly:
layers/*.shonly definesrun_LXX()and depends onrelease-test.shhavingsource lib/assert.shfirst (pass/failare global counters). To verify one layer alone, run the test file it wraps, notbash layers/L13_units.sh. - A missing layer script is a hard failure: if
manifestnames a file thatlayers/does not contain →❌ 层脚本缺失:xxx.shexits 1 immediately, never silently skipped. - L13 and L13a overlap: L13 runs “by name” (clear names on failure), L13a “globs
unit/**and enforces coverage thresholds”; the same file may run twice — a deliberate double safety net.
1.5 Summary
The layer list lives in exactly one file: tools/tests/layers/manifest. To know “which layers exist and in what order they run”, always read it — not the docs, not a chat log.
2. release-test.sh Usage
Purpose: run the full gate before/after a release; locally, run only the part that can run.
Learning path: run it once to see the skeleton → pick flags by scenario → check the flag table → remember the base-address and concurrency limits
2.1 Minimal usage
Output (the skeleton of one full gate — fixed head and tail, layers unrolled in between):
=============================================
发版全量自动化测试 (target: https://blog.17lai.site)
=============================================
🔍 [preflight] 环境预检...
✅ 构建产物有效 (123456 字节)
✅ playwright 可用(NODE_PATH=/home/andy/.local/share/mise/installs/npm-playwright/1.56.0/lib/node_modules)
✅ _config.yml 未被污染
✅ 网络基址可达(HTTP 200)
✅ [preflight] 环境就绪
🔒 [preflight] 已获取门禁锁(PID 12345)
🌐 L10: 发版前 SW 冒烟(Vercel 测试域 blog2.17lai.site)
...
测试结果: PASS=<N> FAIL=0
=============================================
🎉 全部通过!Corresponding command:
tools/tests/release-test.sh2.2 Common options
① --local (the most common for local iteration)
Output (the summary section states explicitly what was skipped):
⏭️ 已跳过 L10(远程 SW 冒烟)与 L11(playwright 集成)—— 本地迭代模式;
发版门禁(不带 --local)会跑全量,L11 覆盖内容宽度/灯箱/懒加载/阅读模式等
测试结果: PASS=<N> FAIL=0
🎉 全部通过!Corresponding command:
tools/tests/release-test.sh --local② --skip-build (public/ is ready, just re-run the assertions)
Output (both L1 lines become “skipped”; docker is no longer invoked):
🔨 L1: 构建验证
✅ 跳过构建(--skip-build)
✅ 跳过产物验证(--skip-build)Corresponding command:
tools/tests/release-test.sh --skip-build③ --skip-l10 (skip only the remote SW smoke, keep L11 browser integration)
Output:
🌐 L10: 发版前 SW 冒烟(Vercel 测试域 blog2.17lai.site)
⏭️ 跳过 L10(--local/--skip-l10:本地迭代不验证远程 SW)Corresponding command:
tools/tests/release-test.sh --skip-l10④ --prepare (bring the environment up in one shot when it is not ready)
Output:
🔧 [preflight] 自动就绪环境...
✅ 容器已在运行
✅ 产物有效 (123456 字节),跳过重建
🔍 [preflight] 复检环境...
✅ [preflight] 环境就绪Corresponding command:
tools/tests/release-test.sh --prepare⑤ RUN_L14=1 (also run visual assertions locally)
Output (originally “skip”, now really runs):
🎯 L14: 视觉断言(visual-assert)
✅ L14 layout-checks:18 项全部通过
⏱️ L14 总计:12 文件通过, 0 文件失败(299s)Corresponding command:
RUN_L14=1 tools/tests/release-test.sh --local⑥ SKIP_L14=1 (force skip, takes precedence over RUN_L14)
Output:
🎯 L14: 视觉断言(visual-assert)
⏭️ L14 视觉断言(SKIP_L14=1 → 强制跳过)Corresponding command:
SKIP_L14=1 RUN_L14=1 tools/tests/release-test.sh2.3 Full parameters
| Flag | Effect |
|---|---|
--skip-build | Skips L1 build + artifact verification (use when already built) |
--local | Target switches to adaptive local base (port detection, see base address section below), skips L10 (remote SW smoke 5min+) and L11 (playwright serial >800s) |
--skip-l10 | Skips only L10, keeps L11 playwright integration |
--prepare | Auto-prepares environment: starts container if not running, rebuilds if artifacts invalid, rechecks at the end |
RUN_L14=1 | Enables L14 visual assertions in local mode (skipped locally by default) |
SKIP_L14=1 | Forces L14 skip (even if RUN_L14=1 is set) |
Base address: production is fixed at https://blog.17lai.site (port 443, never a port number); local uses LOCAL_BASE with adaptive port detection — probe order: BLOG_PORT env var → TEST_BASE env var → root _config.yml server.port (docker 4000) → 4100, take the first HTTP 200; on success exports TEST_BASE/TEST_URL, and all 36 test files follow automatically.
Execution order (
manifestline order):L10 → L01 → L02 → L03_05 → L07 → L08 → L09 → L11 → L12 → L2i → L13 → L13a → L14 → TC index check → summary. Note L10 runs first (before L01) — old docs often get this backwards.
Release rule: after
tools/cicd.sh -rpublishes, you MUST runtools/tests/release-test.shto verify the production environment.
2.4 Boundaries & pitfalls
① Concurrency is rejected outright
Output:
❌ [preflight] 门禁已在运行(PID 12345),拒绝并发启动
锁文件:/tmp/opencode/gate.lock
💡 如确认无其他门禁在跑,可手动删除:rm /tmp/opencode/gate.lockCorresponding command:
tools/tests/release-test.sh --local # 另开一个终端重复执行即可复现Concurrency kills each other’s local server — this is a hard rejection, not a warning. A stale lock (holder process already dead) is taken over automatically and prints
⚠️ [preflight] 陈旧锁(PID xxxx 已死),自动接管.
② Fails within seconds when the environment is not ready, and prints fix commands
Output:
❌ 本地服务器不可达(已尝试端口: 4000 4100)
💡 修复命令(任选其一):
1. docker 生成: docker compose -f docker-compose.test.yml exec -T hexo bash -c 'tools/cicd.sh -d'
2. 本机预览: tools/test.sh server
3. 恢复服务: docker compose -f docker-compose.test.yml exec -T hexo bash -c 'pm2 restart all'Corresponding command:
tools/tests/release-test.sh --local③ The shape of a failure summary
Output:
测试结果: PASS=<N> FAIL=2
=============================================
❌ 存在失败项,请检查!Corresponding command:
tools/tests/release-test.sh # exit code 1- With only
--localand noRUN_L14, L14 always skips — do not misread “did not run” as “passed”. --localturns off both L10 and L11, not just L10; to turn off only L10 use--skip-l10.
2.5 Summary
Three high-frequency combos: local iteration --local, re-run assertions --skip-build, release no flags (must be fully green before the release counts as done).
3. L1-L14 Layer Coverage
Purpose: know what each layer “asserts”, so a red mark immediately locates the broken feature.
Learning path: see four layers’ typical outputs → check the coverage table → read the L11 list → remember unhooked/duplicated items
3.1 Minimal usage
Output (L1 is the smallest layer — only two assertions):
🔨 L1: 构建验证
✅ 构建成功 (hexo g Success)
✅ public/index.html 存在 (123456 字节)Corresponding command:
tools/tests/release-test.sh # 不带 --skip-build 即跑 L13.2 Common options
① L2: URL reachability — one line per path
Output:
✅ /archives/ → 200
✅ /categories/ → 200
✅ /tags/ → 200Corresponding command:
curl -s -o /dev/null -w '%{http_code}\n' https://blog.17lai.site/archives/② L7: core features — feature name + measured value
Output:
✅ 搜索入口
✅ TOC 折叠配置(<实际配置值>,0=全部折叠)
✅ 暗色模式 CSS
✅ infinite-scroll 状态元素 + data-loading 文案 (<i18n 文案>)Corresponding command:
curl -s https://blog.17lai.site/ | grep -o 'id="searchInput"' | head -1③ L13: unit test gate — one line per file
Output:
✅ 单测 unit-wiki-helper.test.js
✅ 单测 search-integration.test.js(PASS=<N> FAIL=0)
✅ 教程文章结构门禁 check-tutorial-articles.jsCorresponding command:
node tools/tests/unit/unit-wiki-helper.test.js④ L14: visual assertions — summarized per suite
Output:
✅ L14 homepage:<N> 项全部通过
⚠️ L14 nav-scrolled 第 1 次未通过(疑似负载抖动),重试一次…
✅ L14 nav-scrolled:<N> 项全部通过
⏱️ L14 总计:12 文件通过, 0 文件失败(312s)Corresponding command:
node tools/visual-assert.js run --local tools/visual-assert/nav-scrolled.json3.3 Full parameters
| Layer | Coverage | Assertion Example |
|---|---|---|
| L1 | Build verification | hexo g Success + public/index.html > 1000B |
| L2 | 20 layout page URLs reachable | /posts/fc764afd/, /archives/, /categories/, /tags/, /about/, /friends/, /galleries/, /bb/, /musics/, /movies/, /msg/ + 4 test articles → HTTP 200 |
| L2b | Multilingual verification | en article real translation / fallback notice banner / comment path normalization / default language no prefix |
| L2x | Unified language fallback | MATERY_LANG injection / fallback pages / standalone page multilingual (incl. gallery sub-pages) / aggregation page multilingual |
| L2y | Encrypt/decrypt refresh | wiki sidebar leaks no metadata/section keys (structure/i18n/encrypt_) / encrypted container complete (hbeForm + storage-key) |
| L2i | SEO structured data | og:image / JSON-LD / fetchpriority |
| L3 | Comment section check | msg/friends/bb pages contain #comments |
| L4 | href=/ style errors | page href=/ references should be 0 |
| L5 | Version consistency | config vs sw.tmp.js consistent in 3 places |
| L6 | Key resource check | 404 page / key JS versions |
| L7 | Core feature coverage | gallery lightbox / encrypted gallery / search / JS module merge / TOC collapse / dark mode / comments / infinite-scroll / wiki code blocks / wiki component styles (main has post-container / .wiki-content word-wrap / admonition .note rule precisely scoped) |
| L8 | Enhanced feature coverage | tag plugin rendering (note/timeline/tabs/label/githubCard/mermaid) / encrypted posts / Feed / static assets / analytics |
| L9 | Static assets + SW smoke | main.css > 50KB / utils.js > 5KB / production domain 7 pages no SW errors |
| L10 | SW smoke (test domain) | blog2.17lai.site 7 pages no SW errors + interaction verification (search/reward/lightbox/TOC/dark mode) |
| L11 | Playwright integration (18 items) | see table below |
| L12 | Localized asset check | mermaid / aplayer assets exist |
| L13 | Full unit test gate | 15 *.test.js + search integration + 4 *.test.sh + 1 tutorial-structure gate (see §4) |
| L13a | Coverage statistics | unit/**/*.test.js coverage scan (line ≥85 / branch ≥77 / funcs ≥70) |
| L14 | Visual assertions (12 suites) | see §9 |
Comment library version baseline (upgraded 2026-09-24, config in the
userConfig/_config.tmp.ymllibs section): walinev=3.15.2(enabled) / twikoov=2.0.8(disabled) / valinev=1.5.3+ avv=5.19.2(disabled) / gitalkv=1.8.0(deprecated); skillmatery-libs/references/{waline,twikoo,valine,gitalk}.mdrecords the versions and upgrade history in sync.
L11 Playwright Integration List (real browser)
| Test File | Coverage |
|---|---|
effects-integration.test.js | Page effects (sakura/snowflake/fireworks loading) |
videobg-integration.test.js | Video background (threshold/light-dark pool/webm contract/disabled state) |
wordcloud.test.js | Word cloud / no jQuery / TOC anti-flicker / dark-light switching |
i18n.test.js | Multilingual completion (MATERY_I18N injection + button copy + en translations) |
musics-integration.test.js | Online music APlayer (multi-domain failover) |
lazyload-integration.test.js | Lazyload handleCard three-way dispatch (51 assertions) |
floating-panel-integration.test.js | Floating panel (toggle/font scaling/persistence) |
content-width.test.js | Content width unification (4K/FHD/2K/single-column cap) |
readmode-integration.test.js | Read mode / code fullscreen / scroll-down-bar |
wiki-styles.test.js | Wiki tag component styles (note / ::: container colors + centering + width consistency) |
code-widget.test.js | codeWidget delegation idempotency (second invocation still works with single click) |
core-events-integration.test.js | Event bus / progress bar linkage |
wiki-prism-integration.test.js | Wiki code blocks prism + line-numbers |
misc-interactions.test.js | Reward popup / trad-simp conversion (G14/G15) |
lang-client-strategy.test.js | Client language strategy (site-wide follow/crawler skip/panel echo, 7 assertions) |
rich-content-integration.test.js | Rich content rendering (math MathJax+KaTeX/mermaid/markmap/typewriter/share/Live2D, 11 assertions) |
wiki-integration.test.js | Multilingual wiki reachability / sidebar sections / language switcher (18 assertions) |
infinite-scroll-integration.test.js | Infinite Scroll (Home/Archive real pagination + tag-page single-page grid) |
lightbox.test.js | Lightbox (gallery/image zoom interaction) |
gallery-hover.test.js | Gallery/card hover animation (guards the classList multi-class fix) |
3.4 Boundaries & pitfalls
- L11 always skips locally:
--localskips the whole block (⏭️ 跳过 L11 playwright 集成(--local:…)), so “all green locally” does not mean “the browser layer is not broken”. - L11 pass criteria are not uniform: some files look for
PASS=N FAIL=0, some for0 失败, andlazyloadhas no summary line at all (its criterion is “no FAIL/失败/❌”). New files must match the existing criterion, otherwise they go green falsely. - L14 retries once automatically on failure:
⚠️ L14 xxx 第 1 次未通过(疑似负载抖动),重试一次…; a retried pass is recorded in the flaky list (see §11) and does not change the PASS/FAIL counts. - Unhooked files are now zero:
wiki-integration.test.jsandinfinite-scroll-integration.test.jsexisted early on but were hooked into no layer; they are now wired in (2026-09-27 / L11 section) with assertions. The only remaining unhooked file istools/tests/unit-fontawesome.test.py(L13a’s glob only takes.test.js), run it manually withpython3 tools/tests/unit-fontawesome.test.py.
3.5 Summary
Layer count is not coverage: L1/L13 answer “does it run”, L2/L7/L8 answer “is it in the artifacts”, L11/L14 answer “is it right in the browser”. Miss one of the three and the fault leaks through the gap.
4. Unit Test List (tools/tests/)
Purpose: look up “which file tests what”, and why some files run twice.
Learning path: run one file to see the output format → recognize the three summary-line shapes → check the file list → remember the mock pitfall
4.1 Minimal usage
Output (a single test file introduces itself; the last line is always a summary the gate can match):
✅ TOC 折叠配置解析(collapseDepth=0 视为全部折叠)
✅ collapseDepth=6 视为全部展开
✅ 未配置时取默认值
结果: PASS=3 FAIL=0Corresponding command:
node tools/tests/unit/unit-toc.test.js4.2 Common options
① The three summary-line formats (the gate regex-matches them; the format must not change)
Output:
结果: PASS=3 FAIL=0结果: 5 通过, 0 失败unit-i18n-core: 10 pass / 0 failCorresponding command:
grep -n 'console.log' tools/tests/unit/unit-toc.test.js | tail -2② The shell unit test summary line is the shortest
Output:
结果: PASSCorresponding command:
bash tools/tests/unit/unit-version.test.sh③ L13a coverage scan (carries thresholds; exits 1 when below)
Output:
ℹ all files | 86.66 | 78.98 | 72.73 |Inside the gate it is turned into:
✅ node:test 单元测试 + 覆盖率达标(86.66/78.98/72.73)Corresponding command:
node --test --experimental-test-coverage \
--test-coverage-lines=85 --test-coverage-branches=77 --test-coverage-functions=70 \
"tools/tests/unit/**/*.test.js"4.3 Full parameters
L13 gate direct-run list (L13_units.sh names each file, so failures are clearly named):
# node 单测(纯单测/静态,无浏览器依赖)
unit-toc.test.js # TOC 折叠配置(collapseDepth 0||6 falsy 陷阱)
unit-search.test.js # 搜索三引擎
unit-multilang.test.js # 多语言配置
unit-encrypt2.test.js # 加密扩展(片段 + wiki)
unit-wiki-helper.test.js # wiki helper(语言解析/侧栏渲染/canonical 回落,10 用例)
helpers.test.js # 字数统计三 helper(wordcount/min2read/totalcount;加密 origin/wiki 去重/回落/缓存重置,52 断言)
utils.test.js # 通用工具函数
lang-fallback.test.js # 回落链 4 级(13 断言)
echarts-charts.test.js # ECharts 图表
banner-bg.test.js # banner 与背景偏好联动
homepage.test.js # 首页结构
imgsize-unit.test.js # 图片尺寸注入脚本(normalizeImgUrl 协议相对 URL 补全 + 本地/网络图片尺寸读取)
infinite-scroll-aos.test.js # 无限滚动 + AOS 联动
unit-standalone.test.js # 独立页排除法判定 + 语言前缀豁免(22 断言)
unit-i18n-helper.test.js # t() helper(fallback_lang + 大小写容错,5 用例)
# 带外部依赖的集成(retry_match 包装,判据 PASS=N FAIL=0)
search-integration.test.js # 搜索集成(Algolia 分页需真实 API)
# shell 单测
unit-css-architecture.test.sh # CSS 架构(编译产物关键选择器)
unit-version.test.sh # 版本递增进位(防 12.99→12.100)
unit-retry.test.sh # 退避重试库
unit-deploy-target.test.sh # 部署目标切换(hexo/hexoback 双激活校验)L13a glob coverage (unit/**/*.test.js, includes some of the files above):
unit-i18n-core.test.js # i18n 核心回落语义(resolveI18n 四级链 + cfg 防御,10 用例)
unit-sidebar-i18n.test.js # 侧栏 i18n 查表 + 回退链(当前→fallback→default→key,5 用例)
unit-sidebar-keys.test.js # 门禁校验器 sidebar-keys.js 行为(4 wiki × 9 语言覆盖,4 用例)
unit-encrypt.test.js # 自研加密体系(AES-GCM + PBKDF2 闭环,9 用例)
unit-markmap-prune.test.js # markmap 无脑图页面资源拆除(6 用例)
unit-updated.test.js # 「更新于」取 git 最后提交时间(4 用例)Not hooked into any layer (run manually):
unit-fontawesome.test.py # FontAwesome 精简脚本(L13a 通配只收 .test.js,不含 .py)4.4 Boundaries & pitfalls
Mocks must model real Hexo objects (Query, not plain arrays)
site.posts/site.pagesare Hexo Query objects (array-like),.filter()returns another Query, not an array, and they cannot befor...of-iterated — call.toArray()first to get a real array.helpers.test.js(word count) first mocked them as plain arrays: unit tests were fully green, yet the real build threwwikiPages is not iterable→ every HTML output was 0 bytes. The mock only exercised the real path aftertoArray()was added.
The output format cannot be changed casually
Output (what really happens when the gate cannot match the summary line):
⏳ 搜索集成 无输出(疑似超时),退避 1s 重试...
❌ 搜索集成 业务断言失败(真 bug)Corresponding command:
tools/tests/release-test.sh --local # 改动末尾 console.log 后复跑即可复现Lesson: the closer a mock is to the real object, the better unit tests catch build-level failures; the more stable the summary line, the more reliably the gate recognizes “passed”.
4.5 Summary
A test file has exactly one contract: print a regex-matchable summary line at the end + exit non-zero on failure. Everything else in the output is free-form; these two are not.
5. External Dependency Retry & Degradation (lib/retry.sh)
Purpose: separate “external service jitter” from “our own bug” — the former must not block a release.
Learning path: see one retry output → see the two outcomes (degrade / fail) → check the classification table → know when not to wrap
5.1 Minimal usage
Output (passes on the first try — the ideal case, a single line):
✅ L2 搜索 通过Corresponding command:
source tools/tests/lib/retry.sh
retry_run "L2 搜索" "node tools/tests/search-integration.test.js"5.2 Common options
① retry_run: judged by exit code (3 backoff attempts 1s/4s/9s + jitter)
Output (jitter scenario — passes after retry and is recorded as flaky):
⏳ L2 搜索 第 1 次失败,退避 1s 重试...
⚠️ L2 搜索 第 2 次通过(前 1 次 flaky,需关注)Corresponding command:
retry_run "L2 搜索" "node tools/tests/search-integration.test.js"② retry_match: judged by output pattern (main use in the L11 section)
Output (counts as passed only when PASS=.*FAIL=0 matches):
⏳ L2d 视频 第 1 次未通过,退避 1s 重试...
✅ L2d 视频 通过Corresponding command:
retry_match "L2d 视频" "timeout 180 node tools/tests/videobg-integration.test.js" "0 失败|fail 0|失败, 0"③ All attempts failed → external unavailable (degrade to warn, return 0)
Output:
⚠️ L2d 视频 外部依赖不可用(降级 warn,非产品缺陷)
📄 日志: /tmp/opencode/test-L2d_视频.logCorresponding command:
retry_match "L2d 视频" "timeout 180 node tools/tests/videobg-integration.test.js" "0 失败"④ All attempts failed → business assertion failure (real bug, return 1)
Output:
❌ L2d 视频 业务断言失败(真 bug)
📄 日志: /tmp/opencode/test-L2d_视频.logCorresponding command:
retry_match "L2d 视频" "timeout 180 node tools/tests/videobg-integration.test.js" "0 失败"5.3 Full parameters
Failure classification (when all attempts fail, distinguish by log signature):
| Signature | Verdict | Result |
|---|---|---|
ERR_NAME_NOT_RESOLVED / ECONNREFUSED / ETIMEDOUT / 429 / 50x etc. | external unavailable | ⚠️ degraded warn (returns 0, does not block release) |
| no external signature | business assertion failure | ❌ fail (returns 1, real bug) |
5.4 Boundaries & pitfalls
- Retry count/backoff are fixed: 3 attempts, 1s/4s/9s + jitter. Do not raise them “to make it green” —
unit-retry.test.shasserts the backoff library’s behaviour. - Do not wrap pure static assertions in
retry_match: a local file that cannot be read is not network jitter; retrying only stretches a real bug into 3× the runtime. - A
retry_matchpattern must anchor on zero failures: matching onlyPASS=turns “4/24 passed” into green (the criterion was tightened on 2026-10-07 because of exactly this). - Logs land in
/tmp/opencode/: when something goes red, read the file named on the📄 日志:line — faster than scrolling the terminal.
5.5 Summary
retry_run watches the exit code, retry_match watches the output; both classify only on “all attempts failed” — an intermediate success is flaky: not a failure, but never invisible.
6. Third-Party Interception + ERR_ABORTED Exclusion (lib/browser-env.js)
Purpose: make playwright tests responsible only for “the page’s own errors” — third-party CDN noise is not billed to us.
Learning path: see one assertion output → see the two APIs → check the mechanism table → remember the abort pitfall
6.1 Minimal usage
Output (with the shared environment, a test only asserts two arrays are empty):
✅ 页面无 JS 异常
✅ 无同源资源失败Corresponding command:
node tools/tests/content-width.test.js # 任一 playwright 测试的断言现场6.2 Common options
① interceptThirdParty(page): intercept known pollution sources
Output (without interception, the page’s own unhandled rejection leaks into JS errors):
❌ JS errors [ 'Failed to parse JSON from webpushr' ]Corresponding command:
node tools/tests/effects-integration.test.js② collectPageErrors(page, BASE): collect only JS exceptions + same-origin resource failures
Output (third-party image-host 404s are not counted; same-origin 404s are):
jsErrors: []
sameOriginFailures: []Corresponding command:
NODE_PATH=$(npm root) node tools/tests/lightbox.test.js6.3 Full parameters
| Mechanism | Description |
|---|---|
interceptThirdParty | Intercepts known pollution sources (e.g. webpushr returning non-JSON → page unhandled rejection), returns valid JSON instead of aborting (abort produces net::ERR_FAILED, becoming new noise) |
collectPageErrors | Collects only JS exceptions + same-origin (localhost/production domain) resource failures; third-party CDN/image-host failures are environment noise and not counted |
ERR_ABORTED exclusion | Navigation interruption (multiple goto/leaving the page cancels in-flight requests) is not a resource error, skipped directly |
6.4 Boundaries & pitfalls
- Do not intercept third parties with
route.abort(): abort turns the request intonet::ERR_FAILED, adding a same-origin failure — use fulfill to return valid JSON instead. - Do not hard-code the baseline domain to production: the second argument of
collectPageErrorsis the currentBASE; running locally while passing the production domain makes local resource failures look like third-party ones and silently disappear. - Tests with multiple
gotocalls must tolerateERR_ABORTED: otherwise pagination tests go stably false-red.
6.5 Summary
One sentence: same-origin is billed, third-party is not; abort creates noise, fulfill removes it.
7. Minify Switch Verification (cicd.sh)
Purpose: confirm whether the current build artifacts are minified or readable — debugging wants readable, releasing wants minified.
Learning path: see the switch source → see both artifact heads → check the mode table → remember not to edit by hand
7.1 Minimal usage
Output (the switch is only 3 lines, tied together by the same comment marker):
js:
enable: true # minify-switch
css:
enable: true # minify-switch
html:
enable: true # minify-switchCorresponding command:
grep -n 'minify-switch' _config.yml7.2 Common options
① -d / --debug: minify off, artifacts readable
Output (the head of public/css/main.css — multi-line, indented):
.anchorjs-link {
text-decoration: none !important;
transition: opacity 0.2s ease-in-out;
}
.markdown-body h1:hover > .anchorjs-link,
h2:hover > .anchorjs-link,Corresponding command:
tools/cicd.sh -d
head -c 200 public/css/main.css② -r/-c/-t: minify on, one line without comments
Output (same location becomes one line, noticeably smaller):
.anchorjs-link{text-decoration:none!important;transition:opacity .2s ease-in-out}.markdown-body h1:hover>.anchorjs-link,...Corresponding command:
tools/cicd.sh -t
head -c 200 public/css/main.css7.3 Full parameters
| Mode | minify value | Description |
|---|---|---|
-d / --debug | false | no minification (local debugging, readable output) |
-r / -c / -t | true | minified (hexo-minify always minifies at generate time, so its enable must be toggled) |
7.4 Boundaries & pitfalls
After building, cicd.sh restores
_config.yml(only when the changes involve just the minify-switch marker lines), keeping the working tree clean.
- Do not hand-edit minify in
_config.ymlto test minification: the nextcicd.shoverwrites it per mode, and your manual edit turns into “why did it change again”. Use the flags. - Local
hexo sdoes not minify whenpreview: false: to verify minification you must go throughnpm run buildorcicd.sh -t, never the local preview. - The minify switch is only 3 lines:
js/css/html. Miss one and you get a half-minified artifact where “JS is minified but CSS is not”.
7.5 Summary
Minification is decided by the build mode, not by the config file; the verification is head -c 200 public/css/main.css — is the first line a single line?
8. Environment Preflight, Single-Instance Lock & Base Address Adaptation
Purpose: the “health check” before the gate runs — if unhealthy, fail in seconds and tell you how to fix it.
Learning path: see a successful checkup → see a failed checkup → check the check-item table → remember the lock
8.1 Minimal usage
Output (a full checkup of a healthy environment, finished within 5 lines):
🔍 [preflight] 环境预检...
✅ 构建产物有效 (123456 字节)
✅ playwright 可用(NODE_PATH=/home/andy/.local/share/mise/installs/npm-playwright/1.56.0/lib/node_modules)
✅ _config.yml 未被污染
✅ 网络基址可达(HTTP 200)
✅ [preflight] 环境就绪Corresponding command:
tools/tests/release-test.sh --local8.2 Common options
① Artifacts missing / too small
Output:
❌ 构建产物不存在(public/index.html)
💡 修复命令:docker compose -f docker-compose.test.yml exec -T hexo bash -c 'tools/cicd.sh -d'Corresponding command:
tools/tests/release-test.sh --skip-build # 跳过构建但产物不存在时即可见② _config.yml polluted by the build
Output (auto-recovered; it does not block you):
⚠️ themes/matery/_config.yml 被构建污染(有未提交修改)
🔧 自动恢复:git -C themes/matery checkout -- _config.yml
✅ _config.yml 已自动恢复Corresponding command:
tools/tests/release-test.sh --local③ Local port adaptation (4000 is not hard-coded)
Output:
✓ 本地基址: http://localhost:4100(端口 4100)
✅ 已导出 TEST_BASE=http://localhost:4100 TEST_URL=http://localhost:4100Corresponding command:
tools/tests/release-test.sh --local8.3 Full parameters
| Check | Failure Behavior |
|---|---|
| Local server reachable (HTTP 200) | Prints fix commands then exits |
Build artifacts valid (public/index.html > 1000B) | Prints rebuild commands |
| playwright available | Skips browser-dependent layers |
themes/matery/_config.yml not polluted by build | Auto git checkout to restore exactly |
| Network base address reachable (release mode only) | Reports base address unreachable |
# 未就绪时打印的 3 条修复命令(任选其一)
docker compose -f docker-compose.test.yml exec -T hexo bash -c 'tools/cicd.sh -d'
tools/test.sh server
docker compose -f docker-compose.test.yml exec -T hexo bash -c 'pm2 restart all'--prepare auto-prepares: starts container if not running, rebuilds if artifacts invalid, rechecks at the end.
Single-instance lock: the gate acquires a lock at ${TMPDIR:-/tmp}/opencode/gate.lock on startup; concurrent runs are rejected outright (prints the lock-holding PID); stale locks are automatically taken over, trap EXIT releases. Concurrent gates are forbidden — they kill each other’s local server.
Base address & port adaptation: see §2’s base address section (production fixed at 443 / local port detection) — 36 test files follow automatically via exported TEST_BASE/TEST_URL.
8.4 Boundaries & pitfalls
preflightretries 3 times when the network base is unreachable (❌ 网络基址不可达(HTTP 000,期望 200/301,已重试 3 次)), then prints💡 检查代理/DNS:curl -sI https://blog.17lai.site— fix the network first, do not touch the assertions.- Local mode performs no network base check (only the local 200), so all-green locally does not mean production is reachable.
- Lock file leftovers: an abnormal exit may leave
gate.lock; the script checks whether the PID is alive and takes over automatically — only “a lock holding a live PID” counts as real concurrency. - Do not use
rm -rf publicinstead of--prepare:--preparerebuilds when artifacts are gone, while manual deletion only makes the next gate fail before L1.
8.5 Summary
preflight’s job is “either tell me how to fix it within seconds, or let me through” — it must never let you discover at minute 15 that the server was never up.
9. L14 Visual Assertion Layer
Purpose: read real computed styles with playwright and turn “position/size/color” into numeric assertions — the hard gate after CSS changes.
Learning path: run one suite → see retry and failure output → check the suite list → remember the make-target pitfall
9.1 Minimal usage
Output (a passing single suite is just one summary line):
结果: 18 通过, 0 失败Corresponding command:
node tools/visual-assert.js run --local tools/visual-assert/layout-checks.json9.2 Common options
① --local: assert against the local base (omit in production mode)
Output:
✅ L14 layout-checks:18 项全部通过Corresponding command:
node tools/visual-assert.js run --local tools/visual-assert/layout-checks.json② Failure details (only the first 3 ❌ are printed, to avoid flooding)
Output:
❌ L14 footer:<M> 失败(共 <N> 项)|明细:❌ footer-margin 期望 24px 实际 16px ❌ footer-padding ...Corresponding command:
node tools/visual-assert.js run --local tools/visual-assert/footer.json③ Per-file timeout (default 600s, override with L14_TIMEOUT)
Output:
❌ L14 post-layout:超时或异常(exit 124)Corresponding command:
L14_TIMEOUT=900 node tools/visual-assert.js run --local tools/visual-assert/layout-checks.json9.3 Full parameters
tools/visual-assert/*.json has 14 suites in total; gate L14 runs 12 of them:
layout-checks reward-modal search-modal dark-mode homepage about
footer 404 i18n tags nav-scrolled toc-expandedDeliberately not activated (run manually): mobile-menu (duplicates layout-checks’ mobile-menu-functional), post-layout (partially overlaps layout-checks).
| Property | Value |
|---|---|
| Semantics | Production-blocking (failure = FAIL); skipped locally by default |
| Enable locally | RUN_L14=1 tools/tests/release-test.sh |
| Force skip | SKIP_L14=1 |
| Failure handling | A suite that fails is automatically retried once (load jitter); only fails if still failing after retry, with details printed |
| Duration | ~299s (heavy) |
⚠️
make visual-asserttrap: that make target depends onbuild, which overwritesthemes/matery/_config.ymlplaceholders in-place → triggers L5 version consistency 4-item failures. Correct usage:node tools/visual-assert.js run --local [tools/visual-assert/<suite>.json], or let the L14 layer run it.
9.4 Boundaries & pitfalls
--localis mandatory: without it the assertions target the production base, and local changes are never measured.- A missing playwright directory skips the whole layer:
⏭️ L14 visual-assert(playwright 不可用)— do not read a skip as a pass. - An unreachable local server also skips:
⏭️ L14 视觉断言(localhost:4000 不可达 → HTTP 000). - Do not validate with
make visual-assert: polluting_config.ymlcosts you four red L5 items, and sends your debugging in a completely wrong direction.
9.5 Summary
L14 is the only layer that can prove “the pixels are right”; it is slow, heavy, and not run locally by default — which is exactly why CSS changes must manually add this layer.
10. TC Index & Git Hooks
Purpose: keep the “test file list” and the “test case document” from ever drifting apart.
Learning path: see the scan output → see the two generate/verify commands → check the mechanism table → remember the hook must be enabled once
10.1 Minimal usage
Output (generation prints scan statistics, then writes the file):
📊 扫描结果:13 层 / 42 测试文件 / 3 lib 文件 / 284 断言 / 406 用例名
✅ TC 索引已写入(13 层 / 284 断言)Corresponding command:
node tools/tests/gen-tc-index.js10.2 Common options
① Verify (this is exactly what the gate calls)
Output (one line when consistent):
✅ TC 索引与测试文件一致Corresponding command:
node tools/tests/gen-tc-index.js --check② When inconsistent (exit 1)
Output (the ❌ line in the gate summary):
❌ TC 清单不一致(运行 node tools/tests/gen-tc-index.js 更新)Corresponding command:
make tc-index-check③ Auto-regeneration on commit (the hook)
Output (pre-commit stages automatically; the commit still succeeds):
🔧 检测到 tools/tests/ 变更,重新生成 TC 清单...
✅ TC 索引已写入(13 层 / 284 断言)Corresponding command:
git config core.hooksPath .githooks # 新克隆执行一次10.3 Full parameters
The authoritative source for tests is tools/tests/**; the generated TC table lives between <!-- GENERATED:START --> and <!-- GENERATED:END --> in docs/superpowers/specs/2026-08-06-layout-test-cases.md.
| Mechanism | Description |
|---|---|
node tools/tests/gen-tc-index.js / make tc-index | Regenerate the TC index |
make tc-index-check | Check if the index is stale (inconsistent → exit 1) |
.githooks/pre-commit | When a commit touches tools/tests/, auto-regenerates and stages the document → submitting a stale index is structurally impossible |
Gate --check | Runs gen-tc-index.js --check before summary (covers --no-verify and other bypasses) |
First clone requires one-time setup: git config core.hooksPath .githooks. When the gate reports “TC index inconsistent”, run make tc-index then commit (bypass: git commit --no-verify).
The exact numbers in the scan statistics (layers/files/assertions/test names) grow with the tests — rely on the actual output; the docs never hard-code them.
10.4 Boundaries & pitfalls
make tc-indexmodifies the document: commit it along with the change, otherwise the next--checkis red again.--no-verifybypasses the hook but not the gate: the--checkinside the gate is the last net.- Hand-written content outside the GENERATED block is never overwritten: feel free to add notes outside the table; the generator only rewrites between the markers.
10.5 Summary
Test files are the source, the TC document is a mirror; the hook keeps the mirror live, the gate --check keeps the mirror trustworthy.
11. Flake Visibility & Baseline Reference Values
Purpose: list “passed only after retry” items explicitly — they do not block a release, but they must not vanish silently.
Learning path: see one flaky summary → see the three baselines → check the baseline table → remember the numbers change
11.1 Minimal usage
Output (a clean round — no flaky section):
测试结果: PASS=<N> FAIL=0
=============================================
🎉 全部通过!Corresponding command:
tools/tests/release-test.sh11.2 Common options
① When there are flaky items (one extra ⚠️ line, PASS/FAIL unchanged)
Output:
⚠️ 本次门禁 flaky: 1 项(L14 nav-scrolled)
测试结果: PASS=<N> FAIL=0
🎉 全部通过!Corresponding command:
tools/tests/release-test.sh② The three baselines
Output (the fixed marker of the local tier):
⏭️ 已跳过 L10(远程 SW 冒烟)与 L11(playwright 集成)—— 本地迭代模式;
测试结果: PASS=<N> FAIL=0
🎉 全部通过!Corresponding command:
tools/tests/release-test.sh --local11.3 Full parameters
| Baseline | Expected | Command |
|---|---|---|
| Local | All pass (0 failures) | tools/tests/release-test.sh --local |
| Local + L14 | All pass (0 failures, including visual assertions) | RUN_L14=1 tools/tests/release-test.sh |
| Production | All pass (0 failures) | tools/tests/release-test.sh (after release) |
The exact PASS count grows with each version (every added assertion changes it); rely on the actual output instead of a hard-coded number.
3 libs:
assert.sh(82 lines),retry.sh(114 lines, responsible for flake tracking),preflight.sh(230 lines).browser-env.jsis a playwright shared helper (see §6).
11.4 Boundaries & pitfalls
- Flaky is not a pass: it only means “passed after retry”; the same item showing flaky two rounds in a row is a bug worth investigating.
- PASS counts are not comparable across tiers:
--localskips L10/L11/L14, so PASS is naturally lower; comparing numbers is meaningless — look only atFAIL=0. - Re-run baselines, do not cite them: the post-release production gate must actually run once; a PASS in an old log is not evidence.
11.5 Summary
Read a gate result with two questions only: is FAIL=0, and is there a flaky section? The first is the gate, the second is a technical-debt reminder.
12. How to Add a Test Case
Purpose: the full path from “write a test file” to “hooked into the gate and collected by the TC index”.
Learning path: see the new test’s own output → see the gate output once hooked → use the templates → remember the mock and the criteria
12.1 Minimal usage
Output (after writing the new file, get it passing on its own first — this line is the contract the gate matches):
✅ should render expected element
结果: PASS=1 FAIL=0Corresponding command:
node tools/tests/my-feature.test.jsReusing the same contract inside the gate (run_test usage):
run_test "my-feature" "node tools/tests/my-feature.test.js"run_test is a helper inside release-test.sh: it runs the command, captures output, and decides pass/fail by the PASS=N FAIL=0 contract.
12.2 Common options
① Belongs to L13 (pure unit/static, no browser)
Output (one more ✅ in the gate once hooked):
✅ 单测 my-feature.test.jsCorresponding command:
# 在 tools/tests/layers/L13_units.sh 的 for 清单里追加文件名即可(unit/ 前缀自动判断)
my-feature.test.js \② Belongs to L11 (needs chromium + server)
Output (the criterion is PASS=N FAIL=0):
✅ my-interaction 通过Corresponding command:
retry_match "my-interaction" "node tools/tests/my-interaction.test.js" "PASS=.*FAIL=0" # 写进 layers/L11_integration.sh③ Local verification (only L13 + curl assertions — fastest loop)
Output:
测试结果: PASS=<N> FAIL=0
🎉 全部通过!Corresponding command:
tools/tests/release-test.sh --local④ Sync the TC index
Output:
✅ TC 索引与测试文件一致Corresponding command:
make tc-index12.3 Full parameters
Steps
- Determine the test type:
- Pure unit / static assertions (no browser) → L13 (node direct)
- playwright integration (needs chromium + server) → L11
- Create the test file
tools/tests/xxx.test.js(node:test or playwright) - External dependency tests: wrap with
retry_run/retry_match(lib/retry.sh), auto-classify and degrade on total failure - playwright tests: use
lib/browser-env.js’sinterceptThirdParty+collectPageErrorsfor unified error attribution - Register in the matching layer script (
tools/tests/layers/L11_integration.shorL13_units.sh), align the output format (PASS=N FAIL=0orN 通过 / 0 失败) - Local verification:
tools/tests/release-test.sh --local(runs L13 + curl assertions); the release gate runs the full suite - Sync TC index: after adding/modifying, the TC index must stay in sync (
.githooks/pre-commitdoes this automatically; or manually runmake tc-index) — otherwise the gate--checkreports “TC index inconsistent”
Code Templates
L13 unit test template (node:test, no browser):
// tools/tests/my-feature.test.js
const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const PUBLIC = path.resolve(__dirname, '../../public');
describe('my-feature', () => {
it('should render expected element', () => {
const html = fs.readFileSync(path.join(PUBLIC, 'index.html'), 'utf8');
assert.ok(html.includes('expected-marker'), 'missing expected marker');
});
});
// 末尾输出(release-test.sh 通过此行判定)
const pass = 1, fail = 0;
console.log(`\n结果: PASS=${pass} FAIL=${fail}`);
process.exit(fail > 0 ? 1 : 0);L11 playwright template (needs chromium + server):
// tools/tests/my-interaction.test.js
const { chromium } = require('playwright');
const { interceptThirdParty, collectPageErrors } = require('./lib/browser-env');
const BASE = process.env.TEST_BASE || 'http://localhost:4000';
let browser, page;
let pass = 0, fail = 0;
async function setup() {
browser = await chromium.launch();
page = await browser.newPage();
await interceptThirdParty(page);
}
async function testFeature() {
const env = collectPageErrors(page, BASE);
await page.goto(`${BASE}/posts/xxxxx/`, { waitUntil: 'networkidle' });
const el = await page.$('.my-feature');
if (el) { pass++; } else { fail++; console.error('FAIL: .my-feature not found'); }
// 检查无 JS 异常
if (env.jsErrors.length > 0) { fail++; console.error('FAIL: JS errors', env.jsErrors); }
else { pass++; }
}
(async () => {
await setup();
await testFeature();
await browser.close();
console.log(`\n结果: PASS=${pass} FAIL=${fail}`);
process.exit(fail > 0 ? 1 : 0);
})();Hooking Into the Gate: Where to Add a Line
L13 (node unit test): append one file name to the for t in \ list in tools/tests/layers/L13_units.sh (the directory prefix — unit/ or root — is detected automatically).
L11 (playwright integration): append in tools/tests/layers/L11_integration.sh:
retry_match "my-interaction" "node tools/tests/my-interaction.test.js" "PASS=.*FAIL=0"
retry_matchwraps external-dependency tests — auto-retries 3 times on network jitter, and degrades to warn instead of fail when all attempts fail (see §5).
Worked Example: Adding a “Sidebar Collapse” Test
- Requirement: verify the post sidebar auto-collapses on narrow screens
- Type: needs a browser → L11 playwright
- Create
tools/tests/sidebar-collapse.test.js(using the L11 template above) - Hook in: add a
retry_matchline inlayers/L11_integration.sh - Verify:
tools/tests/release-test.sh --local? — no, local skips L11; runnode tools/tests/sidebar-collapse.test.jsdirectly instead, or use--skip-l10to keep L11 - TC sync:
make tc-index(or let the pre-commit hook do it automatically)
Assertion Output Convention
release-test.sh judges pass/fail by output pattern, so the test file must print a matchable summary line at the end:
console.log(`\n结果: PASS=${pass} FAIL=${fail}`);
process.exit(fail > 0 ? 1 : 0);Authoritative Test Case List
docs/superpowers/specs/2026-08-06-layout-test-cases.md (full layout test cases) + docs/testing/TESTING-PYRAMID-GUIDE.md (testing methodology) — after adding a feature, update the case list and release-test.sh coverage in sync.
12.4 Boundaries & pitfalls
Mocks must match real Hexo objects (same as §4.4): a plain-array mock keeps unit tests green while the build outputs 0 bytes, and a missing toArray() cannot be detected.
The step most easily forgotten after adding a test:
Output (TC sync skipped, so the last gate line goes red):
❌ TC 清单不一致(运行 node tools/tests/gen-tc-index.js 更新)Corresponding command:
node tools/tests/gen-tc-index.js --checkDo not stuff playwright tests into L13: they always fail without a browser and drag the whole layer down.
12.5 Summary
Adding a test = one file + one hook-up + one TC sync; skip any one of the three and the gate reminds you as “inconsistent” or “always failing”.
13. Performance Verification (LCP Baseline, Manual)
Purpose: LCP is not in the gate, but it must have a reproducible comparison baseline.
Learning path: see the baseline conclusion → see the reproduction command → check the levers and the threshold → remember the noscript trap
13.1 Minimal usage
Output (the mobile conclusion given by the baseline document — this is the “before optimization” reference):
**移动端 LCP 4.6 s / 5.3 s 均远超 2.5 s 门槛**,与 Search Console「40 个 URL 的 LCP > 2.5s」的字段结论方向一致。Corresponding command:
grep -n '移动端 LCP' docs/analysis/LCP-V2-BASELINE-2026-09-18.md13.2 Common options
① Look at the baseline table structure (page / LCP / FCP / TBT / CLS / performance score / LCP element)
Output:
| 模式 | 页面 | LCP | FCP | TBT | CLS | 性能分 | LCP 元素 |Corresponding command:
grep -n '| 模式 | 页面 | LCP' docs/analysis/LCP-V2-BASELINE-2026-09-18.md② Look at run-to-run variance (it decides the acceptance criterion)
Output:
- mobile LCP 两组分别为 **4.6/5.3 s**(§2.2)与 **3.7/3.6 s**(本组)——**运行间方差约 ±0.9 s**,与 mobile 节流下的固有噪声一致。**B 验收必须用多组采样的中位数,勿用单次值**。Corresponding command:
grep -n '运行间方差' docs/analysis/LCP-V2-BASELINE-2026-09-18.md13.3 Full parameters
- Baseline:
docs/analysis/LCP-V2-BASELINE-2026-09-18.md(resource counts / Lighthouse desktop+mobile / LCP element identity / §5 reproduction commands / §7 optimization work) - Four optimizations (2026-09-18~20): critical CSS preload · highlight conditional loading by layout · markmap localized + async · post hero-image preload
- Threshold: mobile LCP ≤ 2.5s (Search Console “40 URLs over threshold” is the observation basis)
- Trigger: re-measure whenever head-level resource loading order/conditions change (CSS/JS/images)
13.4 Boundaries & pitfalls
- Trap: not stripping
noscriptinflates the resource count by 4 per page (baseline §1.3) — always strip before re-measuring. - A single sample is not an acceptance value: under mobile throttling the run-to-run variance is about ±0.9 s; take the median of multiple runs.
- LCP element identity is unstable: the homepage LCP element drifts between runs, so compare on “element identity + value” together, not the number alone.
- LCP staying out of the automated gate is deliberate: it needs Lighthouse sampling on real devices with controlled network conditions, which assertion-style tests cannot express.
13.5 Summary
Performance verification = baseline document + reproduction command + median criterion; miss one and any “optimization result” you get is untrustworthy.
⚠️ Known Pitfalls
Pitfall 5: Config Changes Require Clean Build
Output (the typical symptom under a stale cache: L1 green, feature assertion red):
🔨 L1: 构建验证
✅ 构建成功 (hexo g Success)
...
❌ 搜索入口Corresponding command:
npm run clean && npm run build # 或 tools/tests/release-test.sh --prepareCause: Local preview uses stale cached artifacts; test assertions are checking old behavior.
Pitfall 6: source/_data/* Incremental Cache Misjudgment
Output (the L2 assertion on the page does not match):
❌ /friends/ → 200 但页面无友链内容Corresponding command:
rm -f db.json && npm run build # 容器环境用 tools/cicd.sh -d(内置 clean)Cause: Hexo’s incremental cache incorrectly judges “cached, unchanged”.
Appendix: Test ↔ Feature Map
Purpose: Want to know “is feature X covered by automated tests?” — look up by feature name below.
| Feature | Test File | Layer | What It Verifies |
|---|---|---|---|
| Page effects (sakura/snowflakes/fireworks) | effects-integration.test.js | L11 | Effect scripts load per gate, no errors |
| Video background | videobg-integration.test.js | L11 | Threshold/light-dark pool/webm contract/disabled state |
| Word cloud | wordcloud.test.js | L11 | Rendering / no jQuery / TOC anti-flicker / dark-light switch |
| Multilingual | i18n.test.js | L11 | MATERY_I18N injection + button copy + en translations |
| Music APlayer | musics-integration.test.js | L11 | Multi-domain failover |
| Lazyload | lazyload-integration.test.js | L11 | handleCard three-way dispatch (51 assertions) |
| Floating panel | floating-panel-integration.test.js | L11 | Toggle / font scaling / persistence |
| Content width | content-width.test.js | L11 | 4K/FHD/2K/single-column cap |
| Read mode | readmode-integration.test.js | L11 | Fullscreen enter/exit / floating ball / code fullscreen / expand |
| Wiki styles | wiki-styles.test.js | L11 | Note / ::: container colors + centering + width consistency |
| codeWidget idempotency | code-widget.test.js | L11 | Second invocation still works with single click |
| Event bus | core-events-integration.test.js | L11 | Event bus / progress bar linkage |
| Wiki prism | wiki-prism-integration.test.js | L11 | Code blocks prism + line-numbers |
| Reward / trad-simp | misc-interactions.test.js | L11 | Reward popup / simplified-traditional conversion |
| Client language strategy | lang-client-strategy.test.js | L11 | Site-wide follow / crawler skip / panel echo |
| Rich content | rich-content-integration.test.js | L11 | Math / mermaid / markmap / typewriter / share / Live2D |
| Wiki multilingual | wiki-integration.test.js | L11 | Multilingual wiki reachability / sidebar / language switcher |
| Lightbox | lightbox.test.js | L11 | Gallery/image zoom interaction |
| Card hover | gallery-hover.test.js | L11 | Gallery/card hover animation |
| TOC collapse | unit-toc.test.js | L13 | collapseDepth 0||6 falsy trap |
| Search | unit-search.test.js | L13 | Three-engine config |
| Multilingual config | unit-multilang.test.js | L13 | Language config parsing |
| Encryption extensions | unit-encrypt2.test.js | L13 | Fragment + wiki encryption |
| wiki helper | unit-wiki-helper.test.js | L13 | Language parsing / sidebar rendering / canonical fallback |
| Sidebar i18n | unit-sidebar-i18n.test.js | L13a | Lookup + fallback chain |
| Sidebar keys | unit-sidebar-keys.test.js | L13a | Gate validator 4 wikis × 9 languages |
| Fallback chain | lang-fallback.test.js | L13 | 4-level fallback (13 assertions) |
| i18n core | unit-i18n-core.test.js | L13a | resolveI18n 4-level chain + cfg defense |
| i18n helper | unit-i18n-helper.test.js | L13 | t() helper fallback |
| ECharts | echarts-charts.test.js | L13 | Chart rendering |
| Banner background | banner-bg.test.js | L13 | Banner & background preference linkage |
| Homepage structure | homepage.test.js | L13 | Homepage DOM structure |
| Image size | imgsize-unit.test.js | L13 | normalizeImgUrl + dimension reading |
| Standalone pages | unit-standalone.test.js | L13 | Exclusion logic + language prefix exemption |
| markmap pruning | unit-markmap-prune.test.js | L13a | Plugin injection removal on pages without mindmaps (6 cases) |
| “Updated on” | unit-updated.test.js | L13a | Takes the git last-commit time (4 cases) |
| Encryption system | unit-encrypt.test.js | L13a | AES-GCM + PBKDF2 closed loop (9 cases) |
| CSS architecture | unit-css-architecture.test.sh | L13 | Key selectors in compiled output |
| Version numbers | unit-version.test.sh | L13 | Increment carry |
| Retry library | unit-retry.test.sh | L13 | Backoff retry |
| Deploy targets | unit-deploy-target.test.sh | L13 | hexo/hexoback dual-activation |
Appendix: Triple-Role Self-Check List
When adding or modifying an article in the “hexo theme feature test” series, check these three items:
| # | Check | Pass Criteria |
|---|---|---|
| ① | Verifiable | Every feature has a clear input → expected output (automated assertion marker or manual verification standard) |
| ② | Demonstrated | Every feature describes its rendered effect (text description, rendered example, or screenshot) |
| ③ | Actionable | Every feature has syntax / config steps + caveats (parameter order, prerequisites, common pitfalls) |
Quick check: If a feature “only lists its name without saying how to verify” → missing ①; “only lists syntax without showing effect” → missing ②; “doesn’t explain how to use it or is ambiguous” → missing ③.
Appendix: Testing System Quick Reference
| Command | Purpose |
|---|---|
tools/tests/release-test.sh | Full release gate (L1-L14) |
tools/tests/release-test.sh --local | Local iteration (adaptive port, skips L10/L11/L14) |
tools/tests/release-test.sh --prepare | Auto-prepare environment (container + build + recheck) |
RUN_L14=1 tools/tests/release-test.sh --local | Enable L14 visual assertions locally |
make tc-index / make tc-index-check | Generate / verify TC index (.githooks/pre-commit auto-syncs) |
tools/tests/run-tests.sh | Removed 2026-09-13 (overlapped with L11); see tools/tests/release-test.sh |
node tools/tests/gen-tc-index.js | Generate/verify TC index (make tc-index) |
make test-pwa | Vercel test domain SW smoke (7 pages) + interaction verification |
make visual-compare / visual-assert | Visual regression (playwright numeric assertions); ⚠️ make visual-assert includes a build dependency that pollutes _config.yml, prefer node tools/visual-assert.js run --local |
tools/visual-regression.sh report | Visual comparison report (20 pages × 4 breakpoints) |
References
系列教程
Hexo 主题功能测试系列
- Hexo主题功能测试-布局与页面篇 —— 页面布局、导航、侧边栏、卡片等结构功能
- Hexo主题功能测试-交互视觉篇 —— 代码高亮、图片灯箱、动画、明暗切换等交互
- Hexo主题功能测试-内容tag篇 —— note / tabs / timeline / label / button 等 tag 插件
- Hexo主题功能测试-Markdown语法篇 —— Markdown 渲染与扩展语法
- Hexo主题功能测试-自动化测试篇 —— 主题功能的自动化测试方案

