290 lines
13 KiB
Python
290 lines
13 KiB
Python
"""Version 1.3.4 : numéro de version fourni à la construction, fichiers statiques
|
|
rechargés à chaque changement de leur contenu, progression des tests.
|
|
|
|
La 1.3.3 a été publiée avec le numéro 1.3.2, écrit à la main dans le dépôt : les
|
|
pages appelaient toujours ``app.js?v=1.3.2``, le navigateur gardait l'app.js de la
|
|
1.3.2 en cache, et ce script ne trouvait plus le menu d'agrégation retiré de la
|
|
page : diagrammes non affichés, ajout impossible (l'export, calculé par le
|
|
serveur, marchait). Désormais aucun numéro n'est écrit dans le dépôt, et le code
|
|
ne s'en sert que pour l'afficher.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tomllib
|
|
from importlib.metadata import version as installed_version
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
import shortstats
|
|
from shortstats import __version__, cli
|
|
from shortstats.web import app as web_app
|
|
from shortstats.web.app import HERE, assets_version
|
|
|
|
from . import progression
|
|
from .test_web import app_client, login, users_file # noqa: F401 (fixtures)
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
SCRIPT = ROOT / "scripts" / "version.sh"
|
|
PEP440 = re.compile(r"^\d+(\.\d+)*(\.post\d+)?(\+[a-z0-9]+(\.[a-z0-9]+)*)?$")
|
|
|
|
|
|
# -- 1. aucun numéro écrit dans le dépôt ------------------------------------------------
|
|
|
|
def test_no_hardcoded_version():
|
|
project = tomllib.loads((ROOT / "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 (ROOT / "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(ROOT).as_posix() for p in (ROOT / "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"]
|
|
|
|
|
|
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)}$", (ROOT / "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__}"
|
|
|
|
|
|
# -- 2. calcul du numéro d'après git ----------------------------------------------------
|
|
|
|
@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_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(ROOT / "setup.py"))
|
|
assert given["version"] == "9.8.7.post3+gabcdef"
|
|
monkeypatch.delenv("SHORTSTATS_VERSION")
|
|
runpy.run_path(str(ROOT / "setup.py"))
|
|
assert PEP440.match(given["version"]), given["version"]
|
|
|
|
|
|
# -- 3. fichiers statiques : empreinte du contenu, et de rien d'autre ---------------------
|
|
|
|
def test_assets_version_follows_content(tmp_path, monkeypatch):
|
|
(tmp_path / "app.js").write_text("console.log(1);")
|
|
(tmp_path / "vendor").mkdir()
|
|
(tmp_path / "vendor" / "lib.js").write_text("x")
|
|
before = assets_version(tmp_path)
|
|
assert re.fullmatch(r"[0-9a-f]{16}", before) and before == assets_version(tmp_path)
|
|
# le numéro de version n'y entre pas
|
|
monkeypatch.setattr(web_app, "__version__", "0+autre")
|
|
monkeypatch.setattr(shortstats, "__version__", "0+autre")
|
|
assert assets_version(tmp_path) == before
|
|
(tmp_path / "app.js").write_text("console.log(2);")
|
|
changed = assets_version(tmp_path)
|
|
assert changed != before
|
|
(tmp_path / "vendor" / "lib.js").write_text("y")
|
|
assert assets_version(tmp_path) != changed
|
|
changed = assets_version(tmp_path)
|
|
(tmp_path / "vendor" / "lib.js").rename(tmp_path / "vendor" / "lib2.js") # même contenu, autre nom
|
|
assert assets_version(tmp_path) != changed
|
|
|
|
|
|
def test_templates_use_assets_version():
|
|
for page in (HERE / "templates").glob("*.html"):
|
|
text = page.read_text()
|
|
assert "?v={{ version }}" not in text, page.name
|
|
for ref in re.findall(r"path='[^']+\.(?:js|css)'\) }}(\S*?)\"", text):
|
|
assert ref == "?v={{ assets }}", page.name
|
|
|
|
|
|
# Éléments que le script cherche sans les exiger (il vérifie leur absence).
|
|
OPTIONAL_IDS = {
|
|
"live.js": {"collect-state"}, # bouton « Lancer une collecte », tableau de bord seulement
|
|
"chartrender.js": {"vg-tooltip-element"}, # infobulle créée par Vega au premier survol
|
|
}
|
|
|
|
|
|
def test_scripts_find_their_elements():
|
|
"""Chaque élément cherché par un script (« $("#id") ») existe dans les pages qui le chargent.
|
|
|
|
L'erreur de la 1.3.3 vue depuis le navigateur : un app.js qui cherchait
|
|
#f-agg dans une page qui ne l'avait plus.
|
|
"""
|
|
templates = HERE / "templates"
|
|
common = "".join((templates / n).read_text() for n in ("base.html", "_theme_switch.html"))
|
|
checked = 0
|
|
for page in templates.glob("*.html"):
|
|
html = page.read_text()
|
|
ids = set(re.findall(r'\bid="([^"{]+)"', html + common))
|
|
for js in re.findall(r"path='([\w-]+\.js)'", html):
|
|
src = (HERE / "static" / js).read_text()
|
|
refs = {a or b for a, b in re.findall(r'\$\("#([\w-]+)"\)|getElementById\("([\w-]+)"\)', src)}
|
|
missing = refs - ids - OPTIONAL_IDS.get(js, set())
|
|
assert not missing, f"{page.name} charge {js}, qui cherche {sorted(missing)}"
|
|
checked += len(refs)
|
|
assert checked > 50
|
|
|
|
|
|
def test_dashboard_links_assets_version(app_client):
|
|
login(app_client)
|
|
page = app_client.get("/").text
|
|
v = assets_version()
|
|
for name in ("app.js", "chartrender.js", "chartview.js", "app.css", "theme.js"):
|
|
assert f"/static/{name}?v={v}\"" in page
|
|
assert f"version {__version__}" in app_client.get("/help").text
|
|
|
|
|
|
# -- 4. progression des tests -------------------------------------------------------------
|
|
|
|
def test_progression_durations():
|
|
assert progression.duree(0.04) == "0,0 s"
|
|
assert progression.duree(12.34) == "12,3 s"
|
|
assert progression.duree(65) == "1 min 05 s"
|
|
assert progression.duree(3720) == "1 h 02 min"
|
|
assert progression.pluriel(1, "échec") == "1 échec" and progression.pluriel(3, "réussi") == "3 réussis"
|
|
|
|
|
|
def test_progression_output(pytester):
|
|
pytester.makeconftest(f"import sys; sys.path.insert(0, {str(ROOT / 'tests')!r})\n"
|
|
"import progression\n"
|
|
"from progression import pytest_addoption\n"
|
|
"def pytest_configure(config):\n progression.register(config)\n")
|
|
pytester.makepyfile("""
|
|
import pytest, time
|
|
@pytest.mark.parametrize("i", range(30))
|
|
def test_ok(i):
|
|
pass
|
|
def test_skip():
|
|
pytest.skip("non")
|
|
def test_ko():
|
|
assert False
|
|
def test_lent():
|
|
time.sleep(0.3)
|
|
@pytest.fixture
|
|
def casse():
|
|
raise RuntimeError
|
|
def test_prep(casse):
|
|
pass
|
|
""")
|
|
res = pytester.runpytest("--progression", "0.2", "--progression-tests", "10", "-p", "no:cacheprovider")
|
|
out = res.stdout.str()
|
|
lines = [l for l in out.splitlines() if l.startswith("[")]
|
|
assert "34 tests à exécuter ; une ligne toutes les 0,2 s ou tous les 10 tests" in out
|
|
assert re.match(r"^\[10/34 29,4 %\] écoulé \d+,\d s · reste ~\d+,\d s · 10 réussis$", lines[0])
|
|
assert lines[-1].startswith("[34/34 100,0 %]") and "terminé · 31 réussis, 1 ignoré, 1 échec, 1 erreur" in lines[-1]
|
|
assert "ÉCHEC tests" not in out and re.search(r"^ÉCHEC test_progression_output\.py::test_ko · ", out, re.M)
|
|
assert "ÉCHEC (à la préparation) test_progression_output.py::test_prep" in out
|
|
# ni points ni pourcentages de pytest ; son résumé final reste
|
|
assert not re.search(r"^[.sFE]+\s*(\[\s*\d+%\])?$", out, re.M)
|
|
assert "short test summary info" in out or "FAILURES" in out
|
|
res.assert_outcomes(passed=31, skipped=1, failed=1, errors=1)
|
|
# -v ou --progression=0 : affichage habituel
|
|
assert "à exécuter" not in pytester.runpytest("--progression", "0").stdout.str()
|
|
|
|
|
|
# -- 5. plein écran : un diagramme ajusté à sa zone ne la fait pas défiler ----------------
|
|
|
|
def test_fit_chart_zone_never_scrolls():
|
|
"""Vega suit la taille de la zone (ResizeObserver) : si la zone pouvait défiler, un
|
|
dessin qui la dépasse de quelques pixels ferait apparaître puis disparaître les
|
|
barres de défilement à chaque image (diagramme qui tremble). Vérifié dans Chromium :
|
|
295 changements de taille sur 297 images avant, aucun après."""
|
|
js = (HERE / "static" / "chartrender.js").read_text()
|
|
assert 'box.classList.toggle("is-fit", spec.height === "container")' in js
|
|
assert js.index("fitHeight(spec, box, narrow);\n") < js.index('toggle("is-fit"') < js.index("await vegaEmbed(")
|
|
css = (HERE / "static" / "app.css").read_text()
|
|
assert re.search(r"^\.card\.is-full \.chart-box\.is-fit \{ overflow: hidden; \}$", css, re.M)
|