返回 last30days-skill
test_changelog_workflow.py
根目录 / tests / test_changelog_workflow.py
1 """Contract tests for towncrier + lockstep release preparation."""
2
3 from __future__ import annotations
4
5 import importlib.util
6 import json
7 import os
8 import re
9 import shlex
10 import subprocess
11 import tempfile
12 import unittest
13 from pathlib import Path
14
15 import yaml
16
17 ROOT = Path(__file__).resolve().parents[1]
18
19
20 def _assert_run_blocks_indented(text: str, *, label: str) -> None:
21 """Fail if a ``run: |`` block contains under-indented (esp. column-0) lines.
22
23 A prior bug treated indent <= run_indent as "end of block" and skipped the
24 assertion, so column-0 Python inside the scalar never failed the test.
25 """
26 in_run = False
27 run_indent = 0
28 for lineno, line in enumerate(text.splitlines(), 1):
29 match = re.match(r"^(\s*)run:\s*\|\s*$", line)
30 if match:
31 in_run = True
32 run_indent = len(match.group(1))
33 continue
34 if not in_run or not line.strip():
35 continue
36 indent = len(line) - len(line.lstrip(" "))
37 if indent > run_indent:
38 continue
39 # Valid block end: a YAML key or list item at/above the run: indent.
40 # Column-0 (or any non-key dedent) is the Actions parse failure.
41 looks_like_yaml = bool(
42 re.match(r"^\s*(- )?[A-Za-z_][\w-]*\s*:", line)
43 or re.match(r"^\s*-\s+\S", line)
44 )
45 if indent == 0 or not looks_like_yaml:
46 raise AssertionError(
47 f"{label}:{lineno} under-indented inside run: | "
48 f"(indent={indent}, run_indent={run_indent}): {line!r}"
49 )
50 in_run = False
51
52
53 def _tag_release_workflow_text() -> str:
54 return (ROOT / ".github" / "workflows" / "tag-release.yml").read_text(
55 encoding="utf-8"
56 )
57
58
59 def _tag_release_version_sed_expr(workflow_text: str) -> str:
60 """Extract the sed expression from tag-release.yml's VERSION pipeline."""
61 match = re.search(
62 r'printf \'%s\\n\' "\$\{HEAD_MSG\}" \| sed -n \'([^\']+)\' \| head -n1',
63 workflow_text,
64 )
65 if not match:
66 raise AssertionError(
67 "Could not find VERSION sed pipeline in tag-release.yml"
68 )
69 return match.group(1)
70
71
72 def _parse_release_version_from_message(message: str, sed_expr: str) -> str:
73 """Run the same sed pipeline tag-release.yml uses to extract VERSION."""
74 result = subprocess.run(
75 [
76 "bash",
77 "-c",
78 f"printf '%s\\n' \"${{HEAD_MSG}}\" | sed -n '{sed_expr}' | head -n1",
79 ],
80 capture_output=True,
81 text=True,
82 check=True,
83 env={**os.environ, "HEAD_MSG": message},
84 )
85 return result.stdout.strip()
86
87
88 def _load_prepare_release():
89 path = ROOT / ".github" / "scripts" / "prepare_release.py"
90 spec = importlib.util.spec_from_file_location("prepare_release", path)
91 assert spec and spec.loader
92 module = importlib.util.module_from_spec(spec)
93 spec.loader.exec_module(module)
94 return module
95
96
97 class TestChangelogWorkflow(unittest.TestCase):
98 def test_towncrier_config_present(self) -> None:
99 text = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
100 self.assertIn("[tool.towncrier]", text)
101 self.assertIn('directory = "changelog.d"', text)
102 self.assertIn('filename = "CHANGELOG.md"', text)
103 for fragment_type in (
104 "security",
105 "removed",
106 "deprecated",
107 "added",
108 "changed",
109 "fixed",
110 ):
111 self.assertIn(f'directory = "{fragment_type}"', text)
112
113 def test_changelog_has_towncrier_start_marker(self) -> None:
114 text = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8")
115 self.assertIn("<!-- towncrier release notes start -->", text)
116 self.assertNotIn("## [Unreleased]", text)
117
118 def test_changelog_d_readme_exists(self) -> None:
119 self.assertTrue((ROOT / "changelog.d" / "README.md").is_file())
120
121 def test_prepare_release_script_exists(self) -> None:
122 self.assertTrue((ROOT / ".github" / "scripts" / "prepare_release.py").is_file())
123
124 def test_release_workflows_exist(self) -> None:
125 workflows = ROOT / ".github" / "workflows"
126 for name in (
127 "prepare-release.yml",
128 "tag-release.yml",
129 "changelog-guard.yml",
130 ):
131 self.assertTrue((workflows / name).is_file(), msg=name)
132
133 def test_tag_release_workflow_yaml_parses(self) -> None:
134 """Bare ``chore(release):`` in an unquoted ``if:`` breaks Actions YAML.
135
136 GitHub then reports the run as failed with zero jobs on every push to
137 main. The expression must be double-quoted; prefer ``contains`` so
138 merge-commit messages still match.
139 """
140 text = _tag_release_workflow_text()
141 yaml.safe_load(text)
142 self.assertRegex(
143 text,
144 r'(?m)^\s+if:\s+"contains\(github\.event\.head_commit\.message, '
145 r"'chore\(release\): bump version to '\)\"\s*$",
146 )
147 # VERSION parse must scan the full message (merge commits put the
148 # chore line in the body, not on line 1).
149 self.assertNotIn("| head -n1 | sed -n", text)
150
151 def test_tag_release_workflow_version_extraction(self) -> None:
152 """VERSION sed must match direct and merge-commit message shapes."""
153 text = _tag_release_workflow_text()
154 sed_expr = _tag_release_version_sed_expr(text)
155 expected = "3.18.3"
156 direct = f"chore(release): bump version to {expected}"
157 merge = (
158 "Merge pull request #879 from mvanhorn/release/v3.18.3\n\n"
159 f"chore(release): bump version to {expected}"
160 )
161 for message in (direct, merge):
162 with self.subTest(message=message.splitlines()[0]):
163 self.assertEqual(
164 _parse_release_version_from_message(message, sed_expr),
165 expected,
166 )
167
168 def test_changelog_guard_run_blocks_stay_indented(self) -> None:
169 """Column-0 lines inside ``run: |`` break Actions YAML parsing."""
170 path = ROOT / ".github" / "workflows" / "changelog-guard.yml"
171 _assert_run_blocks_indented(
172 path.read_text(encoding="utf-8"),
173 label=str(path),
174 )
175
176 def test_changelog_guard_skips_dependabot_without_fragment(self) -> None:
177 """Dependabot PRs must not need skip-changelog or a fragment.
178
179 mcp/* is an engine path, so gomod bumps fail the fragment gate unless
180 the author is exempted. Label-only exemption is not enough: Dependabot
181 cannot reliably apply skip-changelog (custom labels replace defaults
182 and missing repo labels are dropped). SKIP_CHANGELOG=1 from the
183 Dependabot author check must precede the fragment gate and must not
184 be reset afterwards.
185 """
186 text = (ROOT / ".github" / "workflows" / "changelog-guard.yml").read_text(
187 encoding="utf-8"
188 )
189 self.assertIn("PR_AUTHOR: ${{ github.event.pull_request.user.login }}", text)
190 self.assertIn("dependabot[bot]", text)
191 dependabot_assign = re.search(
192 r'if \[ "\$\{PR_AUTHOR\}" = "dependabot\[bot\]" \]; then\n'
193 r"\s+SKIP_CHANGELOG=1",
194 text,
195 )
196 self.assertIsNotNone(
197 dependabot_assign,
198 "Dependabot must set SKIP_CHANGELOG=1 from PR_AUTHOR",
199 )
200 fragment_gate = (
201 'if [ "${touches_engine}" -eq 1 ] && [ "${has_fragment}" -eq 0 ]'
202 ' && [ "${SKIP_CHANGELOG}" -eq 0 ]; then'
203 )
204 gate_at = text.find(fragment_gate)
205 self.assertNotEqual(
206 gate_at,
207 -1,
208 "Fragment gate must still consult SKIP_CHANGELOG",
209 )
210 self.assertLess(
211 dependabot_assign.start(),
212 gate_at,
213 "Dependabot SKIP_CHANGELOG=1 must precede the fragment gate",
214 )
215 self.assertNotIn(
216 "SKIP_CHANGELOG=0",
217 text[dependabot_assign.end() :],
218 "SKIP_CHANGELOG must not be reset after the Dependabot assignment",
219 )
220
221 def test_run_block_indent_checker_rejects_column_zero(self) -> None:
222 malformed = (
223 "jobs:\n"
224 " guard:\n"
225 " steps:\n"
226 " - name: Enforce\n"
227 " run: |\n"
228 " set -euo pipefail\n"
229 "import json\n"
230 )
231 with self.assertRaises(AssertionError):
232 _assert_run_blocks_indented(malformed, label="synthetic")
233
234 def test_reference_only_changes_follow_the_runtime_fragment_gate(self) -> None:
235 workflow = yaml.safe_load((ROOT / ".github/workflows/changelog-guard.yml").read_text())
236 blocks = [
237 step["run"] for job in workflow["jobs"].values() for step in job["steps"]
238 if "has_fragment=0" in step.get("run", "")
239 ]
240 self.assertEqual(1, len(blocks))
241 gate = blocks[0][blocks[0].index("has_fragment=0"):]
242 references = (
243 "skills/last30days/references/setup-wizard.md",
244 "skills/last30days/references/comparison.md",
245 )
246 for reference in references:
247 cases = (
248 ([reference], "0", 1),
249 ([reference, "changelog.d/1230.changed.md"], "0", 0),
250 ([reference], "1", 0),
251 (["README.md"], "0", 0),
252 )
253 for changed, skip, expected in cases:
254 with self.subTest(changed=changed, skip=skip):
255 setup = "CHANGED=(" + " ".join(shlex.quote(path) for path in changed) + ")\n"
256 result = subprocess.run(
257 ["bash", "-euc", setup + gate], text=True, capture_output=True,
258 env={**os.environ, "SKIP_CHANGELOG": skip},
259 )
260 self.assertEqual(expected, result.returncode, result.stdout + result.stderr)
261 if expected:
262 self.assertIn("Engine/skill changes need a changelog.d fragment", result.stdout)
263 else:
264 self.assertIn("Changelog guard passed", result.stdout)
265
266 def test_read_manifest_version_helper(self) -> None:
267 script = ROOT / ".github" / "scripts" / "read_manifest_version.py"
268 self.assertTrue(script.is_file())
269 spec = importlib.util.spec_from_file_location("read_manifest_version", script)
270 assert spec and spec.loader
271 mod = importlib.util.module_from_spec(spec)
272 spec.loader.exec_module(mod)
273 self.assertEqual(
274 mod.version_from("pyproject.toml", 'version = "3.18.1"\n'),
275 "3.18.1",
276 )
277 self.assertEqual(
278 mod.version_from("skills/last30days/SKILL.md", 'version: "3.18.1"\n'),
279 "3.18.1",
280 )
281 self.assertEqual(
282 mod.version_from(
283 "uv.lock",
284 '[[package]]\nname = "last30days-skill"\nversion = "3.18.1"\n',
285 ),
286 "3.18.1",
287 )
288 self.assertEqual(
289 mod.version_from(
290 ".claude-plugin/plugin.json",
291 json.dumps({"version": "3.18.1"}),
292 ),
293 "3.18.1",
294 )
295 self.assertEqual(
296 mod.version_from(
297 ".claude-plugin/marketplace.json",
298 json.dumps({"plugins": [{"version": "3.18.1"}]}),
299 ),
300 "3.18.1",
301 )
302 self.assertEqual(
303 mod.version_from(
304 "mcp/manifest.json",
305 json.dumps({"manifest_version": "0.3", "version": "3.18.1"}),
306 ),
307 "3.18.1",
308 )
309 with self.assertRaises(SystemExit):
310 mod.version_from(".claude-plugin/plugin.json", "{not-json")
311
312 def test_pr_template_has_agent_and_relationship_sections(self) -> None:
313 text = (ROOT / ".github" / "PULL_REQUEST_TEMPLATE.md").read_text(
314 encoding="utf-8"
315 )
316 self.assertIn("## Agent disclosure", text)
317 self.assertIn("### Relationship to this change", text)
318 self.assertIn("changelog.d/", text)
319 self.assertIn("What does this PR do?", text)
320 self.assertTrue((ROOT / "CONTRIBUTING.md").is_file())
321
322 def test_next_version_bumps(self) -> None:
323 mod = _load_prepare_release()
324 self.assertEqual(mod.next_version("3.18.1", "patch"), "3.18.2")
325 self.assertEqual(mod.next_version("3.18.1", "minor"), "3.19.0")
326 self.assertEqual(mod.next_version("3.18.1", "major"), "4.0.0")
327
328 def test_main_refuses_equal_version_outside_dry_run(self) -> None:
329 mod = _load_prepare_release()
330 with tempfile.TemporaryDirectory() as tmp:
331 tmp_path = Path(tmp)
332 (tmp_path / "pyproject.toml").write_text(
333 '[project]\nname = "last30days-skill"\nversion = "3.18.1"\n',
334 encoding="utf-8",
335 )
336 mod.ROOT = tmp_path
337 mod.PYPROJECT = tmp_path / "pyproject.toml"
338 with self.assertRaises(SystemExit) as ctx:
339 mod.main(["--version", "3.18.1"])
340 self.assertIn("Refusing to re-release", str(ctx.exception))
341
342 def test_prepare_release_bumps_mcp_manifest(self) -> None:
343 mod = _load_prepare_release()
344 self.assertIn(ROOT / "mcp" / "manifest.json", mod.JSON_VERSION_FILES)
345
346 def test_changelog_guard_version_paths_match_release_bump_set(self) -> None:
347 """Every path prepare_release.py bumps must be guarded, and vice versa."""
348 mod = _load_prepare_release()
349 bump_set = {
350 str(path.relative_to(ROOT))
351 for path in (
352 mod.PYPROJECT,
353 mod.UV_LOCK,
354 mod.SKILL_MD,
355 *mod.JSON_VERSION_FILES,
356 *mod.MARKETPLACE_FILES,
357 )
358 }
359 text = (ROOT / ".github" / "workflows" / "changelog-guard.yml").read_text(
360 encoding="utf-8"
361 )
362 match = re.search(r"VERSION_PATHS=\(\n(.*?)\n\s*\)", text, re.DOTALL)
363 if not match:
364 raise AssertionError("VERSION_PATHS=( ... ) not found in changelog-guard.yml")
365 guarded = {line.strip() for line in match.group(1).splitlines() if line.strip()}
366 self.assertIn("mcp/manifest.json", guarded)
367 self.assertEqual(bump_set, guarded)
368
369 def test_prepare_release_workflow_stages_every_bumped_file(self) -> None:
370 """A file prepare_release.py rewrites but the workflow never stages is
371 silently dropped from the release commit, so the bump is lost and any
372 test waiting on the new value keeps skipping."""
373 mod = _load_prepare_release()
374 bump_set = {
375 str(path.relative_to(ROOT))
376 for path in (
377 mod.PYPROJECT,
378 mod.UV_LOCK,
379 mod.SKILL_MD,
380 *mod.JSON_VERSION_FILES,
381 *mod.MARKETPLACE_FILES,
382 )
383 }
384 text = (ROOT / ".github" / "workflows" / "prepare-release.yml").read_text(
385 encoding="utf-8"
386 )
387 match = re.search(r"\n\s*git add \\\n(.*?)\n\s*git status", text, re.DOTALL)
388 if not match:
389 raise AssertionError("git add ... block not found in prepare-release.yml")
390 staged = {
391 line.strip().rstrip("\\").strip()
392 for line in match.group(1).splitlines()
393 if line.strip()
394 }
395 self.assertIn("mcp/manifest.json", staged)
396 self.assertEqual(set(), bump_set - staged)
397
398 def test_bump_all_updates_lockstep_surfaces(self) -> None:
399 mod = _load_prepare_release()
400 with tempfile.TemporaryDirectory() as tmp:
401 tmp_path = Path(tmp)
402 # Minimal fixtures mirroring the lockstep layout.
403 (tmp_path / "skills" / "last30days").mkdir(parents=True)
404 (tmp_path / ".claude-plugin").mkdir()
405 (tmp_path / ".codex-plugin").mkdir()
406 (tmp_path / ".grok-plugin").mkdir()
407 (tmp_path / "mcp").mkdir()
408
409 (tmp_path / "pyproject.toml").write_text(
410 '[project]\nname = "last30days-skill"\nversion = "3.18.1"\n',
411 encoding="utf-8",
412 )
413 (tmp_path / "skills" / "last30days" / "SKILL.md").write_text(
414 '---\nversion: "3.18.1"\n---\n\n# last30days v3.18.1: Title\n',
415 encoding="utf-8",
416 )
417 for rel in (
418 ".claude-plugin/plugin.json",
419 ".codex-plugin/plugin.json",
420 ".grok-plugin/plugin.json",
421 "gemini-extension.json",
422 "mcp/manifest.json",
423 ):
424 (tmp_path / rel).write_text(
425 json.dumps({"name": "last30days", "version": "3.18.1"}, indent=2)
426 + "\n",
427 encoding="utf-8",
428 )
429 for rel in (
430 ".claude-plugin/marketplace.json",
431 ".grok-plugin/marketplace.json",
432 ):
433 (tmp_path / rel).write_text(
434 json.dumps(
435 {
436 "name": "last30days-skill",
437 "plugins": [{"name": "last30days", "version": "3.18.1"}],
438 },
439 indent=2,
440 )
441 + "\n",
442 encoding="utf-8",
443 )
444 (tmp_path / "uv.lock").write_text(
445 'version = 1\n\n[[package]]\nname = "last30days-skill"\n'
446 'version = "3.18.1"\nsource = { virtual = "." }\n',
447 encoding="utf-8",
448 )
449
450 # Point module paths at the temp tree.
451 mod.ROOT = tmp_path
452 mod.SKILL_MD = tmp_path / "skills" / "last30days" / "SKILL.md"
453 mod.PYPROJECT = tmp_path / "pyproject.toml"
454 mod.UV_LOCK = tmp_path / "uv.lock"
455 mod.JSON_VERSION_FILES = (
456 tmp_path / ".claude-plugin" / "plugin.json",
457 tmp_path / ".codex-plugin" / "plugin.json",
458 tmp_path / ".grok-plugin" / "plugin.json",
459 tmp_path / "gemini-extension.json",
460 tmp_path / "mcp" / "manifest.json",
461 )
462 mod.MARKETPLACE_FILES = (
463 tmp_path / ".claude-plugin" / "marketplace.json",
464 tmp_path / ".grok-plugin" / "marketplace.json",
465 )
466
467 touched = mod.bump_all("9.9.9")
468 self.assertEqual(len(touched), 10)
469
470 pyproject = (tmp_path / "pyproject.toml").read_text(encoding="utf-8")
471 self.assertIn('version = "9.9.9"', pyproject)
472
473 skill = (tmp_path / "skills" / "last30days" / "SKILL.md").read_text(
474 encoding="utf-8"
475 )
476 self.assertIn('version: "9.9.9"', skill)
477 self.assertIn("# last30days v9.9.9:", skill)
478
479 for rel in (
480 ".claude-plugin/plugin.json",
481 ".codex-plugin/plugin.json",
482 ".grok-plugin/plugin.json",
483 "gemini-extension.json",
484 "mcp/manifest.json",
485 ):
486 data = json.loads((tmp_path / rel).read_text(encoding="utf-8"))
487 self.assertEqual(data["version"], "9.9.9", msg=rel)
488
489 for rel in (
490 ".claude-plugin/marketplace.json",
491 ".grok-plugin/marketplace.json",
492 ):
493 data = json.loads((tmp_path / rel).read_text(encoding="utf-8"))
494 self.assertEqual(data["plugins"][0]["version"], "9.9.9", msg=rel)
495
496 uv_lock = (tmp_path / "uv.lock").read_text(encoding="utf-8")
497 self.assertRegex(
498 uv_lock,
499 re.compile(
500 r'(?ms)^\[\[package\]\]\nname = "last30days-skill"\nversion = "9\.9\.9"',
501 ),
502 )
503
504
505 if __name__ == "__main__":
506 unittest.main()
507
507 lines PYTHON