Debian Codegraph @

tests/unit_tests/test_publish_artifacts.py

raw
1 """The files this repo publishes to harlequin.sh, and the manifest that dates them.
2
3 Three artifacts are generated here and read there, and nothing at run time
4 reads any of them, so the only thing that notices a broken publish is a reader
5 on the site. What can go wrong is narrow and worth pinning: an artifact that
6 stops being copied, a skill published without the references it points at, a
7 manifest that names a version nobody can install, and a byte changed on the way
8 through.
9
10 The workflow that carries them is checked here too -- by name, because a script
11 renamed out from under it fails at release time, once a year, in the other repo.
12 """
13
14 from __future__ import annotations
15
16 import hashlib
17 import importlib.util
18 import json
19 from importlib.metadata import version
20 from pathlib import Path
21 from types import ModuleType
22 from typing import Any
23
24 import pytest
25 from jsonschema import Draft202012Validator
26
27 from harlequin.config_schema import SCHEMA_ID
28 from harlequin.hsql.modes import skill as skill_mode
29
30 REPO_ROOT = Path(__file__).resolve().parents[2]
31 SCRIPT_NAME = "scripts/publish_artifacts.py"
32 SCRIPT_PATH = REPO_ROOT / "scripts" / "publish_artifacts.py"
33 WORKFLOW_PATH = REPO_ROOT / ".github" / "workflows" / "publish-artifacts.yml"
34 PUBLISH_WORKFLOW_PATH = REPO_ROOT / ".github" / "workflows" / "publish.yml"
35
36
37 @pytest.fixture(scope="module")
38 def publisher() -> ModuleType:
39 """The script, loaded from `scripts/`, which is not an importable package."""
40 spec = importlib.util.spec_from_file_location("publish_artifacts", SCRIPT_PATH)
41 assert spec is not None and spec.loader is not None
42 module = importlib.util.module_from_spec(spec)
43 spec.loader.exec_module(module)
44 return module
45
46
47 @pytest.fixture(scope="module")
48 def staged(publisher: ModuleType, tmp_path_factory: pytest.TempPathFactory) -> Path:
49 directory = tmp_path_factory.mktemp("artifacts")
50 publisher.stage(directory)
51 return directory
52
53
54 @pytest.fixture(scope="module")
55 def manifest(staged: Path) -> dict[str, Any]:
56 data: dict[str, Any] = json.loads(
57 (staged / "manifest.json").read_text(encoding="utf-8")
58 )
59 return data
60
61
62 def _relative_paths(directory: Path) -> set[str]:
63 return {
64 path.relative_to(directory).as_posix()
65 for path in directory.rglob("*")
66 if path.is_file()
67 }
68
69
70 # --- what gets published -----------------------------------------------------
71
72
73 def test_the_three_artifacts_and_the_manifest_are_what_ships(staged: Path) -> None:
74 """Named here rather than derived, so dropping one is a failing test and
75 not a page that silently stops updating."""
76 references = {f"references/{path.name}" for path in skill_mode.reference_paths()}
77 assert (
78 _relative_paths(staged)
79 == {
80 "config-v1.json",
81 "hsql-reference.md",
82 "SKILL.md",
83 "manifest.json",
84 }
85 | references
86 )
87
88
89 def test_every_artifact_is_the_committed_file_byte_for_byte(
90 publisher: ModuleType, staged: Path
91 ) -> None:
92 """It publishes what the wheel ships. A line ending changed on the way
93 through is a diff on every release and a file that is in no release."""
94 for artifact in publisher.artifacts():
95 assert (staged / artifact.name).read_bytes() == artifact.source.read_bytes()
96
97
98 def test_the_skill_is_published_with_the_references_it_points_at(
99 staged: Path,
100 ) -> None:
101 """A `SKILL.md` whose pointers dangle is worse than one that never had
102 them: the agent reading it cannot tell a missing reference from one that
103 does not exist. So a new reference file is published by adding it."""
104 assert (staged / skill_mode.FILENAME).read_bytes() == skill_mode.text()
105 published = skill_mode.reference_paths()
106 assert published
107 for reference in published:
108 assert (staged / "references" / reference.name).read_bytes() == (
109 reference.read_bytes()
110 )
111
112
113 def test_the_published_schema_is_the_one_that_names_the_site(staged: Path) -> None:
114 """The whole reason this pipeline exists: `$id` has pointed at a URL on the
115 site since 2.10, and this is the file that has to be at it."""
116 schema = json.loads((staged / "config-v1.json").read_text(encoding="utf-8"))
117 Draft202012Validator.check_schema(schema)
118 assert schema["$id"] == SCHEMA_ID
119 assert SCHEMA_ID.startswith("https://harlequin.sh/")
120
121
122 def test_a_missing_source_stops_the_publish(
123 publisher: ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
124 ) -> None:
125 """Half an upload is the one outcome worse than a stale page."""
126 missing = publisher.Artifact(REPO_ROOT / "docs" / "nope.md", "nope.md")
127 monkeypatch.setattr(publisher, "artifacts", lambda: [missing])
128 with pytest.raises(FileNotFoundError, match="docs/nope.md"):
129 publisher.stage(tmp_path)
130 assert not list(tmp_path.iterdir())
131
132
133 # --- the manifest ------------------------------------------------------------
134
135
136 def test_the_manifest_names_the_release_the_artifacts_came_from(
137 manifest: dict[str, Any],
138 ) -> None:
139 """It is what the site's reference page prints as its generated-from line,
140 so a reader can tell whether the page is behind the hsql they have."""
141 assert manifest["version"] == version("harlequin")
142
143
144 def test_the_manifest_describes_every_file_beside_it(
145 manifest: dict[str, Any], staged: Path
146 ) -> None:
147 described = {entry["path"] for entry in manifest["files"]}
148 assert described == _relative_paths(staged) - {"manifest.json"}
149 for entry in manifest["files"]:
150 content = (staged / entry["path"]).read_bytes()
151 assert entry["bytes"] == len(content)
152 assert entry["sha256"] == hashlib.sha256(content).hexdigest()
153 assert (REPO_ROOT / entry["source"]).is_file()
154
155
156 def test_publishing_twice_writes_the_same_bytes(
157 publisher: ModuleType, staged: Path, tmp_path: Path
158 ) -> None:
159 """No timestamp, no hostname, no ordering by directory: a re-run's PR is
160 empty when nothing changed, so a diff on the site is a real change."""
161 publisher.stage(tmp_path)
162 assert _relative_paths(tmp_path) == _relative_paths(staged)
163 for name in _relative_paths(tmp_path):
164 assert (tmp_path / name).read_bytes() == (staged / name).read_bytes()
165
166
167 # --- the workflow that carries them ------------------------------------------
168
169
170 def test_the_workflow_runs_this_script() -> None:
171 """Renaming the script is a release-time failure in another repo otherwise."""
172 assert SCRIPT_NAME in WORKFLOW_PATH.read_text(encoding="utf-8")
173
174
175 def test_the_generators_the_workflow_checks_are_the_ones_that_write_artifacts() -> None:
176 """It refuses to publish a committed artifact its generator disagrees with,
177 which only works while it names both generators."""
178 workflow = WORKFLOW_PATH.read_text(encoding="utf-8")
179 for generator in ("write_config_schema.py", "write_cli_reference.py"):
180 assert f"scripts/{generator}" in workflow
181
182
183 def test_a_release_publishes_the_artifacts() -> None:
184 """The manifest names a version, so it goes out when that version does."""
185 publish = PUBLISH_WORKFLOW_PATH.read_text(encoding="utf-8")
186 assert "./.github/workflows/publish-artifacts.yml" in publish