Loading...

Loading...

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 sectionWhat 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 PitfallsDistinguish “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/manifest

Stacked 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.json

1.3 Full parameters

LayerNameHow It RunsDependencies
L1Build verificationhexo generate + artifact checknone
L13Full unit test gatenode tools/tests/*.test.js + shell unit testsno chromium
L11Playwright integrationreal browser + local serverchromium + server
L2/L2b/L2x/L2y/L2iProduction URL assertionscurl + grepproduction/local server
L3-L8Feature marker checkscurl + static assertionsproduction/local server
L9Static assets + SW smokecurl + playwrightproduction domain
L13aCoverage statisticsnode --experimental-test-coverage scans unit/**none
L14Visual assertionsnode tools/visual-assert.js run (12 suites)chromium + server
L10SW smoke (test domain)playwrightVercel test domain blog2.17lai.site

1.4 Boundaries & pitfalls

  • Execution order is not documentation order: manifest line 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/*.sh only defines run_LXX() and depends on release-test.sh having source lib/assert.sh first (pass/fail are global counters). To verify one layer alone, run the test file it wraps, not bash layers/L13_units.sh.
  • A missing layer script is a hard failure: if manifest names a file that layers/ does not contain → ❌ 层脚本缺失:xxx.sh exits 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.sh

2.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.sh

2.3 Full parameters

FlagEffect
--skip-buildSkips L1 build + artifact verification (use when already built)
--localTarget switches to adaptive local base (port detection, see base address section below), skips L10 (remote SW smoke 5min+) and L11 (playwright serial >800s)
--skip-l10Skips only L10, keeps L11 playwright integration
--prepareAuto-prepares environment: starts container if not running, rebuilds if artifacts invalid, rechecks at the end
RUN_L14=1Enables L14 visual assertions in local mode (skipped locally by default)
SKIP_L14=1Forces 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 (manifest line 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 -r publishes, you MUST run tools/tests/release-test.sh to verify the production environment.

2.4 Boundaries & pitfalls

① Concurrency is rejected outright

Output:

❌ [preflight] 门禁已在运行(PID 12345),拒绝并发启动
   锁文件:/tmp/opencode/gate.lock
   💡 如确认无其他门禁在跑,可手动删除:rm /tmp/opencode/gate.lock

Corresponding 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 --local and no RUN_L14, L14 always skips — do not misread “did not run” as “passed”.
  • --local turns 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 即跑 L1

3.2 Common options

① L2: URL reachability — one line per path

Output:

✅ /archives/ → 200
✅ /categories/ → 200
✅ /tags/ → 200

Corresponding 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.js

Corresponding 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.json

3.3 Full parameters

LayerCoverageAssertion Example
L1Build verificationhexo g Success + public/index.html > 1000B
L220 layout page URLs reachable/posts/fc764afd/, /archives/, /categories/, /tags/, /about/, /friends/, /galleries/, /bb/, /musics/, /movies/, /msg/ + 4 test articles → HTTP 200
L2bMultilingual verificationen article real translation / fallback notice banner / comment path normalization / default language no prefix
L2xUnified language fallbackMATERY_LANG injection / fallback pages / standalone page multilingual (incl. gallery sub-pages) / aggregation page multilingual
L2yEncrypt/decrypt refreshwiki sidebar leaks no metadata/section keys (structure/i18n/encrypt_) / encrypted container complete (hbeForm + storage-key)
L2iSEO structured dataog:image / JSON-LD / fetchpriority
L3Comment section checkmsg/friends/bb pages contain #comments
L4href=/ style errorspage href=/ references should be 0
L5Version consistencyconfig vs sw.tmp.js consistent in 3 places
L6Key resource check404 page / key JS versions
L7Core feature coveragegallery 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)
L8Enhanced feature coveragetag plugin rendering (note/timeline/tabs/label/githubCard/mermaid) / encrypted posts / Feed / static assets / analytics
L9Static assets + SW smokemain.css > 50KB / utils.js > 5KB / production domain 7 pages no SW errors
L10SW smoke (test domain)blog2.17lai.site 7 pages no SW errors + interaction verification (search/reward/lightbox/TOC/dark mode)
L11Playwright integration (18 items)see table below
L12Localized asset checkmermaid / aplayer assets exist
L13Full unit test gate15 *.test.js + search integration + 4 *.test.sh + 1 tutorial-structure gate (see §4)
L13aCoverage statisticsunit/**/*.test.js coverage scan (line ≥85 / branch ≥77 / funcs ≥70)
L14Visual assertions (12 suites)see §9

