280 lines
18 KiB
Python
280 lines
18 KiB
Python
"""Validation des configurations de diagramme (messages d'erreur, valeurs par défaut)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
from shortstats.web import chart_catalog, chart_config, chart_view, evolution, highlight, marks
|
|
from shortstats.web.chart_catalog import ChartError
|
|
from shortstats.web.chart_config import validate_config
|
|
|
|
from ..outils.lignes import A, B
|
|
|
|
|
|
@pytest.mark.parametrize("raw,message", [
|
|
({"x": "nope", "y": "views"}, "Abscisse"),
|
|
({"x": "views", "y": "nope"}, "Ordonnée"),
|
|
({"x": "views", "y": "likes", "type": "pie"}, "Type"),
|
|
({"x": "views", "y": "likes", "color": "title"}, "couleur"),
|
|
({"x": "views", "y": "likes", "sql": "DROP TABLE"}, "inconnus"),
|
|
({"x": "views", "y": "likes", "title": "x" * 200}, "Titre"),
|
|
({"x": "views", "y": "count", "type": "scatter"}, "impossible"),
|
|
("pas un objet", "objet"),
|
|
])
|
|
def test_validation_errors(raw, message):
|
|
with pytest.raises(ChartError, match=message):
|
|
validate_config(raw)
|
|
|
|
|
|
def test_validation_evolution():
|
|
ok = chart_config.validate_config({"source": "evolution", "x": "age", "y": "views"})
|
|
assert ok.source == "evolution" and ok.to_dict()["source"] == "evolution"
|
|
for raw, msg in [
|
|
({"source": "evolution", "x": "publish_date", "y": "views"}, "Abscisse"),
|
|
({"source": "evolution", "x": "age", "y": "duration"}, "Ordonnée"),
|
|
({"source": "evolution", "x": "snapshot_date", "y": "views", "type": "boxplot"}, "Âge de la vidéo"),
|
|
({"source": "evolution", "x": "age", "y": "views", "type": "heatmap"}, "courbe, barres"),
|
|
({"source": "evolution", "x": "age", "y": "views", "color": "views"}, "couleur"),
|
|
({"source": "autre", "x": "age", "y": "views"}, "Source"),
|
|
]:
|
|
with pytest.raises(chart_catalog.ChartError, match=msg):
|
|
chart_config.validate_config(raw)
|
|
# anciens diagrammes (sans « source ») : relevé à 7 j
|
|
assert chart_config.validate_config({"x": "views", "y": "likes"}).source == "j7"
|
|
|
|
|
|
def test_rules():
|
|
ok = [
|
|
{"x": "publish_date", "y": "views@6", "y_more": ["views@8", "views@17", "views"]}, # 1 catégorie, 4 moments
|
|
{"x": "publish_date", "y": "views@6", "y_more": ["views@8", "likes@6", "likes@8"]}, # 2 catégories
|
|
{"x": "views@6", "y": "duration", "y_more": ["comments"]},
|
|
{"x": "theme", "y": "theme_rate@56", "y_more": ["theme_rate@6", "theme_comments@56"]},
|
|
{"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"]},
|
|
]
|
|
for raw in ok:
|
|
assert len(chart_config.validate_config(raw).ys) == 1 + len(raw["y_more"])
|
|
bad = [
|
|
({"x": "publish_date", "y": "views", "y_more": ["likes", "comments"]}, "2 catégories"), # 3 catégories à 7 j
|
|
({"x": "publish_date", "y": "views@6", "y_more": ["likes@6", "comment_rate@6"]}, "2 catégories"),
|
|
({"x": "publish_date", "y": "count", "y_more": ["views"]}, "seulement des mesures"),
|
|
({"x": "publish_date", "y": "views", "y_more": ["theme"]}, "seulement des mesures"),
|
|
({"x": "publish_date", "y": "theme_rate@56", "y_more": ["theme_rate@6"]}, "Thème des commentaires » en abscisse"),
|
|
({"x": "theme", "y": "theme_rate@56", "y_more": ["views@56"]}, "seulement des mesures de thème"),
|
|
({"x": "views", "y": "likes", "y_more": ["comment_likes"]}, "commentaire épinglé"),
|
|
({"x": "weekday", "y": "views", "y_more": ["views@6"], "type": "boxplot"}, "une seule ordonnée"),
|
|
({"x": "views@6", "y": "views", "y_more": ["views@8"], "type": "bar"}, "catégorie ou une date"),
|
|
({"source": "evolution", "x": "age", "y": "views", "y_more": ["likes", "comments"]}, "2 catégories"),
|
|
({"source": "evolution", "x": "age", "y": "views", "y_more": ["views@6"]}, "invalide"),
|
|
({"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"], "type": "boxplot"}, "une seule"),
|
|
]
|
|
for raw, msg in bad:
|
|
with pytest.raises(chart_catalog.ChartError, match=msg):
|
|
chart_config.validate_config(raw)
|
|
# doublons et répétition de l'ordonnée principale retirés ; ancien format sans y_more accepté
|
|
cfg = chart_config.validate_config({"x": "publish_date", "y": "views", "y_more": ["views", "views@6", "views@6"]})
|
|
assert cfg.y_more == ("views@6",) and cfg.to_dict()["y_more"] == ["views@6"]
|
|
assert chart_config.validate_config({"x": "views", "y": "likes"}).y_more == ()
|
|
assert chart_config.compatible_types("weekday", "views", multi=True)["boxplot"]
|
|
|
|
|
|
def test_validation_types_par_categorie():
|
|
base = {"x": "publish_date", "y": "views@6", "y_more": ["likes@6"]}
|
|
assert chart_config.validate_config({**base, "type": "bar", "type2": "line"}).type2 == "line"
|
|
assert chart_config.validate_config(base).type2 == ""
|
|
assert chart_config.validate_config({**base, "type2": None}).to_dict()["type2"] == ""
|
|
# une seule catégorie : sans objet, ignoré (la 2e vient d'être retirée dans l'éditeur)
|
|
assert chart_config.validate_config({"x": "publish_date", "y": "views@6", "y_more": ["views@8"],
|
|
"type2": "bar"}).type2 == ""
|
|
assert chart_config.validate_config({"x": "publish_date", "y": "views", "type2": "bar"}).type2 == ""
|
|
for raw, msg in [
|
|
({**base, "type2": "boxplot"}, "courbe, barres, nuage de points"),
|
|
({**base, "type2": "camembert"}, "axe de droite"),
|
|
({"x": "views", "y": "views@6", "y_more": ["likes@6"], "type2": "bar"}, "Barres impossible pour l'axe de droite"),
|
|
({"x": "title", "y": "views@6", "y_more": ["likes@6"], "type2": "line"}, "Courbe impossible pour l'axe de droite"),
|
|
({"source": "evolution", "x": "snapshot_date", "y": "views", "y_more": ["likes"], "type2": "bar"},
|
|
"Âge de la vidéo"),
|
|
({"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"], "type2": "scatter"},
|
|
"Nuage de points impossible pour l'axe de droite : l'abscisse doit être une statistique"),
|
|
]:
|
|
with pytest.raises(chart_catalog.ChartError, match=msg):
|
|
chart_config.validate_config(raw)
|
|
evo_cfg = chart_config.validate_config({"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"],
|
|
"type2": "bar"})
|
|
assert evolution.layer_types(evo_cfg) == ["line", "bar"]
|
|
|
|
|
|
def test_pairs_validation():
|
|
cfg = chart_config.validate_config({"source": "evolution", "x": "likes", "y": "views"})
|
|
assert evolution.is_pairs(cfg) and evolution.mode(cfg, None) == "pairs"
|
|
assert evolution.resolved_type(cfg) == "scatter"
|
|
assert chart_config.validate_config({"source": "evolution", "x": "likes", "y": "views", "color": "period"}).color == "period"
|
|
for raw, msg in [
|
|
({"source": "evolution", "x": "likes", "y": "views", "type": "line"}, "un point par relevé : nuage de points"),
|
|
({"source": "evolution", "x": "age", "y": "views", "type": "scatter"}, "statistique à toutes les étapes"),
|
|
({"source": "evolution", "x": "age", "y": "views", "color": "period"}, "couleur"),
|
|
({"source": "evolution", "x": "duration", "y": "views"}, "Abscisse invalide"),
|
|
]:
|
|
with pytest.raises(chart_catalog.ChartError, match=msg):
|
|
chart_config.validate_config(raw)
|
|
assert evolution.compatible_types("likes")["scatter"] is None
|
|
assert evolution.compatible_types("likes")["line"]
|
|
assert evolution.compatible_types("age")["scatter"]
|
|
|
|
|
|
def test_highlight_validation():
|
|
assert highlight.validate(None) == ()
|
|
ok = highlight.validate([{"video": "evo00000003", "title": "Ma vidéo"}, {"rank": "views", "n": 2},
|
|
{"rank": "views", "n": 2}])
|
|
assert ok == ({"video": "evo00000003", "title": "Ma vidéo"}, {"rank": "views", "n": 2}) # sans doublon
|
|
for bad in ([{"video": "x"}], [{"rank": "inconnu"}], [{"rank": "views", "n": 0}], [{"rank": "views", "n": True}],
|
|
[{"video": "evo00000003", "autre": 1}], [{}] , "x", [{"rank": "views"}] * 4,
|
|
[{"video": "evo00000003", "title": "t" * 201}]):
|
|
with pytest.raises(chart_catalog.ChartError):
|
|
highlight.validate(bad)
|
|
assert highlight.describe({"rank": "latest", "n": 1}) == "la plus récente"
|
|
assert highlight.describe({"rank": "views", "n": 3}) == "3e plus vue"
|
|
assert highlight.describe({"rank": "like_rate", "n": 1}) == "au meilleur taux de like"
|
|
assert highlight.short("x" * 40) == "x" * 29 + "…"
|
|
cfg = chart_config.validate_config({"x": "views", "y": "likes", "highlight": [{"rank": "views", "n": 1}]})
|
|
assert cfg.to_dict()["highlight"] == [{"rank": "views", "n": 1}]
|
|
assert chart_config.validate_config({"x": "views", "y": "likes"}).to_dict()["highlight"] == []
|
|
view = chart_view.parse_view({"highlight": []}, cfg)
|
|
assert view.highlight == () # liste vide : aucune (remplace celle du diagramme)
|
|
assert chart_view.parse_view({}, cfg).highlight is None
|
|
|
|
|
|
def test_defaults_validation():
|
|
raw = {"x": "publish_date", "y": "views", "type": "scatter",
|
|
"defaults": {"filters": {"views": {"min": 5000, "max": 1000}, "weekday": {"in": ["Lundi"]},
|
|
"plus_la": {"min": 1}},
|
|
"y_axes": [{"min": None, "max": 9000}], "individual": True}}
|
|
cfg = chart_config.validate_config(raw)
|
|
# bornes remises dans l'ordre, filtre qui ne s'applique plus retiré
|
|
assert cfg.defaults == {"filters": {"views": {"min": 1000, "max": 5000}, "weekday": {"in": ["Lundi"]}},
|
|
"y_axes": [{"min": None, "max": 9000.0}], "individual": True}
|
|
assert cfg.to_dict()["defaults"] == cfg.defaults
|
|
assert chart_config.validate_config({**raw, "defaults": {}}).defaults == {}
|
|
assert chart_config.validate_config({"x": "views", "y": "likes"}).to_dict().get("defaults", {}) == {}
|
|
for bad in ({"hidden": {"s": ["Vues"]}}, {"highlight": []}, {"filters": {"views": {"min": "x"}}}, [1]):
|
|
with pytest.raises(chart_catalog.ChartError, match="défaut"):
|
|
chart_config.validate_config({**raw, "defaults": bad})
|
|
# sans vue : celle des filtres par défaut ; vue envoyée (même vide) : elle seule
|
|
view = chart_view.parse_view(None, cfg)
|
|
assert view.filters == {"views": ("range", 1000, 5000), "weekday": ("set", ("Lundi",))}
|
|
assert view.individual and view.y_axes == ((None, 9000.0),)
|
|
assert chart_view.parse_view({}, cfg).filters == {}
|
|
assert chart_view.parse_view(None, cfg, apply_defaults=False).filters == {}
|
|
|
|
|
|
def test_validation_rules():
|
|
ok = chart_config.validate_config({"x": "theme", "y": "theme_rate@56"})
|
|
assert ok.color is None
|
|
auto = chart_config.validate_config({"x": "views@56", "y": "theme_rate@56"})
|
|
assert auto.color == "theme" # couleur libre : un thème par couleur
|
|
evo_auto = chart_config.validate_config({"source": "evolution", "x": "age", "y": "theme_rate"})
|
|
assert evo_auto.color == "theme"
|
|
bad = [
|
|
({"x": "theme", "y": "views"}, "va avec une mesure de thème"),
|
|
({"x": "theme", "y": "count"}, "va avec une mesure de thème"),
|
|
({"x": "views", "y": "likes", "color": "theme"}, "va avec une mesure de thème"),
|
|
({"x": "views@56", "y": "theme_rate@56", "color": "weekday"}, "thème par thème"),
|
|
({"x": "weekday", "y": "theme_rate@56", "color": "theme", "type": "boxplot"}, "distinguer les thèmes"),
|
|
({"x": "publish_date", "y": "theme_rate@56", "y_more": ["theme_comments@56"]}, "en abscisse"),
|
|
({"x": "theme", "y": "theme_rate@56", "y_more": ["views@56"]}, "seulement des mesures de thème"),
|
|
({"source": "evolution", "x": "age", "y": "theme_rate", "type": "boxplot"}, "Boîte à moustaches"),
|
|
({"source": "evolution", "x": "age", "y": "theme_rate", "color": "channel"}, "thème par thème"),
|
|
({"source": "evolution", "x": "age", "y": "views", "color": "theme"}, "va avec une mesure de thème"),
|
|
({"source": "evolution", "x": "age", "y": "theme_rate", "y_more": ["views"]}, "une seule ordonnée"),
|
|
# données du commentaire épinglé (avant la 1.3.0) : message clair
|
|
({"x": "pinned_theme", "y": "views"}, "Diagramme à modifier"),
|
|
({"x": "views", "y": "comment_likes"}, "commentaire épinglé"),
|
|
({"source": "evolution", "x": "age", "y": "views", "color": "theme_each"}, "commentaire épinglé"),
|
|
]
|
|
for raw, msg in bad:
|
|
with pytest.raises(chart_catalog.ChartError, match=msg):
|
|
chart_config.validate_config(raw)
|
|
# boîtes à moustaches par thème : avec le thème en abscisse
|
|
assert chart_config.validate_config({"x": "theme", "y": "theme_rate@6", "type": "boxplot"}).type == "boxplot"
|
|
|
|
|
|
def test_validate_channels():
|
|
cfg = validate_config({"x": "views", "y": "likes", "channels": [A, B, A], "split_channels": False})
|
|
assert cfg.channels == (A, B) and cfg.split_channels is False
|
|
assert cfg.to_dict()["channels"] == [A, B]
|
|
json.dumps(cfg.to_dict())
|
|
assert validate_config({"x": "views", "y": "likes"}).split_channels is True
|
|
for bad in (["@handle"], "UC" + "a" * 22, [1], ["UC" + "a" * 21]):
|
|
with pytest.raises(ChartError, match="chaînes"):
|
|
validate_config({"x": "views", "y": "likes", "channels": bad})
|
|
with pytest.raises(ChartError, match="maximum"):
|
|
validate_config({"x": "views", "y": "likes", "channels": [f"UC{i:022d}" for i in range(51)]})
|
|
with pytest.raises(ChartError, match="split_channels"):
|
|
validate_config({"x": "views", "y": "likes", "split_channels": "oui"})
|
|
|
|
|
|
def test_marks_validation_and_storage():
|
|
assert marks.validate(None) == {} and marks.validate({}) == {}
|
|
# valeurs par défaut omises : configuration habituelle, lisible par les versions d'avant
|
|
assert marks.validate({"shape": "circle", "point": "normal", "line": "normal"}) == {}
|
|
assert marks.validate({"shape": "square", "point": "large", "line": ""}) == {"shape": "square", "point": "large"}
|
|
for bad in ({"shape": "star"}, {"point": "huge"}, {"line": 3}, {"color": "red"}, ["square"]):
|
|
try:
|
|
marks.validate(bad)
|
|
except chart_catalog.ChartError:
|
|
continue
|
|
raise AssertionError(bad)
|
|
cfg = chart_config.validate_config({"x": "views", "y": "likes", "marks": {"shape": "diamond", "line": "thick"}})
|
|
assert cfg.marks == {"shape": "diamond", "line": "thick"}
|
|
assert cfg.to_dict()["marks"] == {"shape": "diamond", "line": "thick"}
|
|
assert chart_config.validate_config(cfg.to_dict()) == cfg # aller-retour (enregistrement, export)
|
|
assert "marks" not in chart_config.validate_config({"x": "views", "y": "likes"}).to_dict()
|
|
evo_cfg = chart_config.validate_config({"source": "evolution", "x": "age", "y": "views", "marks": {"point": "small"}})
|
|
assert evo_cfg.marks == {"point": "small"}
|
|
|
|
|
|
def test_aggs_validation_and_compat():
|
|
# ancien format : une agrégation pour tout le diagramme, relue et réécrite telle quelle
|
|
old = chart_config.validate_config({"x": "weekday", "y": "views", "agg": "median"})
|
|
assert old.aggs == () and old.agg == "median" and old.agg_spec(0) == {"op": "median"}
|
|
assert old.to_dict()["agg"] == "median" and "aggs" not in old.to_dict()
|
|
# même opération partout, sans limite : toujours l'ancien format (lisible par la 1.3.2)
|
|
same = chart_config.validate_config({"x": "weekday", "y": "views@6", "y_more": ["views@8"],
|
|
"aggs": [{"op": "max"}, {"op": "max"}]})
|
|
assert same.aggs == () and same.to_dict()["agg"] == "max"
|
|
# une limite, ou des opérations différentes : une agrégation par ordonnée
|
|
cfg = chart_config.validate_config({"x": "weekday", "y": "views", "y_more": ["views", "likes"],
|
|
"aggs": [{"op": "median"}, {"op": "mean", "limit": {"last": 10}},
|
|
{"limit": {"when": "$date € $A-1"}}]})
|
|
assert cfg.y_more == ("views", "likes") # même donnée, autre agrégation : gardée
|
|
assert cfg.aggs == ({"op": "median"}, {"op": "mean", "limit": {"last": 10}},
|
|
{"op": "auto", "limit": {"when": "$date € $A-1"}}) # espaces réduits
|
|
d = cfg.to_dict()
|
|
assert "agg" not in d and d["aggs"][1] == {"op": "mean", "limit": {"last": 10}}
|
|
assert chart_config.validate_config(d) == cfg # relu à l'identique (enregistrement, export)
|
|
# doublon exact retiré, avec son agrégation
|
|
dup = chart_config.validate_config({"x": "weekday", "y": "views", "y_more": ["views", "views"],
|
|
"aggs": [{"op": "mean"}, {"op": "median"}, {"op": "median"}]})
|
|
assert dup.y_more == ("views",) and [a["op"] for a in dup.aggs] == ["mean", "median"]
|
|
assert chart_config.validate_config({"x": "weekday", "y": "views", "y_more": ["views"]}).y_more == ()
|
|
# évolution : une statistique peut revenir avec une autre agrégation
|
|
evo = chart_config.validate_config({"source": "evolution", "x": "age", "y": "views", "y_more": ["views"],
|
|
"aggs": [{"op": "median"}, {"op": "mean", "limit": {"last": 16}}]})
|
|
assert evo.y_more == ("views",) and evolution.layer_types(evo) == ["line"]
|
|
for raw, msg in [
|
|
({"aggs": [{"op": "mode"}]}, "opération inconnue"),
|
|
({"aggs": [{"op": "mean"}, {"op": "mean"}]}, "une par ordonnée"),
|
|
({"aggs": [{"limit": {"last": 0}}]}, "entre 1 et 1000"),
|
|
({"aggs": [{"limit": {"last": True}}]}, "entre 1 et 1000"),
|
|
({"aggs": [{"limit": {"when": "$date = 2026-13-01"}}]}, "date « 2026-13-01 » invalide"),
|
|
({"aggs": [{"limit": {"when": "$date ~ $A"}}]}, "« ~ » inattendu"),
|
|
({"aggs": [{"limit": {"when": 2026}}]}, "période de sortie invalide"),
|
|
({"aggs": [{"limit": {"from": "2026-01-01"}}]}, "limite invalide"),
|
|
({"aggs": [{"limit": {"depuis": "2026-01-01"}}]}, "limite invalide"),
|
|
({"aggs": [{"op": "mean", "n": 3}]}, "invalide"),
|
|
]:
|
|
with pytest.raises(chart_catalog.ChartError, match=msg):
|
|
chart_config.validate_config({"x": "weekday", "y": "views", **raw})
|
|
# nombre de vidéos en abscisse (axes inversés) : rien à agréger, agrégation ignorée
|
|
assert chart_config.validate_config({"x": "count", "y": "weekday", "aggs": [{"op": "max"}]}).aggs == ()
|