shortstats/tests/unitaires/test_architecture.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

106 lines
5 KiB
Python

"""Règles de structure du site (1.4.0) : tout le SQL dans web/data/, ce qui dépend de la
source de données dans web/sources.py, un seul parcours des couches d'une spec
(web/spec_layers.py), des modules de diagramme sans import circulaire."""
from __future__ import annotations
import ast
import re
import pytest
from shortstats.web import chart_aggregate, sources, transpose
from shortstats.web.templating import HERE
WEB = HERE
MODULES = sorted(p for p in WEB.rglob("*.py") if "data" not in p.relative_to(WEB).parts)
SQL = re.compile(r"\b(SELECT|INSERT INTO|UPDATE shortstats|DELETE FROM|GROUP BY|ORDER BY|LEFT JOIN|CROSS JOIN|LATERAL)\b")
# Expressions des données (liste blanche des catalogues) : du SQL, mais pas des requêtes.
SQL_ALLOWED = {"evolution.py": {"SNAP_DATE_SQL"}}
def _strings_with_sql(tree):
for node in ast.walk(tree):
if isinstance(node, ast.Constant) and isinstance(node.value, str) and SQL.search(node.value):
yield node
def test_sql_is_written_only_in_data():
for path in MODULES:
allowed = SQL_ALLOWED.get(path.name, set())
tree = ast.parse(path.read_text())
allowed_nodes = set()
for node in tree.body:
if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id in allowed for t in node.targets):
allowed_nodes |= {id(n) for n in ast.walk(node)}
bad = [n.lineno for n in _strings_with_sql(tree) if id(n) not in allowed_nodes]
assert not bad, f"{path.relative_to(WEB)} : SQL hors de web/data/ (lignes {bad})"
def test_queries_are_run_only_in_data():
for path in MODULES:
for n, line in enumerate(path.read_text().splitlines(), 1):
if ".execute(" in line:
# seule exception : l'abonnement aux événements du relais temps réel
assert path.name == "live.py" and "LISTEN" in line, f"{path.relative_to(WEB)}:{n}"
# Branches restantes sur la source, propres aux vidéos mises en avant (forme des lignes,
# place du titre) : elles ne concernent que highlight.py.
SOURCE_TESTS_ALLOWED = {"sources.py": 0, "highlight.py": 2}
def test_source_branches_only_in_sources():
for path in MODULES:
n = len(re.findall(r"\bsource\s*[!=]=\s*\"(?:evolution|j7)\"", path.read_text()))
assert n <= SOURCE_TESTS_ALLOWED.get(path.name, 0), f"{path.relative_to(WEB)} : {n} test(s) de la source"
def test_sources_offer_the_same_operations():
def ops(cls):
return {k for k, v in vars(cls).items() if not k.startswith("_")}
assert ops(sources.J7Source) == ops(sources.EvolutionSource)
assert {"validate", "filters", "compatible_types", "is_transposed", "base_query", "data_query",
"highlight_query", "build", "default_op", "reads_published", "key"} <= ops(sources.J7Source)
assert sources.source_of("evolution") is sources.EVOLUTION
assert sources.source_of("j7") is sources.source_of(None) is sources.source_of("inconnue") is sources.J7
assert chart_aggregate.resolve_op("auto", "evolution") == "median" and chart_aggregate.resolve_op(None) == "mean"
@pytest.mark.parametrize("raw,expected", [
({"x": "count", "y": "weekday"}, True), ({"x": "publish_date", "y": "views"}, False),
({"source": "evolution", "x": "views", "y": "age"}, True), ({"source": "evolution", "x": "age", "y": "views"}, False),
])
def test_transposed_through_sources(raw, expected):
from shortstats.web import chart_config
assert transpose.is_transposed(chart_config.validate_config(raw)) is expected
def test_spec_walkers_are_shared():
"""Les fonctionnalités parcourent les couches avec spec_layers.walk, et reconnaissent
catégorie et rôle avec ses conventions (aucune copie locale)."""
for name in ("marks.py", "legends.py", "highlight.py", "multi.py", "evolution.py", "transpose.py"):
src = (WEB / name).read_text()
assert not re.search(r"def _?walk\(", src), name
assert not re.search(r'"field": "cat", "equal"', src), name
assert not re.search(r'"style": "(hl-line|hl-point|box-median)"', src), name
CHART_LAYERS = ["chart_catalog", "chart_config", "chart_view", "chart_aggregate", "chart_zoom", "chart_layout",
"spec_layers", "charts", "chart_controls"]
def test_chart_modules_import_only_lower_layers():
"""Imports de premier niveau entre modules de diagramme : toujours vers une couche plus
basse (l'ordre de CHART_LAYERS) ; les imports dans une fonction rompent les cycles réels."""
order = {m: i for i, m in enumerate(CHART_LAYERS)}
order["chart_layout"] = order["spec_layers"] = -1 # sans dépendance
for mod in CHART_LAYERS:
tree = ast.parse((WEB / f"{mod}.py").read_text())
for node in tree.body:
if isinstance(node, ast.ImportFrom) and node.level == 1:
targets = [node.module] if node.module else [a.name for a in node.names]
for t in targets:
if t in order:
assert order[t] < order[mod], f"{mod} importe {t}"