Comment library version baseline (upgraded 2026-09-24, config in the userConfig/_config.tmp.yml libs section): waline v=3.15.2 (enabled) / twikoo v=2.0.8 (disabled) / valine v=1.5.3 + av v=5.19.2 (disabled) / gitalk v=1.8.0 (deprecated); skill matery-libs/references/{waline,twikoo,valine,gitalk}.md records the versions and upgrade history in sync.

L11 Playwright Integration List (real browser)

Test FileCoverage
effects-integration.test.jsPage effects (sakura/snowflake/fireworks loading)
videobg-integration.test.jsVideo background (threshold/light-dark pool/webm contract/disabled state)
wordcloud.test.jsWord cloud / no jQuery / TOC anti-flicker / dark-light switching
i18n.test.jsMultilingual completion (MATERY_I18N injection + button copy + en translations)
musics-integration.test.jsOnline music APlayer (multi-domain failover)
lazyload-integration.test.jsLazyload handleCard three-way dispatch (51 assertions)
floating-panel-integration.test.jsFloating panel (toggle/font scaling/persistence)
content-width.test.jsContent width unification (4K/FHD/2K/single-column cap)
readmode-integration.test.jsRead mode / code fullscreen / scroll-down-bar
wiki-styles.test.jsWiki tag component styles (note / ::: container colors + centering + width consistency)
code-widget.test.jscodeWidget delegation idempotency (second invocation still works with single click)
core-events-integration.test.jsEvent bus / progress bar linkage
wiki-prism-integration.test.jsWiki code blocks prism + line-numbers
misc-interactions.test.jsReward popup / trad-simp conversion (G14/G15)
lang-client-strategy.test.jsClient language strategy (site-wide follow/crawler skip/panel echo, 7 assertions)
rich-content-integration.test.jsRich content rendering (math MathJax+KaTeX/mermaid/markmap/typewriter/share/Live2D, 11 assertions)
wiki-integration.test.jsMultilingual wiki reachability / sidebar sections / language switcher (18 assertions)
infinite-scroll-integration.test.jsInfinite Scroll (Home/Archive real pagination + tag-page single-page grid)
lightbox.test.jsLightbox (gallery/image zoom interaction)
gallery-hover.test.jsGallery/card hover animation (guards the classList multi-class fix)

3.4 Boundaries & pitfalls

  • L11 always skips locally: --local skips 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 for 0 失败, and lazyload has 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.js and infinite-scroll-integration.test.js existed 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 is tools/tests/unit-fontawesome.test.py (L13a’s glob only takes .test.js), run it manually with python3 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=0

Corresponding command:

node tools/tests/unit/unit-toc.test.js

4.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 fail

Corresponding command:

grep -n 'console.log' tools/tests/unit/unit-toc.test.js | tail -2

② The shell unit test summary line is the shortest

Output:

结果: PASS

Corresponding 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.pages are Hexo Query objects (array-like), .filter() returns another Query, not an array, and they cannot be for...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 threw wikiPages is not iterable → every HTML output was 0 bytes. The mock only exercised the real path after toArray() 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_视频.log

Corresponding 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_视频.log

Corresponding 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):

SignatureVerdictResult
ERR_NAME_NOT_RESOLVED / ECONNREFUSED / ETIMEDOUT / 429 / 50x etc.external unavailable⚠️ degraded warn (returns 0, does not block release)
no external signaturebusiness 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.sh asserts 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_match pattern must anchor on zero failures: matching only PASS= 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.js

6.3 Full parameters

MechanismDescription
interceptThirdPartyIntercepts 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)
collectPageErrorsCollects only JS exceptions + same-origin (localhost/production domain) resource failures; third-party CDN/image-host failures are environment noise and not counted
ERR_ABORTED exclusionNavigation 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 into net::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 collectPageErrors is the current BASE; running locally while passing the production domain makes local resource failures look like third-party ones and silently disappear.
  • Tests with multiple goto calls must tolerate ERR_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-switch

Corresponding command:

grep -n 'minify-switch' _config.yml

7.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.css

7.3 Full parameters

