shortstats/tests/unitaires/test_version.py
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

144 lines
5.8 KiB
Python

"""Numéro de version fourni à la construction (étiquettes git)."""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
import tomllib
from importlib.metadata import version as installed_version
import pytest
from shortstats import __version__, cli
from ..outils import RACINE
SCRIPT = RACINE / "scripts" / "version.sh"
PEP440 = re.compile(r"^\d+(\.\d+)*(\.post\d+)?(\+[a-z0-9]+(\.[a-z0-9]+)*)?$")
@pytest.fixture()
def repo(tmp_path):
if shutil.which("git") is None:
pytest.skip("git absent")
(tmp_path / "scripts").mkdir()
shutil.copy(SCRIPT, tmp_path / "scripts" / "version.sh")
env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@t", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}
def git(*args):
return subprocess.run(["git", *args], cwd=tmp_path, env=env, check=True, capture_output=True, text=True).stdout.strip()
def version():
return subprocess.run(["sh", "scripts/version.sh"], cwd=tmp_path, env=env, check=True,
capture_output=True, text=True).stdout.strip()
def commit(name):
(tmp_path / name).write_text(name)
git("add", "-A")
git("commit", "-q", "-m", name)
return git("rev-parse", "--short=12", "HEAD")
git("init", "-q")
return git, version, commit, tmp_path
def test_no_hardcoded_version():
project = tomllib.loads((RACINE / "pyproject.toml").read_text())["project"]
assert "version" not in project and project["dynamic"] == ["version"]
literal = re.compile(r"""__version__\s*=\s*["']\d+\.\d""") # « 0+inconnue » : absence de numéro
for path in (RACINE / "src").rglob("*.py"):
assert not literal.search(path.read_text()), path
# le code ne compare jamais le numéro : il l'affiche (page Aide, --version)
users = [p.relative_to(RACINE).as_posix() for p in (RACINE / "src").rglob("*.py") if "__version__" in p.read_text()]
assert sorted(users) == ["src/shortstats/__init__.py", "src/shortstats/cli.py", "src/shortstats/web/app.py",
"src/shortstats/web/templating.py"]
def test_version_from_installed_package():
assert __version__ == installed_version("shortstats")
assert PEP440.match(__version__), __version__
def test_version_matches_build():
"""CI : le paquet installé porte le numéro calculé par scripts/version.sh."""
expected = os.environ.get("SHORTSTATS_VERSION")
if not expected:
pytest.skip("SHORTSTATS_VERSION non défini (hors CI)")
assert __version__ == expected
def test_tag_matches_version():
"""Sur une étiquette vX.Y.Z (CI) : même numéro, et une note de version à ce numéro."""
ref = os.environ.get("GITHUB_REF", "")
if not ref.startswith("refs/tags/v"):
pytest.skip("pas une étiquette de version")
tag = ref.removeprefix("refs/tags/v")
assert re.fullmatch(r"\d+\.\d+\.\d+", tag), f"étiquette invalide : v{tag}"
assert __version__ == tag
assert re.search(rf"^## {re.escape(tag)}$", (RACINE / "CHANGELOG.md").read_text(), re.M), \
f"CHANGELOG.md : pas de section « ## {tag} »"
def test_cli_version(capsys):
with pytest.raises(SystemExit) as exc:
cli.main(["--version"])
assert exc.value.code == 0 and capsys.readouterr().out.strip() == f"shortstats {__version__}"
def test_version_script(repo):
git, version, commit, path = repo
sha = commit("a")
assert version() == f"0.post1+g{sha}" # aucune étiquette
git("tag", "v1.2.3")
assert version() == "1.2.3" # commit étiqueté
sha = commit("b")
sha = commit("c")
assert version() == f"1.2.3.post2+g{sha}" # main : 2 commits après v1.2.3
git("tag", "v1.2") # étiquette invalide : ignorée
git("tag", "essai")
assert version() == f"1.2.3.post2+g{sha}"
git("tag", "v1.3.0")
git("tag", "v1.2.9") # deux étiquettes : la plus haute
assert version() == "1.3.0"
(path / "c").write_text("modifié") # poste de développement
assert version() == "1.3.0+modifie"
git("checkout", "-q", "--", "c")
commit("d")
(path / "d").write_text("modifié")
assert version().endswith(".modifie") and version().startswith("1.3.0.post1+g")
for v in ("0.post1+gabc", "1.2.3", "1.2.3.post2+g0123456789ab", "1.3.0+modifie", version()):
assert PEP440.match(v), v
def test_version_script_refuses_shallow(repo, tmp_path_factory):
git, version, commit, path = repo
commit("a")
commit("b")
clone = tmp_path_factory.mktemp("superficiel")
subprocess.run(["git", "clone", "-q", "--depth", "1", f"file://{path}", str(clone)], check=True, capture_output=True)
# le script se place dans le dépôt qui le contient : on lance celui du clone
shutil.copytree(SCRIPT.parent, clone / "scripts", dirs_exist_ok=True)
res = subprocess.run(["sh", "scripts/version.sh"], cwd=clone, capture_output=True, text=True)
assert res.returncode != 0 and "superficiel" in res.stderr
def test_setup_py_version(monkeypatch):
"""Image Docker : sans historique git, le numéro vient de SHORTSTATS_VERSION ; sinon de git."""
import runpy
import types
given = {}
fake = types.ModuleType("setuptools")
fake.setup = lambda **kw: given.update(kw)
monkeypatch.setitem(sys.modules, "setuptools", fake)
monkeypatch.setenv("SHORTSTATS_VERSION", "9.8.7.post3+gabcdef")
runpy.run_path(str(RACINE / "setup.py"))
assert given["version"] == "9.8.7.post3+gabcdef"
monkeypatch.delenv("SHORTSTATS_VERSION")
runpy.run_path(str(RACINE / "setup.py"))
assert PEP440.match(given["version"]), given["version"]