"""1.3.0 : analyse thématique de tous les commentaires, à chaque relevé, et toute donnée sur les deux axes.""" import json import os import psycopg import pytest from shortstats.web import charts, evolution, transpose from .test_evolution import evo, preview, seed_snapshots # noqa: F401 (fixtures) from .test_web import ORIGIN, app_client, login, users_file # noqa: F401 DUMP = os.environ.get("DUMP_SPECS_V130") _dumped: list = [] THEMES = {"Apothecary Diaries", "applepie"} def show(c, config, view=None, status=200): out = preview(c, config, view, status) if DUMP and status == 200 and out.get("spec"): _dumped.append({"name": json.dumps([config, view]), "spec": out["spec"]}) return out @pytest.fixture() def themed(evo): """evo00000000 à 11 : relevés de 1 h à 30 h, commentaires lus et comptes par thème (seed_snapshots).""" return evo def values(out, key): return [r[key] for r in out["spec"]["data"]["values"] if "hl" not in r] def db_rates(owner_url, sid): """{(vidéo, thème): taux} à l'étape sid, calculés directement en base.""" with psycopg.connect(owner_url) as conn: rows = conn.execute( """SELECT sn.video_id, t.name, 100.0 * coalesce(sth.comments, 0) / sn.comments_read FROM shortstats.video_snapshot sn CROSS JOIN shortstats.theme t LEFT JOIN shortstats.snapshot_theme sth ON sth.video_id = sn.video_id AND sth.step_id = sn.step_id AND sth.theme_id = t.theme_id WHERE sn.step_id = %s AND sn.comments_read > 0""", (sid,)).fetchall() return {(r[0], r[1]): float(r[2]) for r in rows} def test_catalog_and_labels(evo): cat = evo.get("/api/catalog").json() labels = {f["key"]: f["label"] for f in cat["fields"]} assert labels["theme"] == "Thème des commentaires" and labels["views"] == "Vues à 7 j" assert not {"theme_each", "comment_likes"} & set(labels) measures = {m["key"]: m for m in cat["step_measures"]} assert measures["theme_rate"]["theme"] and measures["theme_comments"]["theme"] assert not measures["comments_read"]["theme"] and not measures["comments_read"]["j7"] assert cat["theme_key"] == "theme" assert [f["key"] for f in cat["evolution"]["color"]] == ["channel", "theme", "weekday", "publish_hour"] ys = {f["key"]: f["label"] for f in cat["evolution"]["y"]} assert ys["theme_rate"] == "Taux du thème (% des commentaires lus)" and ys["comments_read"] == "Commentaires lus" assert charts.field("theme_rate@6").label == "Taux du thème à 6 h (% des commentaires lus)" assert charts.field("theme_comments@56").label == "Commentaires du thème à 7 j" def test_validation_rules(): ok = charts.validate_config({"x": "theme", "y": "theme_rate@56"}) assert ok.color is None auto = charts.validate_config({"x": "views@56", "y": "theme_rate@56"}) assert auto.color == "theme" # couleur libre : un thème par couleur evo_auto = charts.validate_config({"source": "evolution", "x": "step", "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": "step", "y": "theme_rate", "type": "boxplot"}, "Boîte à moustaches"), ({"source": "evolution", "x": "step", "y": "theme_rate", "color": "channel"}, "thème par thème"), ({"source": "evolution", "x": "step", "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": "step", "y": "views", "color": "theme_each"}, "commentaire épinglé"), ] for raw, msg in bad: with pytest.raises(charts.ChartError, match=msg): charts.validate_config(raw) # boîtes à moustaches par thème : avec le thème en abscisse assert charts.validate_config({"x": "theme", "y": "theme_rate@6", "type": "boxplot"}).type == "boxplot" def test_bars_per_theme(themed, clean_db): """Thèmes en abscisse, taux moyen en ordonnée (à une étape).""" out = show(themed, {"x": "theme", "y": "theme_rate@6", "type": "bar", "split_channels": False}) xs = values(out, "x") assert sorted(xs) == sorted(["Apothecary Diaries"] * 12 + ["applepie"] * 12) assert "12 vidéo(s)" in out["explanation"] and charts.THEME_NOTE in out["explanation"] enc = out["spec"]["encoding"] assert enc["x"]["title"] == "Thème des commentaires" and enc["y"]["aggregate"] == "mean" assert enc["y"]["title"].startswith("Taux du thème à 6 h (% des commentaires lus)") expected = db_rates(clean_db["owner"], 6) got = {(r["id"], r["x"]): r["y"] for r in out["spec"]["data"]["values"]} assert got.keys() == expected.keys() assert all(abs(got[k] - expected[k]) < 0.001 for k in got) # nombre de commentaires du thème : 0 compris (pas seulement les vidéos qui en ont) counts = show(themed, {"x": "theme", "y": "theme_comments@6", "split_channels": False}) assert len(values(counts, "y")) == 24 and 0 in values(counts, "y") # en ordonnée aussi (barres horizontales) horiz = show(themed, {"x": "theme_rate@6", "y": "theme", "type": "bar", "split_channels": False}) assert horiz["spec"]["encoding"]["y"]["type"] == "nominal" and set(values(horiz, "y")) == THEMES # boîtes par thème box = show(themed, {"x": "theme", "y": "theme_rate@6", "type": "boxplot", "split_channels": False}) assert box["resolved"]["type"] == "boxplot" # deux moments : une barre par moment pour chaque thème two = show(themed, {"x": "theme", "y": "theme_rate@6", "y_more": ["theme_rate@24"], "split_channels": False}) assert {r["s"] for r in two["spec"]["data"]["values"]} == {"Taux du thème à 6 h (% des commentaires lus)", "Taux du thème à 24 h (% des commentaires lus)"} def test_theme_measure_against_another_measure(themed): out = show(themed, {"x": "views@6", "y": "theme_rate@6", "split_channels": False}) assert out["resolved"]["type"] == "scatter" and set(values(out, "c")) == THEMES assert out["spec"]["encoding"]["color"]["title"] == "Thème des commentaires" hist = show(themed, {"x": "theme_rate@6", "y": "count", "split_channels": False}) assert hist["resolved"]["type"] == "histogram" and set(values(hist, "c")) == THEMES by_day = show(themed, {"x": "weekday", "y": "theme_rate@6", "split_channels": False}) assert by_day["resolved"]["type"] == "bar" and by_day["spec"]["encoding"]["xOffset"]["field"] == "c" # commentaires lus (pas une mesure de thème) : une valeur par vidéo, sans thème read = show(themed, {"x": "views@6", "y": "comments_read@6", "split_channels": False}) assert len(values(read, "y")) == 12 and "color" not in read["spec"]["encoding"] def test_theme_filter(themed): base = {"x": "views@6", "y": "theme_rate@6", "split_channels": False} out = show(themed, base, {"filters": {"theme": {"in": ["applepie"]}}}) assert set(values(out, "c")) == {"applepie"} and len(values(out, "c")) == 12 ctl = {f["key"]: f for f in out["controls"]["filters"]} assert ctl["theme"]["values"] == ["Apothecary Diaries", "applepie"] assert "theme_rate@6" in ctl and "theme" not in {f["key"] for f in show( themed, {"x": "views@6", "y": "likes@6", "split_channels": False})["controls"]["filters"]} def test_curves_per_theme_over_steps(themed, clean_db): """Le cas demandé : étapes en abscisse, taux moyen de chaque thème en ordonnée.""" out = show(themed, {"source": "evolution", "x": "step", "y": "theme_rate", "agg": "mean", "split_channels": False}) recs = out["spec"]["data"]["values"] assert {r["c"] for r in recs} == THEMES and out["spec"]["encoding"]["color"]["field"] == "c" assert "moyenne par étape" in out["explanation"] and evolution.THEME_SNAP_NOTE in out["explanation"] first = {r["c"]: r for r in recs if r["lab"] == "6 h"} assert {c: r["n"] for c, r in first.items()} == {"Apothecary Diaries": 12, "applepie": 12} expected = db_rates(clean_db["owner"], 6) for theme in THEMES: mean = sum(v for (vid, t), v in expected.items() if t == theme) / 12 assert abs(first[theme]["y"] - mean) < 0.001 assert out["controls"]["individual"]["available"] is False # nombre de commentaires du thème, à l'âge réel ; commentaires lus (sans thème) counts = show(themed, {"source": "evolution", "x": "age", "y": "theme_comments", "split_channels": False}) assert {r["c"] for r in counts["spec"]["data"]["values"]} == THEMES read = show(themed, {"source": "evolution", "x": "step", "y": "comments_read", "split_channels": False}) assert "c" not in read["spec"]["data"]["values"][0] # barres par étape, une par thème bars = show(themed, {"source": "evolution", "x": "step", "y": "theme_rate", "type": "bar", "split_channels": False}) assert bars["resolved"]["type"] == "bar" # filtre par thème ; « chaque vidéo » sans effet avec les thèmes only = show(themed, {"source": "evolution", "x": "step", "y": "theme_rate", "split_channels": False}, {"filters": {"theme": {"in": ["applepie"]}}, "individual": True}) assert {r["c"] for r in only["spec"]["data"]["values"]} == {"applepie"} and only["resolved"]["mode"] == "agg" # un point par relevé : taux du thème selon les vues pairs = show(themed, {"source": "evolution", "x": "views", "y": "theme_rate", "split_channels": False}) assert pairs["resolved"]["mode"] == "pairs" and {r["c"] for r in pairs["spec"]["data"]["values"]} == THEMES # par chaîne : un diagramme par chaîne (la couleur sert aux thèmes) split = show(themed, {"source": "evolution", "x": "step", "y": "theme_rate"}) assert split["resolved"]["split"] == "facet" show(themed, {"source": "evolution", "x": "step", "y": "theme_rate", "type": "boxplot"}, status=400) def test_highlight_unavailable_with_themes(themed): out = show(themed, {"x": "theme", "y": "theme_rate@6", "highlight": [{"rank": "views", "n": 1}]}) assert "mise en avant des vidéos indisponible avec les thèmes" in out["explanation"] assert not any(r.get("hl") for r in out["spec"]["data"]["values"]) def test_count_on_x_axis(themed, clean_db): with psycopg.connect(clean_db["owner"], autocommit=True) as conn: conn.execute("UPDATE shortstats.video SET status = 'collected', collected_at = now(), view_count = 100") cfg = charts.validate_config({"x": "count", "y": "weekday"}) assert (cfg.x, cfg.y) == ("count", "weekday") and transpose.canonical(cfg).x == "weekday" out = show(themed, {"x": "count", "y": "weekday", "split_channels": False}) enc = out["spec"]["encoding"] assert enc["x"]["aggregate"] == "count" and enc["y"]["field"] == "x" and enc["y"]["type"] == "ordinal" assert out["resolved"]["transposed"] and "axes inversés" in out["explanation"] hist = show(themed, {"x": "count", "y": "views@6", "split_channels": False}) assert "bin" in hist["spec"]["encoding"]["y"] and hist["spec"]["encoding"]["x"]["aggregate"] == "count" assert hist["resolved"]["type"] == "histogram" grouped = show(themed, {"x": "count", "y": "weekday", "color": "channel", "type": "bar", "split_channels": False}) assert "yOffset" in grouped["spec"]["encoding"] and "xOffset" not in grouped["spec"]["encoding"] themed_hist = show(themed, {"x": "count", "y": "theme_rate@6", "split_channels": False}) assert set(values(themed_hist, "c")) == THEMES compat = themed.get("/api/compat?x=count&y=views").json() assert compat["histogram"] is None and compat["scatter"] assert themed.get("/api/compat?x=count&y=count").json()["bar"] for bad, msg in [({"x": "count", "y": "count"}, "Ordonnée invalide"), ({"x": "count", "y": "views", "y_more": ["likes"]}, "une seule ordonnée"), ({"x": "count", "y": "views", "type": "scatter"}, "Nuage de points impossible"), ({"x": "count", "y": "theme"}, "mesure de thème")]: with pytest.raises(charts.ChartError, match=msg): charts.validate_config(bad) def test_time_of_snapshot_on_y_axis(themed): cfg = charts.validate_config({"source": "evolution", "x": "like_rate", "y": "age", "agg": "mean"}) assert (cfg.x, cfg.y, cfg.source) == ("like_rate", "age", "evolution") and not evolution.is_pairs(cfg) out = show(themed, {"source": "evolution", "x": "like_rate", "y": "age", "agg": "mean", "split_channels": False}) enc = out["spec"]["encoding"] assert enc["y"]["title"] == "Âge de la vidéo" and enc["y"]["scale"]["type"] == "log" assert enc["x"]["title"] == "Taux de like (% des vues) (moyenne)" assert out["spec"]["mark"]["orient"] == "horizontal" # relié dans l'ordre des âges assert out["controls"]["x_filter"] == "age" # taux du thème en abscisse, étapes en ordonnée : une courbe par thème rates = show(themed, {"source": "evolution", "x": "theme_rate", "y": "step", "agg": "mean", "split_channels": False}) assert rates["resolved"]["transposed"] and {r["c"] for r in rates["spec"]["data"]["values"]} == THEMES steps = show(themed, {"source": "evolution", "x": "views", "y": "step", "type": "boxplot", "split_channels": False}) layers = steps["spec"]["layer"] assert steps["spec"]["encoding"]["y"]["field"] == "sid" and {"x", "x2"} <= set(layers[0]["encoding"]) assert steps["spec"]["height"] > 320 # une ligne par étape each = show(themed, {"source": "evolution", "x": "views", "y": "age", "split_channels": False}, {"individual": True, "y_axes": [{"min": 0, "max": 5000}]}) assert each["resolved"]["mode"] == "each" and each["controls"]["y_axes"][0]["orient"] == "horizontal" assert each["spec"]["encoding"]["x"]["scale"]["domain"][1] == 5000 # zoom sur l'axe des vues dated = show(themed, {"source": "evolution", "x": "views", "y": "snapshot_date", "type": "bar"}, status=400) assert "Étape du relevé" in dated["error"] for bad, msg in [({"source": "evolution", "x": "step", "y": "age"}, "statistique à toutes les étapes"), ({"source": "evolution", "x": "views", "y": "age", "y_more": ["likes"]}, "une seule abscisse")]: with pytest.raises(charts.ChartError, match=msg): charts.validate_config(bad) compat = themed.get("/api/compat?x=views&y=step&source=evolution").json() assert compat["boxplot"] is None and compat["bar"] is None and compat["scatter"] # enregistrable, rechargé tel quel, avec des vidéos mises en avant r = themed.post("/api/charts", json={"config": {"source": "evolution", "x": "views", "y": "age", "highlight": [{"rank": "views", "n": 1}]}}, headers={"Origin": ORIGIN}) assert r.status_code == 201 and r.json()["config"]["y"] == "age" rendered = themed.get(f"/api/charts/{r.json()['id']}/render").json() assert rendered["resolved"]["transposed"] and any(r.get("hl") for r in rendered["spec"]["data"]["values"]) def test_saved_pinned_chart_reports_clearly(themed, clean_db): """Diagramme enregistré avant la 1.3.0 sur le thème du commentaire épinglé (migration 010).""" from psycopg.types.json import Jsonb with psycopg.connect(clean_db["owner"], autocommit=True) as conn: cid = conn.execute("INSERT INTO shortstats.chart (config, created_by) VALUES (%s, 'alice') RETURNING chart_id", (Jsonb({"x": "pinned_theme", "y": "views"}),)).fetchone()[0] r = themed.get(f"/api/charts/{cid}/render") assert r.status_code == 200 and r.json()["spec"] is None assert "Diagramme à modifier : le thème du commentaire épinglé n'existe plus" in r.json()["explanation"] assert any(c["id"] == cid for c in themed.get("/api/charts").json()) # toujours listé (à modifier) def test_import_of_pinned_exports(): from shortstats.web import transfer old = {"format": transfer.FORMAT, "version": 2, "charts": [ {"x": "publish_date", "y": "views", "color": "theme_each", "defaults": {"filters": {"theme_each": {"in": ["x"]}, "views": {"min": 1}}}}, ]} configs, _ = transfer.parse(json.dumps(old), set()) assert configs[0].color is None and configs[0].defaults == {"filters": {"views": {"min": 1, "max": None}}} with pytest.raises(charts.ChartError, match="Diagramme à modifier"): transfer.parse(json.dumps({**old, "charts": [{"x": "theme", "y": "views"}]}), set()) def test_dump(): if DUMP and _dumped: with open(DUMP, "w") as fh: json.dump(_dumped, fh)