152 lines
9.4 KiB
Python
152 lines
9.4 KiB
Python
"""Vidéos mises en avant : axes qui les couvrent, tailles, rang, découpe."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from shortstats.web import chart_catalog, chart_config, chart_view, chart_zoom, charts, highlight
|
|
|
|
from ..outils.lignes import _scatter, fake_rows, multi_rows
|
|
from ..outils.specs import body_of, keep
|
|
|
|
|
|
def test_highlight_decorate_widens_log_axis():
|
|
cfg = chart_config.validate_config({"x": "views@6", "y": "views", "type": "scatter", "scale": "log",
|
|
"split_channels": False})
|
|
out = charts.build(cfg, fake_rows(cfg))
|
|
top = out["spec"]["encoding"]["y"]["scale"]["domainMax"]
|
|
rec = {"id": "zzz", "t": "Virale", "x": 10, "y": top * 30, "hl": 1, "hn": "Virale", "lbl": True}
|
|
highlight.decorate(out, [rec], "point")
|
|
main = out["spec"]["layer"][0]
|
|
assert main["encoding"]["y"]["scale"]["domainMax"] >= top * 30
|
|
assert main["encoding"]["y"]["axis"]["values"][-1] == main["encoding"]["y"]["scale"]["domainMax"]
|
|
|
|
|
|
def test_slider_and_zoom_cover_highlight():
|
|
cfg = chart_config.validate_config({"x": "views@6", "y": "views", "type": "scatter", "scale": "linear",
|
|
"split_channels": False})
|
|
rows = fake_rows(cfg)
|
|
plain = charts.build(cfg, rows)["resolved"]["y_axes"][0]
|
|
with chart_zoom.extra_y({0: [plain["max"] * 3]}):
|
|
wide = charts.build(cfg, rows)["resolved"]["y_axes"][0]
|
|
# bas resserré, haut laissé : le haut couvre la vidéo (elle n'est pas coupée)
|
|
low = charts.build(cfg, rows, None, chart_view.View(y_axes=((10, None),)))
|
|
assert wide["max"] == plain["max"] * 3 and wide["min"] == plain["min"]
|
|
top = low["spec"]["encoding"]["y"]["scale"]["domain"][1]
|
|
assert top >= plain["max"] * 3
|
|
# hors du contexte : plus rien d'ajouté
|
|
assert charts.build(cfg, rows)["resolved"]["y_axes"][0]["max"] == plain["max"]
|
|
|
|
|
|
def test_extents_by_axis_and_hidden():
|
|
cfg = chart_config.validate_config({"source": "evolution", "x": "age", "y": "views", "y_more": ["like_rate"]})
|
|
prepared = {"recs": [{"y": 5, "cat": 0, "hn": "A", "s": "Vues"}, {"y": 9.5, "cat": 1, "hn": "A", "s": "Taux"},
|
|
{"y": 700, "cat": 0, "hn": "B", "s": "Vues"}, {"y": None, "cat": 1, "hn": "B"}],
|
|
"kind": "path", "missing": []}
|
|
assert highlight.y_extents(cfg, prepared) == {0: [5, 700], 1: [9.5]}
|
|
hide_b = chart_view.View(hidden={"hn": ("B",)})
|
|
assert highlight.y_extents(cfg, prepared, hide_b) == {0: [5], 1: [9.5]}
|
|
assert highlight.y_extents(cfg, prepared, chart_view.View(hidden={"s": ("Taux",)})) == {0: [5, 700]}
|
|
count = chart_config.validate_config({"x": "views", "y": "count"})
|
|
assert highlight.y_extents(count, prepared) == {} # comptage : la vidéo est un trait vertical
|
|
|
|
|
|
def test_x_slider_covers_highlight():
|
|
controls = {"x_filter": "views", "filters": [{"key": "views", "kind": "range", "min": 100, "max": 900,
|
|
"integer": True}]}
|
|
highlight.extend_controls(controls, {"recs": [{"x": 50.4}, {"x": 1200.2}]}, "views")
|
|
assert controls["filters"][0]["min"] == 50 and controls["filters"][0]["max"] == 1201
|
|
dates = {"x_filter": "publish_date", "filters": [{"key": "publish_date", "kind": "date", "min": "2026-08-01",
|
|
"max": "2026-09-01"}]}
|
|
highlight.extend_controls(dates, {"recs": [{"x": "2026-09-12T10:00:00"}]}, "publish_date")
|
|
assert dates["filters"][0]["max"] == "2026-09-12"
|
|
other = {"x_filter": "age", "filters": [{"key": "age", "kind": "range", "min": 1, "max": 9}]}
|
|
highlight.extend_controls(other, {"recs": [{"x": 40}]}, "snapshot_date") # autre abscisse : rien à étendre
|
|
assert other["filters"][0]["max"] == 9
|
|
|
|
|
|
def test_highlight_marks_are_clipped():
|
|
for raw, kind in [({"x": "views@6", "y": "views", "type": "scatter"}, "point"),
|
|
({"x": "views", "y": "count"}, "point"),
|
|
({"x": "weekday", "y": "views@6", "y_more": ["likes@6"], "type": "line"}, "point")]:
|
|
cfg = chart_config.validate_config(raw)
|
|
out = charts.build(cfg, multi_rows(cfg) if cfg.y_more else fake_rows(cfg))
|
|
recs = [{"id": "zz", "t": "Vidéo", "x": out["spec"]["data"]["values"][0]["x"], "y": 10 ** 7,
|
|
"hl": 1, "hn": "Vidéo", "c": None, "ch": None, **({"cat": 0, "s": "Vues à 6 h"} if cfg.y_more else {})}]
|
|
highlight.decorate(out, recs, kind)
|
|
marks = []
|
|
|
|
def walk(node):
|
|
for layer in node.get("layer", []):
|
|
if "mark" in layer and str(layer["mark"].get("style", "")).startswith("hl-"):
|
|
marks.append(layer["mark"])
|
|
walk(layer)
|
|
walk(body_of(out["spec"]))
|
|
assert marks and all(m["clip"] is True for m in marks), raw
|
|
keep(out, f"clip {raw}")
|
|
|
|
|
|
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 chart_catalog.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]]}
|
|
line, dots = (layer["mark"] for layer in highlight._hl_layers(xy, "path", {**st, "sizes": {("large", "normal"): [1]}}))
|
|
assert line["strokeWidth"] == 2.5 and dots["size"] == 137.2
|
|
line, dots = (layer["mark"] for layer in highlight._hl_layers(xy, "path", {**st, "sizes": {("normal", "xthick"): [1]}}))
|
|
assert line["strokeWidth"] == 6.0 and dots["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 chart_catalog.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_rank_before_title():
|
|
videos = [{"label": "Évolution 11", "why": "la plus vue"}, {"label": "Short 28", "why": "2e plus récente"},
|
|
{"label": "Évolution 3", "why": None}]
|
|
assert highlight.note(videos, []) == [
|
|
"mises en avant : la plus vue : « Évolution 11 », 2e plus récente : « Short 28 », « Évolution 3 »"]
|
|
assert highlight.note(videos[1:2], []) == ["mise en avant : 2e plus récente : « Short 28 »"]
|
|
assert highlight.note(videos[2:], ["Absente"]) == ["mise en avant : « Évolution 3 »",
|
|
"sans valeur ici : « Absente »"]
|