dsh-project-dept 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,620 @@
1
+ # -*- coding: utf-8 -*-
2
+ """tests/test_check_skill.py — scripts/check_skill.py 的单元测试(标准库 only)。
3
+
4
+ 覆盖 8 项检查的关键判据与 CLI 契约(exit 0/1/2)。除最后一条 smoke 外,全部用
5
+ tempfile.mkdtemp() 造夹具,不依赖真实包路径。
6
+
7
+ 运行:
8
+ python -m unittest tests.test_check_skill -v
9
+ python -m unittest discover -s tests
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import unittest
20
+ from pathlib import Path
21
+
22
+ PKG_ROOT = Path(__file__).resolve().parents[1]
23
+ CHECK_SKILL = PKG_ROOT / "scripts" / "check_skill.py"
24
+
25
+
26
+ # ---------------------------------------------------------------- CLI 辅助
27
+
28
+
29
+ def run_cli(*args):
30
+ """以子进程方式跑 check_skill.py,强制 UTF-8 输出。"""
31
+ env = dict(os.environ)
32
+ env["PYTHONIOENCODING"] = "utf-8"
33
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
34
+ return subprocess.run(
35
+ [sys.executable, str(CHECK_SKILL), *map(str, args)],
36
+ capture_output=True,
37
+ text=True,
38
+ encoding="utf-8",
39
+ errors="replace",
40
+ env=env,
41
+ cwd=str(PKG_ROOT),
42
+ )
43
+
44
+
45
+ def write_text(path: Path, text: str) -> None:
46
+ path.parent.mkdir(parents=True, exist_ok=True)
47
+ path.write_text(text, encoding="utf-8")
48
+
49
+
50
+ # ---------------------------------------------------------------- 夹具
51
+
52
+
53
+ SKILL_MD = """---
54
+ name: {name}
55
+ description: 测试夹具:一个最小合法 skill 包,用来验证静态自检器的通过路径。
56
+ metadata:
57
+ version: {version}
58
+ tags: [test]
59
+ ---
60
+
61
+ # {name}
62
+
63
+ 最小夹具正文。
64
+
65
+ ## 加载
66
+
67
+ - 先读 `static/core/principles.md`
68
+ - 需要时读 `references/ref.md`
69
+ """
70
+
71
+ MANIFEST = """name: {name}
72
+ version: {version}
73
+ description: >
74
+ test fixture
75
+
76
+ always_load:
77
+ - static/core/principles.md
78
+
79
+ references:
80
+ on_demand:
81
+ - condition: test only
82
+ path: references/ref.md
83
+
84
+ quality_tools:
85
+ gate_script: scripts/dept_gate.py
86
+ audit_script: scripts/check_doc.py
87
+ """
88
+
89
+ README = "# {name}\n\n当前版本 {version}。\n"
90
+ README_EN = "# {name}\n\nCurrent version: {version}\n"
91
+
92
+
93
+ def make_pkg(base: Path, dirname: str = "project-dept", version: str = "1.0.0",
94
+ skill_name=None) -> Path:
95
+ """在 base 下造一个最小合法包,返回包目录。"""
96
+ name = skill_name or dirname
97
+ root = base / dirname
98
+ write_text(root / "SKILL.md", SKILL_MD.format(name=name, version=version))
99
+ write_text(root / "manifest.yaml", MANIFEST.format(name=name, version=version))
100
+ write_text(root / "README.md", README.format(name=name, version=version))
101
+ write_text(root / "README_EN.md", README_EN.format(name=name, version=version))
102
+ write_text(root / "static" / "core" / "principles.md", "# principles\n\n夹具内容。\n")
103
+ write_text(root / "references" / "ref.md", "# ref\n\n夹具内容。\n")
104
+ write_text(root / "scripts" / "dept_gate.py", "# placeholder\n")
105
+ write_text(root / "scripts" / "check_doc.py", "# placeholder\n")
106
+ (root / "tests").mkdir(parents=True, exist_ok=True)
107
+ write_text(
108
+ root / "evals" / "evals.json",
109
+ json.dumps(
110
+ {
111
+ "skill_name": name,
112
+ "evals": [
113
+ {"id": "case-1", "prompt": "问题一", "expected_output": "答案一"},
114
+ {"id": "case-2", "prompt": "问题二", "expected_output": "答案二"},
115
+ ],
116
+ },
117
+ ensure_ascii=False,
118
+ ),
119
+ )
120
+ return root
121
+
122
+
123
+ # ---------------------------------------------------------------- 测试类
124
+
125
+
126
+ class CheckSkillCliTests(unittest.TestCase):
127
+ def setUp(self):
128
+ self.tmp = Path(tempfile.mkdtemp(prefix="check_skill_"))
129
+ self.addCleanup(shutil.rmtree, str(self.tmp), True)
130
+
131
+ # -- 通用断言
132
+
133
+ def assertExit(self, proc, expected):
134
+ self.assertEqual(
135
+ proc.returncode,
136
+ expected,
137
+ msg="stdout:\n%s\nstderr:\n%s" % (proc.stdout, proc.stderr),
138
+ )
139
+
140
+ @staticmethod
141
+ def nonempty_lines(proc):
142
+ return [line for line in proc.stdout.splitlines() if line.strip()]
143
+
144
+ # -- 1. 最小合法包
145
+
146
+ def test_minimal_valid_package_passes(self):
147
+ pkg = make_pkg(self.tmp)
148
+ proc = run_cli("--root", pkg)
149
+ self.assertExit(proc, 0)
150
+ lines = self.nonempty_lines(proc)
151
+ self.assertTrue(lines[0].startswith("SKILL CHECK · "), lines[0])
152
+ self.assertEqual(lines[-1], "结论:通过(exit 0)")
153
+ self.assertNotIn("[x]", proc.stdout)
154
+ self.assertEqual(proc.stderr.strip(), "")
155
+
156
+ # -- 2. name 与目录名不符
157
+
158
+ def test_name_mismatch_detected(self):
159
+ pkg = make_pkg(self.tmp, skill_name="other-dept")
160
+ proc = run_cli("--root", pkg)
161
+ self.assertExit(proc, 1)
162
+ self.assertIn("name", proc.stdout)
163
+ self.assertIn("不符", proc.stdout)
164
+ self.assertEqual(self.nonempty_lines(proc)[-1], "结论:有缺陷(exit 1)")
165
+
166
+ # -- 2b. name 与目录名不符,但显式放开(盲审副本场景)
167
+
168
+ def test_name_mismatch_downgraded_with_flag(self):
169
+ pkg = make_pkg(self.tmp, skill_name="other-dept")
170
+ proc = run_cli("--root", pkg, "--allow-dirname-mismatch")
171
+ self.assertExit(proc, 0)
172
+ self.assertIn("不符", proc.stdout)
173
+ self.assertIn("[!]", proc.stdout)
174
+ self.assertEqual(self.nonempty_lines(proc)[-1], "结论:通过(exit 0)")
175
+
176
+ # -- 3. 版本漂移
177
+
178
+ def test_version_drift_detected(self):
179
+ pkg = make_pkg(self.tmp, version="1.0.14")
180
+ write_text(pkg / "README.md", "# project-dept\n\n当前版本 1.0.13。\n")
181
+ proc = run_cli("--root", pkg)
182
+ self.assertExit(proc, 1)
183
+ self.assertIn("1.0.13", proc.stdout)
184
+ self.assertIn("1.0.14", proc.stdout)
185
+ self.assertIn("版本不一致", proc.stdout)
186
+
187
+ # -- 4. SKILL.md 引用不存在的资产
188
+
189
+ def test_missing_referenced_asset_detected(self):
190
+ pkg = make_pkg(self.tmp)
191
+ skill = pkg / "SKILL.md"
192
+ skill.write_text(
193
+ skill.read_text(encoding="utf-8") + "\n\n详见 `references/nope.md`。\n",
194
+ encoding="utf-8",
195
+ )
196
+ proc = run_cli("--root", pkg)
197
+ self.assertExit(proc, 1)
198
+ self.assertIn("references/nope.md", proc.stdout)
199
+ self.assertIn("SKILL.md:", proc.stdout)
200
+
201
+ # -- 4b. manifest 声明的资产缺失(抓死引用)
202
+
203
+ def test_missing_manifest_asset_detected(self):
204
+ pkg = make_pkg(self.tmp)
205
+ (pkg / "references" / "ref.md").unlink()
206
+ proc = run_cli("--root", pkg)
207
+ self.assertExit(proc, 1)
208
+ self.assertIn("manifest.yaml:", proc.stdout)
209
+ self.assertIn("references/ref.md", proc.stdout)
210
+
211
+ # -- 5. 禁出现文件名
212
+
213
+ def test_forbidden_filename_detected(self):
214
+ pkg = make_pkg(self.tmp)
215
+ skill = pkg / "SKILL.md"
216
+ skill.write_text(
217
+ skill.read_text(encoding="utf-8") + "\n\n回归见 VERIFICATION.md。\n",
218
+ encoding="utf-8",
219
+ )
220
+ proc = run_cli("--root", pkg)
221
+ self.assertExit(proc, 1)
222
+ self.assertIn("VERIFICATION.md", proc.stdout)
223
+ self.assertIn("[x]", proc.stdout)
224
+
225
+ # -- 6. evals.json 坏 JSON
226
+
227
+ def test_broken_evals_json_detected(self):
228
+ pkg = make_pkg(self.tmp)
229
+ write_text(pkg / "evals" / "evals.json", "{ this is not json")
230
+ proc = run_cli("--root", pkg)
231
+ self.assertExit(proc, 1)
232
+ self.assertIn("evals", proc.stdout)
233
+ self.assertIn("JSON", proc.stdout)
234
+
235
+ # -- 6b. evals 字段缺失 / id 重复
236
+
237
+ def test_evals_missing_field_and_duplicate_id_detected(self):
238
+ pkg = make_pkg(self.tmp)
239
+ write_text(
240
+ pkg / "evals" / "evals.json",
241
+ json.dumps(
242
+ {
243
+ "evals": [
244
+ {"id": "dup", "prompt": "p1", "expected_output": "o1"},
245
+ {"id": "dup", "prompt": "p2", "expected_output": "o2"},
246
+ {"id": "case-3", "prompt": "p3"},
247
+ ]
248
+ },
249
+ ensure_ascii=False,
250
+ ),
251
+ )
252
+ proc = run_cli("--root", pkg)
253
+ self.assertExit(proc, 1)
254
+ self.assertIn("id 重复", proc.stdout)
255
+ self.assertIn("expected_output", proc.stdout)
256
+
257
+ # -- 7. 目录不存在 → exit 2
258
+
259
+ def test_missing_root_exits_two(self):
260
+ proc = run_cli("--root", self.tmp / "does-not-exist")
261
+ self.assertExit(proc, 2)
262
+ self.assertIn("无法执行", proc.stdout)
263
+ self.assertEqual(self.nonempty_lines(proc)[-1], "结论:未执行(exit 2)")
264
+
265
+ # -- 7b. SKILL.md 缺失 → exit 2
266
+
267
+ def test_missing_skill_md_exits_two(self):
268
+ pkg = make_pkg(self.tmp)
269
+ (pkg / "SKILL.md").unlink()
270
+ proc = run_cli("--root", pkg)
271
+ self.assertExit(proc, 2)
272
+ self.assertIn("SKILL.md", proc.stdout)
273
+ self.assertEqual(self.nonempty_lines(proc)[-1], "结论:未执行(exit 2)")
274
+
275
+ # -- 8. 入口正文超硬上限:exit 1(v1.2.0 起不是警告)
276
+
277
+ def test_skill_body_over_hard_limit_is_defect(self):
278
+ pkg = make_pkg(self.tmp)
279
+ skill = pkg / "SKILL.md"
280
+ skill.write_text(
281
+ skill.read_text(encoding="utf-8") + "\n" + ("超预算填充" * 1200) + "\n",
282
+ encoding="utf-8",
283
+ )
284
+ proc = run_cli("--root", pkg)
285
+ self.assertExit(proc, 1)
286
+ self.assertIn("硬上限 3000", proc.stdout)
287
+ self.assertEqual(self.nonempty_lines(proc)[-1], "结论:有缺陷(exit 1)")
288
+
289
+ proc_json = run_cli("--root", pkg, "--json")
290
+ self.assertExit(proc_json, 1)
291
+ data = json.loads(proc_json.stdout)
292
+ self.assertFalse(data["ok"])
293
+ self.assertEqual(data["budget"]["skill_md_limit"], 3000)
294
+ self.assertGreater(data["budget"]["skill_md_tokens"], 3000)
295
+
296
+ # -- 9. --json 契约
297
+
298
+ def test_json_output_is_machine_readable(self):
299
+ pkg = make_pkg(self.tmp)
300
+ proc = run_cli("--root", pkg, "--json")
301
+ self.assertExit(proc, 0)
302
+ data = json.loads(proc.stdout) # stdout 上必须只有 JSON
303
+ for key in ("ok", "defects", "warnings", "budget"):
304
+ self.assertIn(key, data)
305
+ self.assertTrue(data["ok"])
306
+ self.assertEqual(data["defects"], [])
307
+ self.assertIsInstance(data["warnings"], list)
308
+ self.assertIsInstance(data["budget"], dict)
309
+ self.assertGreater(data["budget"]["skill_md_tokens"], 0)
310
+ self.assertEqual(data["budget"]["skill_md_limit"], 3000)
311
+ self.assertEqual(data["budget"]["total_limit"], 9000)
312
+
313
+ broken = make_pkg(self.tmp, dirname="broken-pkg", skill_name="other")
314
+ proc_broken = run_cli("--root", broken, "--json")
315
+ self.assertExit(proc_broken, 1)
316
+ data_broken = json.loads(proc_broken.stdout)
317
+ self.assertFalse(data_broken["ok"])
318
+ self.assertTrue(data_broken["defects"])
319
+
320
+ # -- 10. 真实包 smoke(唯一依赖真实包的用例)
321
+
322
+ def test_real_package_smoke(self):
323
+ """真实包:CLI 必须能跑通,输出结构与退出码自洽。
324
+
325
+ 任务单原本要求「真实包 exit 0」。本检查器对真实包当前给出 1 条 [x]
326
+ (README.md 的变更记录里出现不随包分发的文件名 VERIFICATION.md,属既有缺陷,
327
+ 按任务单要求不修改现有文件、记入汇报由 Lead 决定)。因此这里断言「能跑通且
328
+ 自洽」;一旦该缺陷被 Lead 处置、真实包变干净,下面的分支自动升级为断言 exit 0。
329
+ """
330
+ proc = run_cli()
331
+ self.assertNotEqual(proc.returncode, 2, msg=proc.stdout + proc.stderr)
332
+ self.assertIn(proc.returncode, (0, 1), msg=proc.stdout + proc.stderr)
333
+
334
+ lines = self.nonempty_lines(proc)
335
+ self.assertTrue(lines[0].startswith("SKILL CHECK · "), lines[0])
336
+ expected_word = "通过" if proc.returncode == 0 else "有缺陷"
337
+ self.assertEqual(
338
+ lines[-1], "结论:%s(exit %d)" % (expected_word, proc.returncode)
339
+ )
340
+ if proc.returncode == 0:
341
+ self.assertNotIn("[x]", proc.stdout)
342
+ else:
343
+ self.assertIn("[x]", proc.stdout)
344
+
345
+ proc_json = run_cli("--json")
346
+ self.assertEqual(proc_json.returncode, proc.returncode)
347
+ data = json.loads(proc_json.stdout)
348
+ self.assertEqual(data["ok"], proc.returncode == 0)
349
+ self.assertIn("budget", data)
350
+ self.assertEqual(data["exit_code"], proc.returncode)
351
+
352
+
353
+ # ---------------------------------------------------------------- v1.2.1 回归
354
+ #
355
+ # 这四条对应 v1.2.1 修掉的四个"判据可被绕过 / 会腐化"的问题。
356
+ # 冻结纪律:把对应修复回退掉,这些用例必须失败(不是恒真)。
357
+
358
+
359
+ class TestV121Regression(unittest.TestCase):
360
+ def setUp(self):
361
+ self.tmp = Path(tempfile.mkdtemp(prefix="ck121_"))
362
+
363
+ def tearDown(self):
364
+ shutil.rmtree(self.tmp, ignore_errors=True)
365
+
366
+ def _add_tool(self, pkg: Path, rel: str, line: str) -> None:
367
+ mf = pkg / "manifest.yaml"
368
+ mf.write_text(mf.read_text(encoding="utf-8").rstrip("\n") + "\n" + line + "\n",
369
+ encoding="utf-8")
370
+ write_text(pkg / rel, "# placeholder\n")
371
+
372
+ def test_kana_padding_hits_hard_limit(self):
373
+ """假名曾按 3.5 字符/token 估算:4000 个假名 ≈1142 tokens,exit 0 放行。"""
374
+ pkg = make_pkg(self.tmp)
375
+ skill = pkg / "SKILL.md"
376
+ skill.write_text(skill.read_text(encoding="utf-8") + "\n" + ("あ" * 4000) + "\n",
377
+ encoding="utf-8")
378
+ proc = run_cli("--root", pkg)
379
+ self.assertEqual(proc.returncode, 1, msg=proc.stdout)
380
+ self.assertIn("硬上限 3000", proc.stdout)
381
+
382
+ def test_hangul_and_emoji_arms_of_the_same_check(self):
383
+ """谚文与 emoji 走同一段码位判定;各造一份恰好越线的填充。"""
384
+ for filler, label in ((("한" * 3200), "hangul"), (("🌸" * 3200), "emoji")):
385
+ pkg = make_pkg(self.tmp, dirname="p-" + label)
386
+ skill = pkg / "SKILL.md"
387
+ skill.write_text(skill.read_text(encoding="utf-8") + "\n" + filler + "\n",
388
+ encoding="utf-8")
389
+ proc = run_cli("--root", pkg)
390
+ self.assertEqual(proc.returncode, 1, msg="%s: %s" % (label, proc.stdout))
391
+ self.assertIn("硬上限 3000", proc.stdout)
392
+
393
+ def test_fragment_bloat_is_a_defect(self):
394
+ """轴片段以前完全不计入预算:往片段里灌 20,000 字仍然 exit 0。"""
395
+ pkg = make_pkg(self.tmp)
396
+ mf = pkg / "manifest.yaml"
397
+ mf.write_text(
398
+ mf.read_text(encoding="utf-8").rstrip("\n")
399
+ + "\n\naxes:\n deliverable:\n values:\n"
400
+ " document: static/fragments/deliverable/document.md\n",
401
+ encoding="utf-8",
402
+ )
403
+ write_text(pkg / "static" / "fragments" / "deliverable" / "document.md",
404
+ "# 文档交付\n\n" + ("填" * 20000) + "\n")
405
+ proc = run_cli("--root", pkg)
406
+ self.assertEqual(proc.returncode, 1, msg=proc.stdout)
407
+ self.assertIn("单次开工实际加载", proc.stdout)
408
+ self.assertIn("硬上限 14000", proc.stdout)
409
+
410
+ def test_extensionless_tool_declaration_missing_is_a_defect(self):
411
+ """`scripts/no_such_gate` 这种不带扩展名的声明以前整条逃检。"""
412
+ pkg = make_pkg(self.tmp)
413
+ mf = pkg / "manifest.yaml"
414
+ mf.write_text(
415
+ mf.read_text(encoding="utf-8").replace(
416
+ "gate_script: scripts/dept_gate.py",
417
+ "gate_script: scripts/no_such_gate",
418
+ ),
419
+ encoding="utf-8",
420
+ )
421
+ proc = run_cli("--root", pkg)
422
+ self.assertEqual(proc.returncode, 1, msg=proc.stdout)
423
+ self.assertIn("quality_tools", proc.stdout)
424
+ self.assertIn("找不到实体", proc.stdout)
425
+
426
+ def test_stale_tool_count_phrase_is_a_defect(self):
427
+ """实体 3 个脚本、文档里还写"只有俩" ⇒ 缺陷(计数已腐化)。"""
428
+ pkg = make_pkg(self.tmp)
429
+ self._add_tool(pkg, "scripts/run_evals.py", " eval_runner: scripts/run_evals.py")
430
+ readme = pkg / "README.md"
431
+ readme.write_text(
432
+ readme.read_text(encoding="utf-8") + "\n历史说明:两个脚本足以覆盖。\n",
433
+ encoding="utf-8",
434
+ )
435
+ proc = run_cli("--root", pkg)
436
+ self.assertEqual(proc.returncode, 1, msg=proc.stdout)
437
+ self.assertIn("计数已腐化", proc.stdout)
438
+ self.assertIn("README.md", proc.stdout)
439
+
440
+ def test_stale_phrase_in_non_entry_doc_is_a_defect(self):
441
+ """规则不能只在三份入口文档生效:references/ 里的旧措辞一样算缺陷(v1.2.2)。"""
442
+ pkg = make_pkg(self.tmp)
443
+ self._add_tool(pkg, "scripts/run_evals.py", " eval_runner: scripts/run_evals.py")
444
+ write_text(pkg / "references" / "scaffold.md",
445
+ "# scaffold\n\n## 6. Wire the two scripts\n")
446
+ proc = run_cli("--root", pkg)
447
+ self.assertEqual(proc.returncode, 1, msg=proc.stdout)
448
+ self.assertIn("references/scaffold.md", proc.stdout)
449
+ self.assertIn("计数已腐化", proc.stdout)
450
+
451
+ def test_two_tools_package_stays_clean(self):
452
+ """反面:实体就是 2 个时,旧措辞不该被误伤。"""
453
+ pkg = make_pkg(self.tmp)
454
+ readme = pkg / "README.md"
455
+ readme.write_text(
456
+ readme.read_text(encoding="utf-8") + "\n历史说明:两个脚本足以覆盖。\n",
457
+ encoding="utf-8",
458
+ )
459
+ proc = run_cli("--root", pkg)
460
+ self.assertEqual(proc.returncode, 0, msg=proc.stdout)
461
+
462
+
463
+ class TestV130ManifestSyntax(unittest.TestCase):
464
+ """v1.3.0:第 8 项「manifest 语法」。
465
+
466
+ 动机:manifest.yaml 曾两次被写成断行(plain scalar 的续行里带 "key: "),
467
+ 而 build_payload / 正则扫描都发现不了,一路带着坏 YAML 发版。这一族错误
468
+ 只能靠真的解析一遍才能抓住。
469
+ """
470
+
471
+ def setUp(self):
472
+ import tempfile as _tf
473
+ self.tmp = Path(_tf.mkdtemp(prefix="check_skill_v130yaml_"))
474
+
475
+ def tearDown(self):
476
+ shutil.rmtree(self.tmp, ignore_errors=True)
477
+
478
+ def assertExit(self, proc, expected):
479
+ self.assertEqual(
480
+ proc.returncode,
481
+ expected,
482
+ msg="exit=%d expected=%d\nstdout:\n%s\nstderr:\n%s"
483
+ % (proc.returncode, expected, proc.stdout, proc.stderr),
484
+ )
485
+
486
+ def _append_broken_continuation(self, pkg: Path) -> None:
487
+ mpath = pkg / "manifest.yaml"
488
+ text = mpath.read_text(encoding="utf-8")
489
+ text += "\n demo_note: this is a plain scalar\n Nested: continuation with a colon\n"
490
+ mpath.write_text(text, encoding="utf-8")
491
+
492
+ def test_broken_yaml_is_a_defect(self):
493
+ pkg = make_pkg(self.tmp)
494
+ self._append_broken_continuation(pkg)
495
+ proc = run_cli("--root", str(pkg))
496
+ self.assertExit(proc, 1)
497
+ out = proc.stdout + proc.stderr
498
+ self.assertIn("不是合法 YAML", out)
499
+ self.assertIn("manifest 语法", out)
500
+
501
+ def test_clean_package_passes_and_lists_eight_checks(self):
502
+ pkg = make_pkg(self.tmp)
503
+ proc = run_cli("--root", str(pkg))
504
+ self.assertExit(proc, 0)
505
+ out = proc.stdout + proc.stderr
506
+ self.assertIn("[8/8]", out)
507
+ self.assertIn("manifest 语法", out)
508
+
509
+ def test_heuristic_flags_plain_scalar_continuation(self):
510
+ import importlib.util as _ilu
511
+ script = Path(__file__).resolve().parent.parent / "scripts" / "check_skill.py"
512
+ spec = _ilu.spec_from_file_location("_check_skill_under_test", str(script))
513
+ mod = _ilu.module_from_spec(spec)
514
+ import sys as _sys
515
+ _sys.modules[spec.name] = mod # dataclasses 需要它先登记,否则 __module__ 查不到
516
+ spec.loader.exec_module(mod)
517
+
518
+ broken = "a:\n key: value one\n Nested: looks like a mapping\n"
519
+ self.assertTrue(mod._yaml_suspicion(broken))
520
+
521
+ legit = (
522
+ "list:\n"
523
+ " - condition: something\n"
524
+ " path: references/ref.md\n"
525
+ "struct:\n"
526
+ " child: value\n"
527
+ "folded: >-\n"
528
+ " first line\n"
529
+ " Key: this colon inside a block scalar is fine\n"
530
+ )
531
+ self.assertFalse(mod._yaml_suspicion(legit))
532
+
533
+
534
+ class TestV131DuplicateTopLevelKeys(unittest.TestCase):
535
+ """v1.3.1(c1 轻微项):重复顶层键必须报缺陷。
536
+
537
+ PyYAML 对重复键不报错、后者静默覆盖前者 —— 只看「解析成功」等于没查。
538
+ """
539
+
540
+ def setUp(self):
541
+ import tempfile as _tf
542
+ self.tmp = Path(_tf.mkdtemp(prefix="check_skill_v131dup_"))
543
+
544
+ def tearDown(self):
545
+ shutil.rmtree(self.tmp, ignore_errors=True)
546
+
547
+ def test_duplicate_top_level_key_is_a_defect(self):
548
+ pkg = make_pkg(self.tmp)
549
+ mpath = pkg / "manifest.yaml"
550
+ text = mpath.read_text(encoding="utf-8")
551
+ mpath.write_text(text + "\nversion: 9.9.9\n", encoding="utf-8")
552
+ proc = run_cli("--root", str(pkg))
553
+ self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr)
554
+ out = proc.stdout + proc.stderr
555
+ self.assertIn("出现多次", out)
556
+ self.assertIn("静默覆盖", out)
557
+ self.assertIn("version", out)
558
+
559
+
560
+ if __name__ == "__main__":
561
+ unittest.main(verbosity=2)
562
+
563
+
564
+ class TestV130Regression(unittest.TestCase):
565
+ """v1.3.0(P-15-5):读不出来的 .md 不许静默跳过。
566
+
567
+ 以前 read_text() 返回 None 时两处循环都 continue —— 一个 GBK 编码的
568
+ .md 就能让「陈旧措辞 / 禁名」这两条规则对它永不生效(复核人实测逃检)。
569
+ """
570
+
571
+ def setUp(self):
572
+ self.tmp = Path(tempfile.mkdtemp(prefix="check_skill_v130_"))
573
+
574
+ def tearDown(self):
575
+ shutil.rmtree(self.tmp, ignore_errors=True)
576
+
577
+ def assertExit(self, proc, expected):
578
+ self.assertEqual(
579
+ proc.returncode,
580
+ expected,
581
+ msg="exit=%d expected=%d\nstdout:\n%s\nstderr:\n%s"
582
+ % (proc.returncode, expected, proc.stdout, proc.stderr),
583
+ )
584
+
585
+ def _add_third_tool(self, pkg: Path) -> None:
586
+ mpath = pkg / "manifest.yaml"
587
+ text = mpath.read_text(encoding="utf-8")
588
+ assert "quality_tools:" in text
589
+ text = text.replace(
590
+ "quality_tools:", "quality_tools:\n skill_lint_script: scripts/check_skill.py"
591
+ )
592
+ mpath.write_text(text, encoding="utf-8")
593
+ write_text(pkg / "scripts" / "check_skill.py", "# placeholder\n")
594
+
595
+ def test_gbk_md_escaping_stale_scan_is_a_defect(self):
596
+ pkg = make_pkg(self.tmp)
597
+ self._add_third_tool(pkg) # 3 个脚本才会触发陈旧计数扫描
598
+ (pkg / "references" / "gbk.md").write_bytes("# 中文标题\n\n内容\n".encode("gbk"))
599
+ proc = run_cli("--root", str(pkg))
600
+ self.assertExit(proc, 1)
601
+ out = proc.stdout + proc.stderr
602
+ self.assertIn("不是 UTF-8", out)
603
+ self.assertIn("references/gbk.md", out)
604
+
605
+ def test_gbk_readme_is_a_defect(self):
606
+ pkg = make_pkg(self.tmp)
607
+ (pkg / "README.md").write_bytes("# 中文说明\n".encode("gbk"))
608
+ proc = run_cli("--root", str(pkg))
609
+ self.assertExit(proc, 1)
610
+ out = proc.stdout + proc.stderr
611
+ self.assertIn("不是 UTF-8", out)
612
+ self.assertIn("README.md", out)
613
+
614
+ def test_all_utf8_package_stays_clean(self):
615
+ pkg = make_pkg(self.tmp)
616
+ self._add_third_tool(pkg)
617
+ proc = run_cli("--root", str(pkg))
618
+ self.assertExit(proc, 0)
619
+ self.assertNotIn("不是 UTF-8", proc.stdout + proc.stderr)
620
+