"""Diagrammes par l'API : création, rendu, aperçu, filtres par défaut, agrégations.""" from __future__ import annotations from datetime import datetime import psycopg from shortstats.web import chart_catalog, chart_config, multi from ..outils.base import seed_comments, seed_videos from ..outils.site import CH, ORIGIN, OTHER, login, preview def test_chart_crud_and_render(app_client, clean_db): seed_videos(clean_db["owner"]) seed_comments(clean_db["owner"]) login(app_client) h = {"Origin": ORIGIN} cfg = {"x": "weekday", "y": "views", "type": "auto", "agg": "auto", "color": None, "scale": "auto", "title": ""} r = app_client.post("/api/charts", json={"config": cfg}, headers=h) assert r.status_code == 201 chart_id = r.json()["id"] # « Thème » seul (sans mesure de thème) : refusé, avec la raison r = app_client.post("/api/charts", json={"config": {**cfg, "x": "theme", "y": "count"}}, headers=h) assert r.status_code == 400 and "mesure de thème" in r.json()["error"] r2 = app_client.post("/api/charts", json={"config": {**cfg, "x": "theme", "y": "theme_rate@56"}}, headers=h) second = r2.json()["id"] out = app_client.get(f"/api/charts/{chart_id}/render").json() assert out["n"] == 30 and out["spec"]["mark"]["type"] in {"boxplot", "bar"} themes = {v["x"] for v in app_client.get(f"/api/charts/{second}/render").json()["spec"]["data"]["values"]} assert themes == {"Apothecary Diaries", "applepie"} assert app_client.post(f"/api/charts/{second}/move", json={"direction": -1}, headers=h).status_code == 204 assert [c["id"] for c in app_client.get("/api/charts").json()] == [second, chart_id] r = app_client.put(f"/api/charts/{chart_id}", json={"config": {**cfg, "type": "heatmap", "y": "count"}}, headers=h) assert r.status_code == 400 and "impossible" in r.json()["error"] assert app_client.delete(f"/api/charts/{chart_id}", headers=h).status_code == 204 assert app_client.delete(f"/api/charts/{chart_id}", headers=h).status_code == 404 def test_preview_and_compat(app_client, clean_db): seed_videos(clean_db["owner"]) login(app_client) r = app_client.post("/api/preview", json={"config": {"x": "views", "y": "likes"}}, headers={"Origin": ORIGIN}) assert r.json()["resolved"]["type"] == "scatter" compat = app_client.get("/api/compat?x=views&y=count").json() assert compat["histogram"] is None and compat["scatter"] def test_video_titles_are_escaped(app_client, clean_db): seed_videos(clean_db["owner"], n=3) login(app_client) html = app_client.get("/videos").text assert "<b>Short 0</b>" in html and "Short 0" not in html def test_channel_field_in_charts_and_dashboard_banner(app_client, clean_db): login(app_client) assert "Aucune chaîne suivie" in app_client.get("/").text seed_videos(clean_db["owner"], n=6) out = app_client.post("/api/preview", json={"config": {"x": "channel", "y": "views"}}, headers={"Origin": ORIGIN}).json() assert {v["x"] for v in out["spec"]["data"]["values"]} == {"Ma chaîne"} assert "Aucune chaîne suivie" not in app_client.get("/").text def test_charts_filter_and_split_by_channel_from_db(app_client, clean_db): seed_videos(clean_db["owner"], n=20) with psycopg.connect(clean_db["owner"], autocommit=True) as conn: conn.execute("""INSERT INTO shortstats.channel (channel_id, youtube_title) VALUES (%s, 'Seconde chaîne')""", (OTHER,)) conn.execute("UPDATE shortstats.video SET channel_id = %s WHERE right(video_id, 1)::int %% 2 = 1", (OTHER,)) login(app_client) cat = app_client.get("/api/catalog").json() assert [c["name"] for c in cat["channels"]] == ["Ma chaîne", "Seconde chaîne"] assert {c["collected"] for c in cat["channels"]} == {10} def preview(cfg): r = app_client.post("/api/preview", json={"config": cfg}, headers={"Origin": ORIGIN}) assert r.status_code == 200, r.text return r.json() both = preview({"x": "publish_date", "y": "views", "type": "line"}) assert both["n"] == 20 and both["resolved"]["split"] == "color" assert both["spec"]["encoding"]["color"]["scale"]["domain"] == ["Ma chaîne", "Seconde chaîne"] one = preview({"x": "publish_date", "y": "views", "type": "line", "channels": [OTHER]}) assert one["n"] == 10 and one["resolved"]["split"] is None merged = preview({"x": "publish_date", "y": "views", "type": "line", "split_channels": False}) assert merged["resolved"]["split"] is None # enregistré tel quel r = app_client.post("/api/charts", json={"config": {"x": "views", "y": "likes", "channels": [CH]}}, headers={"Origin": ORIGIN}) assert r.status_code == 201 and r.json()["config"]["channels"] == [CH] rendered = app_client.get(f"/api/charts/{r.json()['id']}/render").json() assert rendered["n"] == 10 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 chart_catalog.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_defaults_on_page_and_share(app_client, clean_db): seed_videos(clean_db["owner"]) login(app_client) cfg = {"x": "publish_date", "y": "views", "type": "scatter", "split_channels": False, "defaults": {"filters": {"views": {"min": 10000, "max": 20000}}}} out = preview(app_client, cfg) assert out["n"] == 11 and out["controls"]["active"] == {"views": {"min": 10000, "max": 20000}} assert out["controls"]["defaults"] == cfg["defaults"] assert preview(app_client, cfg, {"filters": {}})["n"] == 30 # vue de la page : sans filtre cid = app_client.post("/api/charts", json={"config": cfg}, headers={"Origin": ORIGIN}).json()["id"] saved = next(c for c in app_client.get("/api/charts").json() if c["id"] == cid)["config"] assert saved["defaults"] == cfg["defaults"] assert app_client.get(f"/api/charts/{cid}/render").json()["n"] == 11 token = app_client.post(f"/api/charts/{cid}/share", headers={"Origin": ORIGIN}).json()["url"].rsplit("/", 1)[1] shared = app_client.post(f"/shared/{token}/render", json={"view": None}, headers={"Origin": ORIGIN}).json() assert shared["n"] == 11 and shared["controls"]["defaults"] == cfg["defaults"] plain = preview(app_client, {**cfg, "defaults": {}}) assert plain["n"] == 30 and plain["controls"]["defaults"] is None def test_period_check_endpoint(app_client, clean_db): # noqa: F811 (fixture) login(app_client) out = app_client.get("/api/period", params={"when": "$date € $A-1"}).json() year = datetime.fromisoformat(out["now"]).year assert out == {"text": f"sorties en {year - 1}", "relative": True, "now": out["now"], "from": f"{year - 1}-01-01 00:00:00", "to": f"{year}-01-01 00:00:00"} bad = app_client.get("/api/period", params={"when": "$date ~ $A"}) assert bad.status_code == 400 and "inattendu" in bad.json()["error"] def test_saved_and_reopened(app_client, clean_db): # noqa: F811 (fixture) seed_videos(clean_db["owner"]) login(app_client) h = {"Origin": ORIGIN} cfg = {"x": "weekday", "y": "views", "y_more": ["views"], "type": "bar", "aggs": [{"op": "median"}, {"op": "mean", "limit": {"last": 2, "when": "$date >= 2026-09-05"}}]} cid = app_client.post("/api/charts", json={"config": cfg}, headers=h).json()["id"] saved = next(c for c in app_client.get("/api/charts").json() if c["id"] == cid)["config"] assert saved["aggs"] == cfg["aggs"] and saved["y_more"] == ["views"] and "agg" not in saved out = app_client.post(f"/api/charts/{cid}/render", json={}, headers=h).json() recs = out["spec"]["data"]["values"] limited = [r for r in recs if r["s"].startswith("Vues à 7 j (moyenne")] assert limited and all(r["id"] >= "vid00000004" for r in limited) # sorties depuis le 05/09/2026 assert max(sum(1 for r in limited if r["x"] == d) for d in {r["x"] for r in limited}) <= 2 assert multi.series_of(multi.j7_ordinates(chart_config.validate_config(saved), None))["views"][0] == "Vues à 7 j (médiane)"