shortstats/tests/test_v132.py
ploush af13dc6a44
All checks were successful
build / test (push) Successful in 6m43s
build / images (collector) (push) Successful in 20s
build / images (web) (push) Successful in 17s
upgrade 1.3.2
2026-11-15 15:45:28 +01:00

307 lines
18 KiB
Python

"""Version 1.3.2 : formes des vidéos mises en avant, axes du temps réguliers,
heures et jours sans vidéo."""
from __future__ import annotations
import json
import math
from shortstats import __version__
from shortstats.web import charts, evolution, highlight
from .test_charts import fake_rows
from .test_evolution import evo, preview # noqa: F401 (fixtures)
from .test_web import app_client, users_file # noqa: F401 (fixtures)
def test_version():
assert __version__ == "1.3.2"
# -- 1. la vidéo mise en avant n'a plus de rond sous sa forme ---------------------------
def _scatter():
cfg = charts.validate_config({"x": "views", "y": "likes", "type": "scatter", "split_channels": False})
return charts.build(cfg, fake_rows(cfg))
def test_highlighted_video_drawn_once_with_its_shape():
res = _scatter()
recs = [{"id": "vid00000003", "t": "Short n°3", "x": 548, "y": 548, "hl": 1, "hn": "Short n°3"}]
highlight.decorate(res, recs, "point", videos=[{"label": "Short n°3", "shape": "triangle-up", "dash": "solid"}])
main, hl = res["spec"]["layer"]
# la couche principale écarte la vidéo mise en avant : seul son triangle est dessiné
assert {"filter": {"not": {"field": "id", "oneOf": ["vid00000003"]}}} in main["transform"]
assert hl["encoding"]["shape"]["scale"]["range"] == ["triangle-up"]
assert not any(t["filter"] == {"not": {"field": "id", "oneOf": ["vid00000003"]}} for t in hl["transform"])
def test_own_points_only_for_unaggregated_layers():
point = {"mark": {"type": "point"}, "encoding": {"x": {"field": "x"}, "y": {"field": "y"}}}
each = {"mark": {"type": "line"}, "encoding": {"detail": {"field": "id"}}}
median = {"mark": {"type": "line"}, "encoding": {"y": {"field": "y", "aggregate": "median"}}}
bars = {"mark": "bar", "encoding": {}}
assert highlight._own_points(point) and highlight._own_points(each)
assert not highlight._own_points(median) and not highlight._own_points(bars)
# -- 2. axes du temps : même espacement, même durée ----------------------------------
def test_age_axis_linear_and_regular():
for lo, hi in [(1, 24), (1, 36), (1, 168), (1, 720), (24, 8766), (1, 26298), (730.5, 26298), (5, 5)]:
scale, axis = evolution.age_axis(lo, hi)
assert scale["type"] == "linear" and scale["nice"] is False
d0, d1 = scale["domain"]
assert d0 <= lo and d1 >= hi
ticks = axis["values"]
assert 2 <= len(ticks) <= evolution.AGE_MAX_TICKS + 1, (lo, hi, ticks)
gaps = {round(b - a, 6) for a, b in zip(ticks, ticks[1:])}
assert len(gaps) == 1, (lo, hi, ticks) # graduations régulières
assert all(d0 - 1e-6 <= t <= d1 + 1e-6 for t in ticks)
assert evolution.age_axis(1, 24)[0]["domain"][0] == 0 # depuis la sortie
assert evolution.age_axis(8766, 26298)[0]["domain"][0] == 8766 # plage tardive : au 1er relevé
def test_age_axis_labels():
def labels(lo, hi):
_, axis = evolution.age_axis(lo, hi)
return dict(zip(axis["values"], json.loads(axis["labelExpr"].split("[indexof(")[0])))
assert labels(1, 24)[12] == "12 h"
assert labels(1, 36)[30] == "1 j 6 h"
assert labels(1, 168)[48] == "2 j"
assert labels(1, 26298)[8766] == "12 mois" and labels(1, 26298)[0] == "0"
assert labels(1, 80000)[17532] == "2 ans" and labels(1, 80000)[8766] == "1 an"
assert labels(1, 4000)[2191.5] == "3 mois"
def test_step_cells_follow_durations():
hours = [1, 2, 3, 24, 27, 30, 168, 336]
recs = [{"x": float(h), "c": c} for h in hours for c in ("A", "B")]
evolution.step_cells(recs, "c")
by = {(r["x"], r["c"]): r for r in recs}
for h in hours:
a, b = by[(h, "A")], by[(h, "B")]
assert a["x0"] < a["x1"] <= b["x0"] < b["x1"] # côte à côte, A puis B
assert math.isclose(a["x1"] - a["x0"], b["x1"] - b["x0"])
# largeur proportionnelle à la durée couverte par l'étape ; jamais de chevauchement
width = {h: by[(h, "B")]["x1"] - by[(h, "A")]["x0"] for h in hours}
assert width[336] > width[27] > width[2]
edges = sorted((r["x0"], r["x1"]) for r in recs)
assert all(e1 <= f0 + 1e-9 for (_, e1), (f0, _) in zip(edges, edges[1:]))
# ordre imposé (jours de la semaine) et lignes concernées seulement
recs = [{"x": 1.0, "c": "Mardi"}, {"x": 1.0, "c": "Lundi"}, {"x": 2.0, "c": "Lundi", "skip": True}]
evolution.step_cells(recs, "c", charts.WEEKDAYS, only=lambda r: not r.get("skip"))
assert recs[1]["x0"] < recs[0]["x0"] and "x0" not in recs[2]
def test_publish_date_groups_on_time_axis():
for ctype in ("bar", "heatmap"):
cfg = charts.validate_config({"x": "publish_date", "y": "views" if ctype != "heatmap" else "weekday",
"type": ctype, "split_channels": False})
x = charts.build(cfg, fake_rows(cfg, 80))["spec"]["encoding"]["x"]
assert x["type"] == "temporal" and x["timeUnit"]["unit"] in {"yearmonthdate", "yearweek", "yearmonth"}
assert x["scale"] == {"type": "utc"}, ctype
def test_line_over_date_bars_is_centered():
cfg = charts.validate_config({"x": "publish_date", "y": "views", "y_more": ["likes"], "type": "bar",
"type2": "line", "split_channels": False})
from .test_multi_y import multi_rows
bars, line = charts.build(cfg, multi_rows(cfg), None, None)["spec"]["layer"]
assert "bandPosition" not in bars["encoding"]["x"] and line["encoding"]["x"]["bandPosition"] == 0.5
# -- 3. heures et jours sans vidéo --------------------------------------------------
def test_every_hour_and_day_on_the_axis():
for x, domain in (("publish_hour", list(range(24))), ("weekday", charts.WEEKDAYS)):
for ctype in ("bar", "line", "boxplot", "scatter"):
cfg = charts.validate_config({"x": x, "y": "views", "type": ctype, "split_channels": False})
rows = [r for r in fake_rows(cfg) if r[2] not in (3, "Mercredi")] # une heure, un jour vides
assert charts.build(cfg, rows)["spec"]["encoding"]["x"]["scale"]["domain"] == domain, (x, ctype)
cfg = charts.validate_config({"x": "views", "y": "publish_hour", "type": "bar", "split_channels": False})
assert charts.build(cfg, fake_rows(cfg))["spec"]["encoding"]["y"]["scale"]["domain"] == list(range(24))
cfg = charts.validate_config({"x": "publish_hour", "y": "weekday", "type": "heatmap", "split_channels": False})
enc = charts.build(cfg, fake_rows(cfg))["spec"]["encoding"]
assert enc["x"]["scale"]["domain"] == list(range(24)) and enc["y"]["scale"]["domain"] == charts.WEEKDAYS
def test_count_line_drops_to_zero_on_empty_hours():
cfg = charts.validate_config({"x": "publish_hour", "y": "count", "type": "line", "color": "weekday",
"split_channels": False})
spec = charts.build(cfg, fake_rows(cfg))["spec"]
count, impute = spec["transform"]
assert count == {"aggregate": [{"op": "count", "as": "n_videos"}], "groupby": ["x", "c"]}
assert impute == {"impute": "n_videos", "key": "x", "keyvals": list(range(24)), "groupby": ["c"], "value": 0}
assert spec["encoding"]["y"]["field"] == "n_videos" and "aggregate" not in spec["encoding"]["y"]
# mesure (vues) : pas de comptage, une heure vide reste sans valeur
cfg = charts.validate_config({"x": "publish_hour", "y": "views", "type": "line", "split_channels": False})
assert "transform" not in charts.build(cfg, fake_rows(cfg))["spec"]
# vidéo mise en avant sur un comptage : un trait à son heure, filtrée avant le comptage
cfg = charts.validate_config({"x": "weekday", "y": "count", "type": "line", "split_channels": False})
res = charts.build(cfg, fake_rows(cfg))
highlight.decorate(res, [{"id": "vid00000001", "t": "Short n°1", "x": "Mardi", "y": 1, "hl": 1, "hn": "S"}],
"point", videos=[{"label": "S", "shape": "diamond", "dash": "solid"}])
main, hl = res["spec"]["layer"]
assert main["transform"][0] == {"filter": highlight.MAIN} and "impute" in main["transform"][2]
assert hl["mark"]["type"] == "rule" and "y" not in hl["encoding"]
# -- 4. style des points et courbes ---------------------------------------------------
from shortstats.web import marks # noqa: E402
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 charts.ChartError:
continue
raise AssertionError(bad)
cfg = charts.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 charts.validate_config(cfg.to_dict()) == cfg # aller-retour (enregistrement, export)
assert "marks" not in charts.validate_config({"x": "views", "y": "likes"}).to_dict()
evo_cfg = charts.validate_config({"source": "evolution", "x": "age", "y": "views", "marks": {"point": "small"}})
assert evo_cfg.marks == {"point": "small"}
def test_style_applies_to_points_and_lines():
style = {"shape": "diamond", "point": "large", "line": "thick"}
point = marks.style_mark({"type": "point", "filled": True, "size": 60}, style)
assert point["shape"] == "diamond" and point["size"] == round(60 * 1.4 * 1.4, 1)
line = marks.style_mark({"type": "line", "point": {"filled": True, "size": 45}, "strokeWidth": 2}, style)
assert line["strokeWidth"] == 3.2 and line["point"] == {"filled": True, "size": 88.2, "shape": "diamond"}
each = marks.style_mark({"type": "line", "strokeWidth": 1.3, "point": {"size": 16}}, {"line": "thin"})
assert each["strokeWidth"] == 0.78 and each["point"] == {"size": 16} # points inchangés
assert marks.style_mark({"type": "line"}, {"line": "xthick"})["strokeWidth"] == 4.8 # épaisseur du thème : 2
# axe de droite (carrés) : reste distinct de l'axe de gauche
assert marks.style_mark({"type": "point", "size": 60, "shape": "square"}, {"shape": "diamond"})["shape"] == "square"
assert marks.style_mark({"type": "point", "size": 60, "shape": "square"}, {"shape": "square"})["shape"] == "circle"
# barres, boîtes et vidéos mises en avant : jamais touchées
for mark in ({"type": "bar"}, {"type": "boxplot"}, {"type": "point", "size": 120, "style": "hl-point"},
{"type": "line", "strokeWidth": 2.5, "style": "hl-line"}):
assert marks.style_mark(mark, style) == mark
def test_style_on_built_charts():
style = {"shape": "triangle-up", "point": "small", "line": "thick"}
res = _scatter()
marks.apply(res, style)
assert res["spec"]["mark"]["shape"] == "triangle-up" and res["spec"]["mark"]["size"] == round(60 * 0.49, 1)
# deux ordonnées en points : gauche en triangles, droite en carrés
from .test_multi_y import multi_rows
cfg = charts.validate_config({"x": "views", "y": "likes", "y_more": ["comments"], "type": "scatter",
"split_channels": False})
res = charts.build(cfg, multi_rows(cfg), None, None)
marks.apply(res, style)
assert [layer["mark"]["shape"] for layer in res["spec"]["layer"]] == ["triangle-up", "square"]
# petits diagrammes par chaîne : le style vaut pour chacun
cfg = charts.validate_config({"x": "publish_date", "y": "views", "type": "line", "split_channels": True})
rows = [r + (("Chaîne A", "Chaîne B")[i % 2],) for i, r in enumerate(fake_rows(cfg))]
res = charts.build(cfg, rows, None, None)
marks.apply(res, style)
body = res["spec"].get("spec", res["spec"])
assert body["mark"]["strokeWidth"] == 3.2 and body["mark"]["point"]["shape"] == "triangle-up"
def test_highlight_size():
assert highlight.validate([{"rank": "views", "n": 1, "size": "large"}]) == ({"rank": "views", "n": 1,
"size": "large"},)
assert highlight.validate([{"rank": "views", "n": 1, "size": "normal"}]) == ({"rank": "views", "n": 1},)
try:
highlight.validate([{"rank": "views", "n": 1, "size": "géante"}])
raise AssertionError("taille inconnue acceptée")
except charts.ChartError as exc:
assert "taille inconnue" in str(exc)
assert highlight.catalog()["sizes"]["xlarge"] == "Très grande"
recs = [{"id": "vid00000003", "t": "A", "x": 548, "y": 548, "hl": 1, "hn": "A"},
{"id": "vid00000005", "t": "B", "x": 822, "y": 822, "hl": 2, "hn": "B"}]
videos = [{"label": "A", "shape": "triangle-up", "dash": "solid", "size": "xlarge"},
{"label": "B", "shape": "square", "dash": "solid", "size": "small"}]
res = _scatter()
highlight.decorate(res, recs, "point", videos=videos)
hl = [layer for layer in res["spec"]["layer"] if layer["mark"].get("style") == "hl-point"]
# une couche par taille, chacune filtrée sur ses vidéos ; mêmes échelles de forme (une seule légende)
assert [layer["mark"]["size"] for layer in hl] == [round(120 * 1.9 * 1.9, 1), round(120 * 0.49, 1)]
assert [layer["transform"][-1]["filter"] for layer in hl] == [{"field": "hl", "oneOf": [1]},
{"field": "hl", "oneOf": [2]}]
assert hl[0]["encoding"]["shape"] == hl[1]["encoding"]["shape"]
# même taille pour toutes : une seule couche, comme avant
res = _scatter()
highlight.decorate(res, recs, "point", videos=[{**v, "size": "large"} for v in videos])
hl = [layer for layer in res["spec"]["layer"] if layer["mark"].get("style") == "hl-point"]
assert len(hl) == 1 and all("oneOf" not in t["filter"] for t in hl[0]["transform"])
# courbe : taille du point et épaisseur du trait indépendantes
xy = {"x": {"field": "x", "type": "quantitative"}, "y": {"field": "y", "type": "quantitative"}}
st = {"domain": ["A"], "shapes": ["diamond"], "dashes": [[1, 0]]}
big_point = highlight._hl_layers(xy, "path", {**st, "sizes": {("large", "normal"): [1]}})[0]["mark"]
assert big_point["strokeWidth"] == 2.5 and big_point["point"]["size"] == 137.2
thick = highlight._hl_layers(xy, "path", {**st, "sizes": {("normal", "xthick"): [1]}})[0]["mark"]
assert thick["strokeWidth"] == 6.0 and thick["point"]["size"] == 70.0
# trait vertical (nombre de vidéos) : son épaisseur seule
rule = highlight._hl_layers({"x": {"field": "x", "type": "quantitative"}}, "point",
{**st, "sizes": {("xlarge", "thin"): [1]}})[0]["mark"]
assert rule["type"] == "rule" and rule["strokeWidth"] == 1.2
def test_highlight_width_independent_of_size():
assert highlight.validate([{"rank": "views", "n": 1, "width": "thick", "size": "small"}]) == (
{"rank": "views", "n": 1, "size": "small", "width": "thick"},)
assert highlight.validate([{"rank": "views", "n": 1, "width": "normal"}]) == ({"rank": "views", "n": 1},)
try:
highlight.validate([{"rank": "views", "n": 1, "width": "large"}]) # une taille, pas une épaisseur
raise AssertionError("épaisseur inconnue acceptée")
except charts.ChartError as exc:
assert "épaisseur inconnue" in str(exc)
assert highlight.catalog()["widths"]["xthick"] == "Très épaisse"
# même taille de point, épaisseurs différentes : deux couches
recs = [{"id": "vid00000003", "t": "A", "x": 548, "y": 548, "hl": 1, "hn": "A"},
{"id": "vid00000005", "t": "B", "x": 822, "y": 822, "hl": 2, "hn": "B"}]
st = highlight._styles([{"label": "A", "shape": "diamond", "dash": "solid", "size": "large", "width": "thin"},
{"label": "B", "shape": "square", "dash": "solid", "size": "large"}], recs)
assert st["sizes"] == {("large", "thin"): [1], ("large", "normal"): [2]}
def test_styles_through_the_api(evo): # noqa: F811 (fixture)
hl = [{"rank": "views", "n": 1, "size": "xlarge", "width": "xthick"}, {"video": "evo00000003", "title": "Évolution 3"}]
cfg = {"source": "evolution", "x": "age", "y": "views", "split_channels": False, "highlight": hl,
"marks": {"shape": "diamond", "point": "large", "line": "thick"}}
out = preview(evo, cfg)
layers = out["spec"]["layer"]
main = layers[0]["mark"]
assert main["strokeWidth"] == 3.2 and main["point"]["shape"] == "diamond"
hl_lines = [layer["mark"] for layer in layers if layer["mark"].get("style") == "hl-line"]
assert sorted(m["strokeWidth"] for m in hl_lines) == [2.5, 6.0] # normale, très épaisse
assert sorted(m["point"]["size"] for m in hl_lines) == [70.0, 252.7] # normal, très grand
assert [(i["size"], i["width"]) for i in out["controls"]["highlight"]["items"]] == [("xlarge", "xthick"),
("normal", "normal")]
assert out["controls"]["highlight"]["sizes"]["small"] == "Petite"
# enregistré tel quel, relu par le tableau de bord
cid = evo.post("/api/charts", json={"config": cfg}, headers={"Origin": "http://testserver"}).json()["id"]
saved = next(c for c in evo.get("/api/charts").json() if c["id"] == cid)["config"]
assert saved["marks"] == cfg["marks"] and saved["highlight"][0]["size"] == "xlarge"
assert evo.get("/api/catalog").json()["marks"]["lines"]["xthick"] == "Très épaisse"
bad = preview(evo, {**cfg, "marks": {"shape": "étoile"}}, status=400)
assert "Style des points et courbes" in bad["error"]
# -- 5. « Étape du relevé » remplacée par « Âge de la vidéo » -------------------------
def test_step_axis_read_as_age():
assert "step" not in evolution.X_FIELDS
for raw, x, y in [({"x": "step", "y": "views", "type": "boxplot"}, "age", "views"),
({"x": "views", "y": "step"}, "views", "age")]:
cfg = charts.validate_config({"source": "evolution", **raw})
assert (cfg.x, cfg.y) == (x, y) and cfg.to_dict()[next(k for k in ("x", "y") if raw[k] == "step")] == "age"
# barres et boîtes : avec l'âge (l'étape seule les permettait jusqu'ici)
compat = evolution.compatible_types("age")
assert compat["bar"] is None and compat["boxplot"] is None
assert evolution.compatible_types("step") == compat
assert "Âge de la vidéo" in evolution.compatible_types("snapshot_date")["bar"]