Files
materials/测试开发工程师/testdev-learning-path/tools/check-chapter.js
huanghaosheng bd678373b1 feat: 测试开发学习路径上线阶段 1 前两个模块(26 章 / 117 小节),工具链支持多阶段
- 新增 modules/s1-01-case-design/(测试理论与用例设计,13 章 / 59 小节)
- 新增 modules/s1-02-http-api/(HTTP 接口与接口测试基础,13 章 / 58 小节)
- tools/modules-plan.json 改为按阶段组织,阶段 1 的 4 个模块全部登记(未开工的两个标「筹备中」跳过)
- tools/build-module-index.js 支持多阶段,上一/下一模块按全书顺序跨阶段衔接(数据库 → 测试理论与用例设计)
- 新增 tools/check-chapter.js:单章自检(结构 / 章号 / 代码块 / 表格 / 锚点),支持 --strict 校验侧栏同步
- assets/doc.css 补 .box.pit 样式;index.html 登记 s1-0 / s1-1 路由;README 更新进度与工具说明
2026-10-16 10:39:46 +08:00

187 lines
9.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/* ==========================================================================
单章 / 单模块自检:给「正在写这一章」的人一个即时反馈,不必跑全站自检
用法:
node tools/check-chapter.js modules/s1-01-case-design/03-equiv.html
node tools/check-chapter.js modules/s1-01-case-design # 整个模块
node tools/check-chapter.js modules/s1-01-case-design/03-equiv.html --strict
参数可以是文件或目录(目录会检查其中所有 NN-*.html),路径相对本工具上一级。
与 tools/check-pages.js 的关系:这里只检查「单个页面自己能负责」的部分
(结构、格式、章号、锚点、链接),侧栏目录树一致性等跨页面项目仍然由
check-pages.js 在跑完 build-nav.js 之后统一检查。
--strict 额外要求:本章所有小节都在侧栏目录树里出现(写完并跑过 build-nav.js 之后用)。
========================================================================== */
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const args = process.argv.slice(2);
const STRICT = args.includes("--strict");
const targets = args.filter(a => !a.startsWith("--"));
if (!targets.length) {
console.error("用法:node tools/check-chapter.js <章节页或模块目录> [--strict]");
process.exit(2);
}
const ALLOWED_BOX = new Set(["", "note", "tip", "warn", "danger", "ok", "case", "lab", "pit"]);
const TAG_PAIRS = ["div", "section", "article", "aside", "nav", "main", "details", "table",
"ul", "ol", "li", "thead", "tbody", "tr", "td", "th", "pre", "p", "span"];
const problems = [];
const notes = [];
function walkHtml(dir, out = []) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) { if (e.name !== "assets" && e.name !== "tools") walkHtml(p, out); }
else if (e.name.endsWith(".html")) out.push(p);
}
return out;
}
/* 站内 id 索引:用于校验锚点是否真实存在 */
const idIndex = new Map();
for (const p of walkHtml(root)) {
const html = fs.readFileSync(p, "utf8");
const ids = new Set([...html.matchAll(/\sid="([^"]+)"/g)].map(m => m[1]));
if (path.resolve(p) === path.resolve(root, "index.html")) {
[...html.matchAll(/^\s*id:"([^"]+)"/gm)].forEach(m => ids.add(m[1]));
}
idIndex.set(path.resolve(p), ids);
}
/* 展开待检查文件 */
const files = [];
for (const t of targets) {
const p = path.resolve(root, t);
if (!fs.existsSync(p)) { console.error(`路径不存在:${t}`); process.exit(2); }
if (fs.statSync(p).isDirectory()) {
const f = fs.readdirSync(p).filter(x => /^\d\d-.*\.html$/.test(x)).sort();
if (!f.length) { console.error(`${t} 下没有 NN-*.html`); process.exit(2); }
f.forEach(x => files.push(path.join(p, x)));
} else files.push(p);
}
for (const p of files) {
const rel = path.relative(root, p).replace(/\\/g, "/");
const html = fs.readFileSync(p, "utf8");
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
const must = (c, m) => { if (!c) problems.push(`${rel}: ${m}`); };
if (!/^modules\/[^/]+\/\d\d-/.test(rel)) {
notes.push(`${rel}:不是章节页,只做结构检查`);
} else {
const chapNo = parseInt(path.basename(rel).slice(0, 2), 10);
const modPath = path.dirname(p);
const modFiles = fs.readdirSync(modPath).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
must(html.includes("<article>"), "缺少 article");
must(html.includes('id="chapters"'), "缺少章节目录侧栏 #chapters");
must(/<h2 id="/.test(html), "缺少 h2 章节标题");
must(html.includes('class="chapnav"'), "缺少章节目录定位条 chapnav");
must(html.includes('class="pager"'), "缺少上一/下一章 pager");
must(html.includes('href="index.html"'), "缺少返回模块目录链接");
must(html.includes('href="../../assets/doc.css"'), "doc.css 路径不对");
must(html.includes('src="../../assets/doc.js"'), "doc.js 路径不对");
must(/assets\/back\.js/.test(html), "缺少返回资料库入口 back.js");
// chapnav:章号 / 总章数 / 小节数
const navPos = html.match(/第 <b class="pos">(\d+)<\/b> \/ (\d+) 章/);
if (!navPos) problems.push(`${rel}: chapnav 缺少「第 N / M 章」`);
else {
if (Number(navPos[1]) !== chapNo) problems.push(`${rel}: chapnav 章号 ${navPos[1]} ≠ 文件名 ${chapNo}`);
if (Number(navPos[2]) !== modFiles.length) problems.push(`${rel}: chapnav 总章数 ${navPos[2]} ≠ 目录实际 ${modFiles.length} 章`);
}
const h3all = html.match(/<h3[ >]/g) || [];
const h3withId = html.match(/<h3 id="/g) || [];
must(h3withId.length === h3all.length, `有 h3 未补 id(${h3withId.length}/${h3all.length})`);
const navSecs = html.match(/本章 (\d+) 小节/);
if (h3all.length && !navSecs) problems.push(`${rel}: 有 ${h3all.length} 个小节但 chapnav 未写「本章 N 小节」`);
if (navSecs && Number(navSecs[1]) !== h3all.length) problems.push(`${rel}: chapnav 小节数 ${navSecs[1]} ≠ 实际 ${h3all.length}`);
// h3 编号与 id
for (const h of html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)) {
if (!/^sec-(x)?\d/.test(h[1]) && !/^sec-\d+-\d+$/.test(h[1])) problems.push(`${rel}: h3 id 命名不规范 ${h[1]}`);
const label = h[2].replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
if (!new RegExp(`^${chapNo}\\.\\d+`).test(label)) {
problems.push(`${rel}: h3「${label.slice(0, 30)}」编号与章号不一致(应为 ${chapNo}.x)`);
}
}
// 当前章在目录树里必须是 active(非空目录树时)
const nav = html.match(/<nav id="chapters">([\s\S]*?)<\/nav>/);
if (!nav) problems.push(`${rel}: 缺少 #chapters 目录树`);
else if (nav[1].trim()) {
must(/class="toc-a active"[^>]*aria-current="page"/.test(html), "当前章未在目录树标 active");
const cur = nav[1].match(/<div class="subnav current">([\s\S]*?)<\/div>/);
const curSecs = cur ? (cur[1].match(/class="toc-a lv3"/g) || []).length : 0;
if (STRICT && curSecs !== h3all.length) problems.push(`${rel}: 本章目录树小节 ${curSecs} ≠ 正文 ${h3all.length}(需要重跑 build-nav.js)`);
const rows = (nav[1].match(/class="toc-a( active)?"/g) || []).length;
must(rows === modFiles.length, `目录树章节数 ${rows} ≠ 目录实际 ${modFiles.length}`);
for (const f of modFiles) {
if (f === path.basename(p)) continue;
must(nav[1].includes(`href="${f}"`), `目录树缺少章节 ${f}`);
}
} else {
notes.push(`${rel}:目录树为空,跑 build-nav.js 后会自动填充`);
}
}
must(/<title>[^<]+<\/title>/.test(html), "缺少 title");
must(!/<style[\s>]/.test(markup), "不应出现 <style> 标签");
const inline = (markup.match(/\sstyle="/g) || []).length;
must(!inline, `有 ${inline} 处内联 style`);
// 代码块
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
pres.forEach((blk, i) => {
if (!/data-lang=/.test(blk)) problems.push(`${rel}: 第 ${i + 1} 个 <pre> 未标注 data-lang`);
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
if (/</.test(body)) problems.push(`${rel}: 第 ${i + 1} 个 <pre> 内有未转义的 <`);
});
// 提示框 / 表格
for (const m of markup.matchAll(/<div class="box([^"]*)"/g)) {
for (const cls of m[1].trim().split(/\s+/).filter(Boolean)) {
if (!ALLOWED_BOX.has(cls)) problems.push(`${rel}: 提示框用了不在规范内的类 box.${cls}`);
}
}
const tables = (markup.match(/<table[\s>]/g) || []).length;
const wrapped = (markup.match(/class="tablewrap"/g) || []).length;
must(tables === wrapped, `表格 ${tables} 个,tablewrap 包裹 ${wrapped} 个`);
// 标签配对
for (const t of TAG_PAIRS) {
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
if (o !== c) problems.push(`${rel}: <${t}> 开合不匹配 ${o}/${c}`);
}
// 残留占位
if (/<!--\s*(MORE|TODO|PART\d|占位)/i.test(html)) problems.push(`${rel}: 有未完成的占位注释`);
// 链接与锚点
const links = [...markup.matchAll(/href="(?!https?:|mailto:)([^"]+)"/g)].map(m => m[1]);
for (const l of new Set(links)) {
const [file, hash] = l.split("#");
const target = file ? path.resolve(path.dirname(p), file) : path.resolve(p);
if (file && !fs.existsSync(target)) { problems.push(`${rel}: 死链 ${l}`); continue; }
if (hash && idIndex.has(target) && !idIndex.get(target).has(hash)) {
problems.push(`${rel}: 锚点不存在 ${l}`);
}
}
const cn = (markup.replace(/<pre[\s\S]*?<\/pre>/g, "").match(/[\u4e00-\u9fff]/g) || []).length;
notes.push(`${rel}:正文汉字约 ${cn},代码块 ${pres.length},表格 ${tables}`);
}
notes.forEach(n => console.log("· " + n));
if (problems.length) {
console.error(`\n发现 ${problems.length} 个问题:`);
problems.forEach(x => console.error(" - " + x));
process.exit(1);
}
console.log(`\nOK:${files.length} 个页面检查通过`);