gabriel / musehub public
test_release_version_identity.py python
222 lines 11.2 KB
Raw
sha256:772b8f0030c38b6a2bc565ade4de3ba0f78ff5f1dd1957cb968c708ec75881df test(version): isolate the release-version probe from the s… Opus 5.5 6 days ago
1 """VER-1 -- MuseHub's own version: ``pyproject.toml``'s ``[project].version`` is the only declaration, one resolver
2 (``musehub.protocol.version.resolve_version``) reads it, and every version-reporting surface reports that string.
3
4 Database-free. Policy: docs/versioning.md ("MuseHub versioning"). Deployment identity (image digest, source labels) and
5 the c-series release labels are other things and are not asserted here; the Muse CLI version is independent. The SemVer
6 release tag is derived by deploy/pep440_to_semver_tag.py (tests/test_pep440_to_semver_tag.py).
7 """
8 from __future__ import annotations
9
10 import asyncio
11 import json
12 import logging
13 import re
14 import shutil
15 import subprocess
16 import sys
17 import tomllib
18 from pathlib import Path
19
20 import packaging
21 import pytest
22 from packaging.version import Version
23
24 from musehub.protocol import version as version_module
25 from musehub.protocol.version import MUSE_VERSION, UNKNOWN_VERSION, resolve_version
26
27 ROOT = Path(__file__).resolve().parents[1]
28 PYPROJECT_VERSION = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"]
29 _VERSION_PY = ROOT / "musehub" / "protocol" / "version.py"
30
31
32 def _pyproject(tmp_path: Path, *, name: str = "musehub", version: str | None = "1.2.3rc4", raw: str | None = None) -> Path:
33 path = tmp_path / "pyproject.toml"
34 path.write_text(raw if raw is not None else f'[project]\nname = "{name}"\n' + (f'version = "{version}"\n' if version else ""))
35 return path
36
37
38 class TestOneCanonicalSource:
39 def test_pyproject_holds_the_canonical_pep440_spelling(self) -> None:
40 assert str(Version(PYPROJECT_VERSION)) == PYPROJECT_VERSION
41
42 def test_reported_version_is_the_pyproject_version(self) -> None:
43 assert MUSE_VERSION == PYPROJECT_VERSION != UNKNOWN_VERSION
44
45 def test_a_source_checkout_never_reaches_the_fallback(self, caplog: pytest.LogCaptureFixture) -> None:
46 with caplog.at_level(logging.WARNING, logger=version_module.logger.name):
47 assert resolve_version() == PYPROJECT_VERSION
48 assert caplog.records == []
49
50 def test_the_fallback_is_a_valid_pep440_version_that_is_never_a_release(self) -> None:
51 assert str(Version(UNKNOWN_VERSION)) == UNKNOWN_VERSION
52 assert Version(UNKNOWN_VERSION).local == "unknown" and Version(UNKNOWN_VERSION) < Version("0.0.1")
53
54
55 class TestResolveVersion:
56 """The resolution order, one case per branch: pyproject beside the package, installed-distribution metadata, fallback."""
57
58 @pytest.fixture(autouse=True)
59 def _no_installed_distribution(self, monkeypatch: pytest.MonkeyPatch) -> None:
60 def _absent(name: str) -> str:
61 raise version_module.metadata.PackageNotFoundError(name)
62
63 monkeypatch.setattr(version_module.metadata, "version", _absent)
64
65 def test_reads_the_declared_version(self, tmp_path: Path) -> None:
66 assert resolve_version(_pyproject(tmp_path)) == "1.2.3rc4"
67
68 def test_a_declared_version_is_reported_in_canonical_spelling(self, tmp_path: Path) -> None:
69 assert resolve_version(_pyproject(tmp_path, version="1.2.3-rc.4")) == "1.2.3rc4"
70
71 def test_the_declaration_wins_over_a_stale_installed_distribution(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
72 monkeypatch.setattr(version_module.metadata, "version", lambda name: "0.2.0rc6")
73 assert resolve_version(_pyproject(tmp_path)) == "1.2.3rc4"
74
75 def test_without_a_pyproject_the_installed_distribution_is_the_record(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
76 monkeypatch.setattr(version_module.metadata, "version", lambda name: "3.4.5" if name == "musehub" else "x")
77 assert resolve_version(tmp_path / "absent.toml") == "3.4.5"
78
79 def test_no_pyproject_and_no_distribution_reports_the_sentinel_and_says_so(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
80 with caplog.at_level(logging.WARNING, logger=version_module.logger.name):
81 assert resolve_version(tmp_path / "absent.toml") == UNKNOWN_VERSION
82 assert UNKNOWN_VERSION in caplog.text
83
84 @pytest.mark.parametrize(
85 "kwargs",
86 [
87 {"name": "something-else"}, # some other project's pyproject.toml beside the package
88 {"version": None}, # no version declared (dynamic or missing)
89 {"version": "not a version"},
90 {"raw": "[project\nname = "}, # malformed TOML
91 {"raw": "[tool.x]\n"}, # no [project] table
92 ],
93 ids=["other-project", "no-version", "invalid-version", "malformed", "no-project-table"],
94 )
95 def test_an_unusable_pyproject_is_skipped_with_a_warning(self, tmp_path: Path, caplog: pytest.LogCaptureFixture, kwargs: dict[str, object]) -> None:
96 with caplog.at_level(logging.WARNING, logger=version_module.logger.name):
97 assert resolve_version(_pyproject(tmp_path, **kwargs)) == UNKNOWN_VERSION # type: ignore[arg-type]
98 assert "version:" in caplog.text
99
100 def test_an_unusable_pyproject_falls_through_to_the_distribution(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
101 monkeypatch.setattr(version_module.metadata, "version", lambda name: "3.4.5")
102 assert resolve_version(_pyproject(tmp_path, name="other")) == "3.4.5"
103
104
105 _PROBE = (
106 "import importlib.util, sys; sys.path[:0] = [sys.argv[2], sys.argv[3]]; "
107 "spec = importlib.util.spec_from_file_location('probe_version', sys.argv[1]); m = importlib.util.module_from_spec(spec); "
108 "spec.loader.exec_module(m); print(m.MUSE_VERSION)"
109 )
110
111
112 def _stale_distribution(site: Path, version: str) -> None:
113 info = site / f"musehub-{version}.dist-info"
114 info.mkdir(parents=True)
115 (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: musehub\nVersion: {version}\n")
116
117
118 def _run_probe(module: Path, site: Path) -> str:
119 """Load ``module`` by path in an isolated interpreter with ``site`` on sys.path (so its dist-info is discoverable).
120
121 ``-S`` keeps the surrounding environment's site-packages out: an editable or regular ``musehub`` install there
122 would otherwise supply real distribution metadata to the "neither" layout. The one third-party dependency of
123 ``version.py`` (``packaging``) is copied into a deps dir instead, so only ``site`` can name a distribution.
124 """
125 deps = site.parent / f"{site.name}-deps"
126 if not deps.exists():
127 shutil.copytree(Path(packaging.__file__).parent, deps / "packaging")
128 out = subprocess.run([sys.executable, "-I", "-S", "-c", _PROBE, str(module), str(site), str(deps)], capture_output=True, text=True, check=True)
129 return out.stdout.strip()
130
131
132 class TestInstallLayouts:
133 """The same ``version.py`` in the three layouts the service runs in, each run in an isolated interpreter."""
134
135 def _lay_out(self, root: Path) -> Path:
136 module = root / "musehub" / "protocol" / "version.py"
137 module.parent.mkdir(parents=True)
138 shutil.copy(_VERSION_PY, module)
139 return module
140
141 def test_container_layout_reads_the_pyproject_beside_the_package_and_ignores_a_stale_distribution(self, tmp_path: Path) -> None:
142 """/app/musehub/protocol/version.py with /app/pyproject.toml, as the Dockerfile lays it out."""
143 app = tmp_path / "app"
144 module = self._lay_out(app)
145 _pyproject(app, version="7.8.9rc1")
146 site = tmp_path / "site-packages"
147 _stale_distribution(site, "0.2.0rc6")
148 assert _run_probe(module, site) == "7.8.9rc1"
149
150 def test_wheel_install_layout_falls_back_to_distribution_metadata(self, tmp_path: Path) -> None:
151 """site-packages/musehub/... has no pyproject.toml beside it (the wheel ships only the package)."""
152 site = tmp_path / "site-packages"
153 module = self._lay_out(site)
154 _stale_distribution(site, "4.5.6")
155 assert _run_probe(module, site) == "4.5.6"
156
157 def test_a_tree_with_neither_reports_the_sentinel(self, tmp_path: Path) -> None:
158 module = self._lay_out(tmp_path / "lonely")
159 assert _run_probe(module, tmp_path / "empty-site") == UNKNOWN_VERSION
160
161 def test_the_dockerfile_copies_pyproject_next_to_the_package_and_the_allowlist_admits_it(self) -> None:
162 dockerfile = (ROOT / "Dockerfile").read_text()
163 runtime = dockerfile[dockerfile.index("AS runtime"):]
164 workdir = re.findall(r"^WORKDIR (\S+)", runtime, re.MULTILINE)[0]
165 package = re.search(r"^COPY \S+ musehub/musehub/ (\S+)$", runtime, re.MULTILINE)
166 pyproject = re.search(r"^COPY \S+ musehub/alembic.ini musehub/pyproject.toml (\S+)$", runtime, re.MULTILINE)
167 assert package and pyproject, "the runtime stage must copy musehub/ and pyproject.toml"
168 # package dir is <dest>/musehub-less: './musehub/' means <WORKDIR>/musehub; pyproject './' means <WORKDIR>/pyproject.toml
169 assert package.group(1) == "./musehub/" and pyproject.group(1) == "./" and workdir == "/app"
170 assert "!musehub/pyproject.toml" in (ROOT / "Dockerfile.dockerignore").read_text().splitlines()
171
172
173 class TestEverySurfaceReportsIt:
174 def test_protocol_info(self) -> None:
175 from musehub.protocol.responses import build_protocol_info
176
177 assert build_protocol_info(0, 0, {}).version == PYPROJECT_VERSION
178
179 def test_mcp_initialize_server_info(self) -> None:
180 from musehub.mcp.dispatcher import _SERVER_VERSION, _handle_initialize
181
182 assert _SERVER_VERSION == PYPROJECT_VERSION
183 assert _handle_initialize({})["serverInfo"] == {"name": "musehub-mcp", "version": PYPROJECT_VERSION}
184
185 def test_mcp_docs_json_server_block(self) -> None:
186 from musehub.api.routes.mcp import mcp_docs_json
187
188 body = json.loads(asyncio.run(mcp_docs_json()).body)
189 assert body["server"]["version"] == PYPROJECT_VERSION
190
191 def test_mcp_reference_page_catalogue(self) -> None:
192 from musehub.api.routes.musehub.ui_docs import _mcp_catalogue
193
194 assert _mcp_catalogue()["server_version"] == PYPROJECT_VERSION
195
196 def test_the_mcp_reference_page_does_not_claim_a_fixed_version(self) -> None:
197 html = (ROOT / "musehub" / "templates" / "musehub" / "pages" / "docs_muse_mcp.html").read_text()
198 assert "does not track the MuseHub release" not in html
199 assert "{{ mcp.server_version }}" in html
200
201 def test_app_settings_and_template_global(self) -> None:
202 from musehub.api.routes.musehub._templates import templates
203 from musehub.config import Settings
204
205 assert Settings().app_version == PYPROJECT_VERSION
206 assert templates.env.globals["MUSE_VERSION"] == PYPROJECT_VERSION
207
208 def test_no_independent_version_literal_in_the_mcp_dispatcher_or_routes(self) -> None:
209 for rel in ("musehub/mcp/dispatcher.py", "musehub/api/routes/mcp.py", "musehub/api/routes/musehub/ui_docs.py"):
210 src = (ROOT / rel).read_text()
211 assert not re.search(r"_SERVER_VERSION\s*=\s*[\"']", src), rel
212 assert not re.search(r"[\"']version[\"']\s*:\s*[\"']\d+\.\d+", src), rel
213
214
215 class TestTheVersioningPolicyIsDocumented:
216 DOC = (ROOT / "docs" / "versioning.md").read_text()
217
218 def test_the_policy_section_names_each_authority(self) -> None:
219 section = self.DOC[self.DOC.index("## MuseHub versioning"):]
220 section = section[: section.index("\n---\n")] if "\n---\n" in section else section
221 for needle in ("pyproject.toml", "serverInfo.version", "GET /protocol", "image digest", "c-series", "Muse CLI", "tag"):
222 assert needle in section, needle
File History 2 commits
sha256:772b8f0030c38b6a2bc565ade4de3ba0f78ff5f1dd1957cb968c708ec75881df test(version): isolate the release-version probe from the s… Opus 5.5 6 days ago
sha256:464e7da93c754ec52b71ac8e5e18d7d7a0ee34f6b0e4aaaefc44740dcdde59dc feat(version): VER-1 independent MuseHub version identity: … Sonnet 5.5 minor ⚠ 7 days ago