"""Diagrammes « Évolution », filtres interactifs et bascule d'agrégation (v1.2.0).""" import itertools import json import os from datetime import datetime, timedelta, timezone import psycopg import pytest from shortstats.web import charts, evolution from .test_web import CH, ORIGIN, OTHER, app_client, login, seed_videos, users_file # noqa: F401 DUMP = os.environ.get("DUMP_SPECS") # chemin : enregistre les specs pour la vérification Vega-Lite _dumped: list = [] def seed_snapshots(owner_url, n_videos=12): """Deux chaînes, des vidéos à différents âges, des relevés sur les premières étapes.""" base = datetime(2026, 9, 1, 17, 0, tzinfo=timezone.utc) with psycopg.connect(owner_url, autocommit=True) as conn: for cid, name in ((CH, "Ma chaîne"), (OTHER, "Autre chaîne")): conn.execute("""INSERT INTO shortstats.channel (channel_id, youtube_title) VALUES (%s, %s) ON CONFLICT DO NOTHING""", (cid, name)) steps = conn.execute("SELECT step_id, nominal_hours FROM shortstats.snapshot_step " "WHERE step_id <= 30 ORDER BY step_id").fetchall() for i in range(n_videos): vid = f"evo{i:08d}" published = base + timedelta(days=i, hours=i % 7) conn.execute( """INSERT INTO shortstats.video (video_id, channel_id, published_at, status, title, duration_s) VALUES (%s, %s, %s, 'pending', %s, %s)""", (vid, CH if i % 2 else OTHER, published, f"Évolution {i}", 20 + i)) for sid, hours in steps[: 6 + i * 2]: views = int(100 * (i + 1) * (float(hours) ** 0.6)) # commentaires relevés et comptes par thème (analyse thématique, 1.3.0) read = views // 300 + 3 conn.execute( """INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count, like_count, comment_count, comments_read) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""", (vid, sid, published + timedelta(hours=float(hours) + 0.1), float(hours) + 0.1, views, views // 20, views // 300, read)) conn.execute( """INSERT INTO shortstats.snapshot_theme (video_id, step_id, theme_id, comments) SELECT %s, %s, theme_id, CASE WHEN name = 'applepie' THEN %s ELSE %s END FROM shortstats.theme WHERE CASE WHEN name = 'applepie' THEN %s ELSE %s END > 0""", (vid, sid, read // 3, i % 3, read // 3, i % 3)) def preview(c, config, view=None, status=200): body = {"config": config} if view is not None: body["view"] = view r = c.post("/api/preview", json=body, headers={"Origin": ORIGIN}) assert r.status_code == status, r.text out = r.json() if DUMP and status == 200 and out.get("spec"): _dumped.append({"name": json.dumps([config, view]), "spec": out["spec"]}) return out @pytest.fixture() def evo(app_client, clean_db): seed_snapshots(clean_db["owner"]) login(app_client) return app_client def test_validation(): ok = charts.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(charts.ChartError, match=msg): charts.validate_config(raw) # anciens diagrammes (sans « source ») : relevé à 7 j assert charts.validate_config({"x": "views", "y": "likes"}).source == "j7" def test_parse_view(): v = charts.parse_view({"filters": {"views": {"min": 10, "max": 5}, "weekday": {"in": ["Lundi"]}, "publish_date": {"min": "2026-09-01"}}, "individual": True}, "j7") assert v.filters["views"] == ("range", 5, 10) and v.filters["weekday"] == ("set", ("Lundi",)) assert v.individual and str(v.filters["publish_date"][1]) == "2026-09-01" # filtre inconnu (diagramme modifié depuis ses filtres par défaut) : ignoré assert charts.parse_view({"filters": {"inconnu": {"min": 1}}}, "j7").filters == {} for bad in [{"filters": {"views": {"min": "x"}}}, {"filters": {"publish_date": {"min": "pas une date"}}}, {"individual": "oui"}, {"autre": 1}, {"filters": {"weekday": {"in": "Lundi"}}}]: with pytest.raises(charts.ChartError): charts.parse_view(bad, "j7") assert charts.parse_view({"filters": {"age": {"min": 1, "max": 12}}}, "evolution").filters["age"] == ("range", 1, 12) assert charts.parse_view({"filters": {"comment_likes": {"min": 1}}}, "evolution").filters == {} def test_every_evolution_combination_renders(evo): n = 0 for x, y, t in itertools.product(evolution.X_FIELDS, evolution.Y_FIELDS, evolution.TYPES): if evolution.incompatibility(t, x): continue themed = charts.is_theme_measure(y) or charts.is_theme_measure(x) if themed and t == "boxplot": continue # la couleur distingue les thèmes : pas de boîtes (vérifié dans test_v130_analysis) for color in ((None, "theme") if themed else (None, "weekday")): for individual in (False, True): cfg = {"source": "evolution", "x": x, "y": y, "type": t, "color": color} out = preview(evo, cfg, {"individual": individual}) assert out["spec"] is not None, (cfg, out["explanation"]) json.dumps(out["spec"]) assert out["controls"]["filters"] n += 1 assert n > 50 def test_modes_and_split(evo): agg = preview(evo, {"source": "evolution", "x": "age", "y": "views"}) assert agg["resolved"]["mode"] == "agg" and agg["resolved"]["split"] == "color" assert "médiane par étape" in agg["explanation"] # âge sur une échelle linéaire des durées (1.3.2) : graduations régulières, depuis la sortie xs = agg["spec"]["encoding"]["x"] assert xs["scale"]["type"] == "linear" and xs["scale"]["domain"][0] == 0 ticks = xs["axis"]["values"] assert len({round(b - a, 6) for a, b in zip(ticks, ticks[1:])}) == 1 assert agg["controls"]["x_filter"] == "age" and agg["controls"]["individual"] == {"available": True, "active": False} each = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"individual": True}) assert each["resolved"]["mode"] == "each" and each["spec"]["encoding"]["detail"] == {"field": "id"} assert "une courbe par vidéo" in each["explanation"] assert {r["id"] for r in each["spec"]["data"]["values"]} == {f"evo{i:08d}" for i in range(12)} box = preview(evo, {"source": "evolution", "x": "age", "y": "views", "type": "boxplot"}) assert box["resolved"]["mode"] == "box" and len(box["spec"]["layer"]) == 3 assert box["controls"]["individual"]["available"] is False one = preview(evo, {"source": "evolution", "x": "age", "y": "views", "channels": [CH]}) assert one["resolved"]["split"] is None def test_trajectories_limited(evo, monkeypatch): monkeypatch.setattr(evolution, "MAX_TRAJECTORIES", 5) each = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"individual": True}) ids = {r["id"] for r in each["spec"]["data"]["values"]} assert ids == {f"evo{i:08d}" for i in range(7, 12)} # les 5 plus récentes assert "5 plus récentes sur 12" in each["explanation"] def test_filters_change_data(evo): base = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"individual": True}) ctl = {f["key"]: f for f in base["controls"]["filters"]} assert ctl["age"]["kind"] == "steps" and ctl["age"]["steps"][0] == {"id": 1, "label": "1 h"} assert ctl["channel"]["values"] == ["Autre chaîne", "Ma chaîne"] assert ctl["weekday"]["kind"] == "set" # âge entre l'étape 3 (3 h) et l'étape 8 (12 h) out = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"individual": True, "filters": {"age": {"min": 3, "max": 8}}}) labels = {r["lab"] for r in out["spec"]["data"]["values"]} assert labels == {"3 h", "4 h", "5 h", "6 h", "7 h", "8 h"} assert out["controls"]["active"] == {"age": {"min": 3, "max": 8}} # une chaîne seulement, par la case à cocher out = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"filters": {"channel": {"in": ["Ma chaîne"]}}}) assert out["resolved"]["split"] is None # date de sortie out = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"individual": True, "filters": {"publish_date": {"min": "2026-09-10"}}}) assert {r["id"] for r in out["spec"]["data"]["values"]} == {"evo00000009", "evo00000010", "evo00000011"} # filtre qui ne laisse rien out = preview(evo, {"source": "evolution", "x": "age", "y": "views"}, {"filters": {"duration": {"min": 1000}}}) assert out["spec"] is None and out["controls"]["filters"] def test_j7_filters_and_individual(app_client, clean_db): seed_videos(clean_db["owner"], n=30) login(app_client) cfg = {"x": "publish_date", "y": "views", "type": "line"} agg = preview(app_client, cfg) assert agg["controls"]["x_filter"] == "publish_date" assert agg["controls"]["individual"]["available"] is True each = preview(app_client, cfg, {"individual": True}) assert each["resolved"]["type"] == "scatter" and "chaque vidéo" in each["explanation"] assert each["n"] == 30 f = preview(app_client, cfg, {"filters": {"views": {"min": 10000, "max": 20000}}}) assert f["n"] == 11 f = preview(app_client, cfg, {"filters": {"duration": {"min": 30, "max": 39}}}) assert f["n"] == 10 # filtre des thèmes sans thème dans le diagramme : sans effet assert preview(app_client, cfg, {"filters": {"theme": {"in": ["applepie"]}}})["n"] == 30 hist = preview(app_client, {"x": "views", "y": "count"}) assert hist["controls"]["individual"]["available"] is False ctl = {c["key"]: c for c in agg["controls"]["filters"]} assert ctl["views"]["min"] == 1000 and ctl["views"]["max"] == 30000 and ctl["views"]["integer"] assert ctl["weekday"]["values"][0] in charts.WEEKDAYS # filtre interactif sur un diagramme enregistré chart_id = app_client.post("/api/charts", json={"config": cfg}, headers={"Origin": ORIGIN}).json()["id"] r = app_client.post(f"/api/charts/{chart_id}/render", json={"view": {"individual": True}}, headers={"Origin": ORIGIN}) assert r.status_code == 200 and r.json()["resolved"]["type"] == "scatter" # filtre inconnu : ignoré (ancien réglage) ; filtre mal formé : refusé assert app_client.post(f"/api/charts/{chart_id}/render", json={"view": {"filters": {"x": {}}}}, headers={"Origin": ORIGIN}).status_code == 200 assert app_client.post(f"/api/charts/{chart_id}/render", json={"view": {"filters": {"views": []}}}, headers={"Origin": ORIGIN}).status_code == 400 # rien n'est enregistré assert app_client.get("/api/charts").json()[0]["config"]["type"] == "line" def test_catalog_and_compat(evo): cat = evo.get("/api/catalog").json() assert set(cat["sources"]) == {"j7", "evolution"} assert [f["key"] for f in cat["evolution"]["x"]] == ["age", "snapshot_date"] # plus d'« Étape » (1.3.2) compat = evo.get("/api/compat?x=snapshot_date&y=views&source=evolution").json() assert compat["line"] is None and compat["boxplot"] and compat["heatmap"] assert evo.get("/api/compat?x=age&y=views&source=evolution").json()["boxplot"] is None assert evo.get("/api/compat?x=step&y=views&source=evolution").json()["boxplot"] is None # ancien nom def teardown_module(_module): if DUMP and _dumped: with open(DUMP, "w") as fh: json.dump(_dumped, fh)