shortstats/tests/test_multi_y.py
ploush 8fb8179907
All checks were successful
build / test (push) Successful in 3m26s
build / images (collector) (push) Successful in 19s
build / images (web) (push) Successful in 17s
Upgrade 1.2.1
2026-11-01 19:38:28 +01:00

140 lines
7.5 KiB
Python

"""Plusieurs ordonnées (1.2.1) : au plus 2 catégories, autant de moments que voulu."""
import itertools
import json
import os
import psycopg
import pytest
from shortstats.web import charts
from .test_charts import fake_rows
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_MULTI")
_dumped: list = []
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": ["comment_likes"]},
{"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"]},
]
for raw in ok:
assert len(charts.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 à J+7
({"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": "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": "step", "y": "views", "y_more": ["likes"], "type": "boxplot"}, "une seule"),
]
for raw, msg in bad:
with pytest.raises(charts.ChartError, match=msg):
charts.validate_config(raw)
# doublons et répétition de l'ordonnée principale retirés ; ancien format sans y_more accepté
cfg = charts.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 charts.validate_config({"x": "views", "y": "likes"}).y_more == ()
assert charts.compatible_types("weekday", "views", multi=True)["boxplot"]
def multi_rows(cfg, n=30, names=("Chaîne A", "Chaîne B")):
base = fake_rows(charts.ChartConfig(x=cfg.x, y="views"), n)
out = []
for i, r in enumerate(base):
extras = tuple(None if (i + j) % 7 == 0 else (r[3] or 1) * (j + 2) for j in range(len(cfg.y_more)))
out.append((r[0], r[1], r[2], r[3], names[i % len(names)], *extras))
return out
SPEC_X = ["publish_date", "views", "weekday", "theme", "publish_hour", "title", "channel"]
@pytest.mark.parametrize("x,ys,ctype,individual,split", [
(x, ys, t, ind, sp)
for x in SPEC_X
for ys in (["views@6", "views@8"], ["views@6", "views@8", "likes@6"], ["views", "duration"])
for t in ("auto", "scatter", "line", "bar")
for ind in (False, True) for sp in (False, True)
if charts.multi_incompatibility(t, charts.field(x).kind) is None or t == "auto"
])
def test_every_multi_combination_builds(x, ys, ctype, individual, split):
cfg = charts.validate_config({"x": x, "y": ys[0], "y_more": ys[1:], "type": ctype, "split_channels": split})
out = charts.build(cfg, multi_rows(cfg), ["Chaîne A", "Chaîne B"], charts.View(individual=individual))
spec = out["spec"]
assert spec is not None
body = spec.get("spec", spec)
cats = {charts.y_category(k) for k in ys}
assert len(body["layer"]) == len(cats)
if len(cats) == 2:
assert body["resolve"] == {"scale": {"y": "independent"}}
assert body["layer"][1]["encoding"]["y"]["axis"]["orient"] == "right"
assert "axe de droite" in out["explanation"]
assert ("facet" in spec) == (split and x != "channel")
assert {r["s"] for r in spec["data"]["values"]} <= {charts.field(k).label for k in ys}
json.dumps(spec)
if DUMP:
_dumped.append({"name": f"{x}/{ys}/{ctype}/{individual}/{split}", "spec": spec})
def test_series_keep_their_own_values():
cfg = charts.validate_config({"x": "publish_date", "y": "views@6", "y_more": ["likes@6"]})
rows = [("v1", "A", "2026-10-01", 100, "Ch", None), ("v2", "B", "2026-10-02", None, "Ch", 7),
("v3", "C", "2026-10-03", None, "Ch", None)]
out = charts.build(cfg, rows, ["Ch"])
recs = out["spec"]["data"]["values"]
assert [(r["id"], r["s"], r["y"]) for r in recs] == [("v1", "Vues à 6 h", 100), ("v2", "Likes à 6 h", 7)]
assert out["n"] == 2 and out["excluded"] == 1
def test_multi_api_j7_and_evolution(evo, 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 = 5000, like_count = 100, author_comment_status = 'not_found'
WHERE video_id IN ('evo00000010', 'evo00000011')""")
out = preview(evo, {"x": "publish_date", "y": "views@6", "y_more": ["views@8", "views"], "split_channels": False})
series = {r["s"] for r in out["spec"]["data"]["values"]}
assert series == {"Vues à 6 h", "Vues à 12 h", "Vues à J+7"}
j7_points = [r for r in out["spec"]["data"]["values"] if r["s"] == "Vues à J+7"]
assert len(j7_points) == 2 # seules les vidéos relevées à J+7 ont cette série
assert out["n"] == 12 # mais toutes comptent pour 6 h
two = preview(evo, {"x": "views@6", "y": "views@8", "y_more": ["likes@6", "likes@8"]})
assert len(two["spec"].get("spec", two["spec"])["layer"]) == 2
assert two["controls"]["filters"] and two["controls"]["x_filter"] == "views@6"
r = evo.post("/api/preview", json={"config": {"x": "publish_date", "y": "views", "y_more": ["likes", "comments"]}},
headers={"Origin": ORIGIN})
assert r.status_code == 400 and "2 catégories" in r.json()["error"]
agg = preview(evo, {"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"]})
body = agg["spec"].get("spec", agg["spec"])
assert len(body["layer"]) == 2 and agg["resolved"]["series"] == ["Vues", "Likes"]
each = preview(evo, {"source": "evolution", "x": "age", "y": "views", "y_more": ["likes"], "split_channels": False},
{"individual": True})
body = each["spec"]
assert body["layer"][0]["encoding"]["detail"] == {"field": "id"} and "une courbe par vidéo" in each["explanation"]
assert {r["s"] for r in body["data"]["values"]} == {"Vues", "Likes"}
compat = evo.get("/api/compat?x=weekday&y=views&multi=1").json()
assert compat["boxplot"] and compat["bar"] is None
assert evo.get("/api/compat?x=step&y=views&source=evolution&multi=1").json()["boxplot"]
# enregistré avec ses ordonnées supplémentaires
cid = evo.post("/api/charts", json={"config": {"x": "publish_date", "y": "views@6", "y_more": ["likes@6"]}},
headers={"Origin": ORIGIN}).json()["id"]
saved = evo.get("/api/charts").json()[0]["config"]
assert saved["y_more"] == ["likes@6"] and evo.get(f"/api/charts/{cid}/render").json()["spec"]
if DUMP:
for o in (out, two, agg, each):
_dumped.append({"name": "api", "spec": o["spec"]})
def teardown_module(_module):
if DUMP and _dumped:
with open(DUMP, "w") as fh:
json.dump(_dumped, fh)