Modeminify valueDescription
-d / --debugfalseno minification (local debugging, readable output)
-r / -c / -ttrueminified (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.yml to test minification: the next cicd.sh overwrites it per mode, and your manual edit turns into “why did it change again”. Use the flags.
  • Local hexo s does not minify when preview: false: to verify minification you must go through npm run build or cicd.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 --local

8.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:4100

Corresponding command:

tools/tests/release-test.sh --local

8.3 Full parameters

CheckFailure Behavior
Local server reachable (HTTP 200)Prints fix commands then exits
Build artifacts valid (public/index.html > 1000B)Prints rebuild commands
playwright availableSkips browser-dependent layers
themes/matery/_config.yml not polluted by buildAuto 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

  • preflight retries 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 public instead of --prepare: --prepare rebuilds 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.json

9.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.json

9.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-expanded

Deliberately not activated (run manually): mobile-menu (duplicates layout-checks’ mobile-menu-functional), post-layout (partially overlaps layout-checks).

PropertyValue
SemanticsProduction-blocking (failure = FAIL); skipped locally by default
Enable locallyRUN_L14=1 tools/tests/release-test.sh
Force skipSKIP_L14=1
Failure handlingA suite that fails is automatically retried once (load jitter); only fails if still failing after retry, with details printed
Duration~299s (heavy)

⚠️ make visual-assert trap: that make target depends on build, which overwrites themes/matery/_config.yml placeholders 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

  • --local is 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.yml costs 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.js

10.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.

MechanismDescription
node tools/tests/gen-tc-index.js / make tc-indexRegenerate the TC index
make tc-index-checkCheck if the index is stale (inconsistent → exit 1)
.githooks/pre-commitWhen a commit touches tools/tests/, auto-regenerates and stages the document → submitting a stale index is structurally impossible
Gate --checkRuns 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-index modifies the document: commit it along with the change, otherwise the next --check is red again.
  • --no-verify bypasses the hook but not the gate: the --check inside 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.sh

11.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 --local

11.3 Full parameters

BaselineExpectedCommand
LocalAll pass (0 failures)tools/tests/release-test.sh --local
Local + L14All pass (0 failures, including visual assertions)RUN_L14=1 tools/tests/release-test.sh
ProductionAll 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.js is 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: --local skips L10/L11/L14, so PASS is naturally lower; comparing numbers is meaningless — look only at FAIL=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=0

Corresponding command:

node tools/tests/my-feature.test.js

Reusing 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.js

Corresponding 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-index

12.3 Full parameters

Steps

  1. Determine the test type:
    • Pure unit / static assertions (no browser) → L13 (node direct)
    • playwright integration (needs chromium + server) → L11
  2. Create the test file tools/tests/xxx.test.js (node:test or playwright)
  3. External dependency tests: wrap with retry_run / retry_match (lib/retry.sh), auto-classify and degrade on total failure
  4. playwright tests: use lib/browser-env.js’s interceptThirdParty + collectPageErrors for unified error attribution
  5. Register in the matching layer script (tools/tests/layers/L11_integration.sh or L13_units.sh), align the output format (PASS=N FAIL=0 or N 通过 / 0 失败)
  6. Local verification: tools/tests/release-test.sh --local (runs L13 + curl assertions); the release gate runs the full suite
  7. Sync TC index: after adding/modifying, the TC index must stay in sync (.githooks/pre-commit does this automatically; or manually run make tc-index) — otherwise the gate --check reports “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_match wraps 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

  1. Requirement: verify the post sidebar auto-collapses on narrow screens
  2. Type: needs a browser → L11 playwright
  3. Create tools/tests/sidebar-collapse.test.js (using the L11 template above)
  4. Hook in: add a retry_match line in layers/L11_integration.sh
  5. Verify: tools/tests/release-test.sh --local? — no, local skips L11; run node tools/tests/sidebar-collapse.test.js directly instead, or use --skip-l10 to keep L11
  6. 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 --check

Do 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.md

13.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.md

13.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 noscript inflates 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 --prepare

Cause: 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.

FeatureTest FileLayerWhat It Verifies
Page effects (sakura/snowflakes/fireworks)effects-integration.test.jsL11Effect scripts load per gate, no errors
Video backgroundvideobg-integration.test.jsL11Threshold/light-dark pool/webm contract/disabled state
Word cloudwordcloud.test.jsL11Rendering / no jQuery / TOC anti-flicker / dark-light switch
Multilinguali18n.test.jsL11MATERY_I18N injection + button copy + en translations
Music APlayermusics-integration.test.jsL11Multi-domain failover
Lazyloadlazyload-integration.test.jsL11handleCard three-way dispatch (51 assertions)
Floating panelfloating-panel-integration.test.jsL11Toggle / font scaling / persistence
Content widthcontent-width.test.jsL114K/FHD/2K/single-column cap
Read modereadmode-integration.test.jsL11Fullscreen enter/exit / floating ball / code fullscreen / expand
Wiki styleswiki-styles.test.jsL11Note / ::: container colors + centering + width consistency
codeWidget idempotencycode-widget.test.jsL11Second invocation still works with single click
Event buscore-events-integration.test.jsL11Event bus / progress bar linkage
Wiki prismwiki-prism-integration.test.jsL11Code blocks prism + line-numbers
Reward / trad-simpmisc-interactions.test.jsL11Reward popup / simplified-traditional conversion
Client language strategylang-client-strategy.test.jsL11Site-wide follow / crawler skip / panel echo
Rich contentrich-content-integration.test.jsL11Math / mermaid / markmap / typewriter / share / Live2D
Wiki multilingualwiki-integration.test.jsL11Multilingual wiki reachability / sidebar / language switcher
Lightboxlightbox.test.jsL11Gallery/image zoom interaction
Card hovergallery-hover.test.jsL11Gallery/card hover animation
TOC collapseunit-toc.test.jsL13collapseDepth 0||6 falsy trap
Searchunit-search.test.jsL13Three-engine config
Multilingual configunit-multilang.test.jsL13Language config parsing
Encryption extensionsunit-encrypt2.test.jsL13Fragment + wiki encryption
wiki helperunit-wiki-helper.test.jsL13Language parsing / sidebar rendering / canonical fallback
Sidebar i18nunit-sidebar-i18n.test.jsL13aLookup + fallback chain
Sidebar keysunit-sidebar-keys.test.jsL13aGate validator 4 wikis × 9 languages
Fallback chainlang-fallback.test.jsL134-level fallback (13 assertions)
i18n coreunit-i18n-core.test.jsL13aresolveI18n 4-level chain + cfg defense
i18n helperunit-i18n-helper.test.jsL13t() helper fallback
EChartsecharts-charts.test.jsL13Chart rendering
Banner backgroundbanner-bg.test.jsL13Banner & background preference linkage
Homepage structurehomepage.test.jsL13Homepage DOM structure
Image sizeimgsize-unit.test.jsL13normalizeImgUrl + dimension reading
Standalone pagesunit-standalone.test.jsL13Exclusion logic + language prefix exemption
markmap pruningunit-markmap-prune.test.jsL13aPlugin injection removal on pages without mindmaps (6 cases)
“Updated on”unit-updated.test.jsL13aTakes the git last-commit time (4 cases)
Encryption systemunit-encrypt.test.jsL13aAES-GCM + PBKDF2 closed loop (9 cases)
CSS architectureunit-css-architecture.test.shL13Key selectors in compiled output
Version numbersunit-version.test.shL13Increment carry
Retry libraryunit-retry.test.shL13Backoff retry
Deploy targetsunit-deploy-target.test.shL13hexo/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:

#CheckPass Criteria
①VerifiableEvery feature has a clear input → expected output (automated assertion marker or manual verification standard)
②DemonstratedEvery feature describes its rendered effect (text description, rendered example, or screenshot)
③ActionableEvery 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

CommandPurpose
tools/tests/release-test.shFull release gate (L1-L14)
tools/tests/release-test.sh --localLocal iteration (adaptive port, skips L10/L11/L14)
tools/tests/release-test.sh --prepareAuto-prepare environment (container + build + recheck)
RUN_L14=1 tools/tests/release-test.sh --localEnable L14 visual assertions locally
make tc-index / make tc-index-checkGenerate / verify TC index (.githooks/pre-commit auto-syncs)
tools/tests/run-tests.shRemoved 2026-09-13 (overlapped with L11); see tools/tests/release-test.sh
node tools/tests/gen-tc-index.jsGenerate/verify TC index (make tc-index)
make test-pwaVercel test domain SW smoke (7 pages) + interaction verification
make visual-compare / visual-assertVisual 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 reportVisual comparison report (20 pages × 4 breakpoints)

References

系列教程

全部文章RSS订阅

Hexo 主题功能测试系列


Hexo Theme Feature Test - Automated Testing
Posted on
September 11, 2026
reprint policy. If reproduced, please indicate source
Support
Comments
Data Loading...
 Current

Read More

Hexo Theme Feature Test - Automated Testing
Hexo Theme Feature Test - Automated Testing Hexo Theme Feature Test - Automated Testing
Complete tutorial for the theme's automated testing system: testing pyramid (L1 build / L13 unit gate / L11 Playwright i
2026-09-11
Next 

Read More

Hexo Theme Feature Test - Markdown Syntax
Hexo Theme Feature Test - Markdown Syntax Hexo Theme Feature Test - Markdown Syntax
A complete Markdown syntax tutorial and test for the theme: full coverage of 16 markdown-it plugins (emoji/abbr/footnote
2026-08-08