shortstats/tests/integration/test_api_mises_en_avant.py
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

211 lines
15 KiB
Python

"""Vidéos mises en avant par l'API : recherche, styles, masquage."""
from __future__ import annotations
import pytest
from shortstats.web import chart_catalog, chart_config, chart_view, charts, highlight
from ..outils.base import seed_videos
from ..outils.site import OTHER, login, preview
from ..outils.specs import _check_path, _hl_layers, body_of, keep
def test_highlight_evolution(evo):
hl = [{"rank": "views", "n": 1}, {"video": "evo00000003", "title": "Évolution 3"}]
out = keep(preview(evo, {"source": "evolution", "x": "age", "y": "views", "y_more": ["like_rate"],
"split_channels": False, "highlight": hl}), "hl evolution multi")
body = out["spec"]
# chaque catégorie garde son échelle : couche principale + couches mises en avant, regroupées
assert all("layer" in group for group in body["layer"])
main = body["layer"][0]["layer"][0]
assert {"not": {"field": "hl", "valid": True}} in [t["filter"] for t in main["transform"]]
path, dots = body["layer"][0]["layer"][1:3]
# la courbe, puis ses relevés marqués de la forme de la vidéo (deux couches depuis 1.3.3)
assert path["mark"]["type"] == "line" and "point" not in path["mark"]
assert dots["mark"]["type"] == "point" and dots["mark"]["style"] == "hl-point"
# titres dans la légende « Vidéos mises en avant », forme et trait de chacune
assert dots["encoding"]["shape"]["scale"] == {"domain": ["Évolution 11", "Évolution 3"],
"range": ["diamond", "triangle-up"]}
assert path["encoding"]["strokeDash"]["scale"]["range"] == [[1, 0], [1, 0]]
assert dots["encoding"]["shape"]["legend"]["title"] == "Vidéos mises en avant"
hl_recs = [r for r in body["data"]["values"] if r.get("hl")]
assert {r["hn"] for r in hl_recs} == {"Évolution 11", "Évolution 3"}
assert not any(r.get("lbl") for r in hl_recs) # plus d'étiquette écrite sur le diagramme
assert "mises en avant : la plus vue : « Évolution 11 », « Évolution 3 »" in out["explanation"]
items = out["controls"]["highlight"]["items"]
assert [i["label"] for i in items] == ["Évolution 11", "Évolution 3"] and items[0]["why"] == "la plus vue"
assert out["controls"]["highlight"]["overridden"] is False
# remplacée sur la page (vue), puis retirée
page = preview(evo, {"source": "evolution", "x": "age", "y": "views", "highlight": hl},
{"highlight": [{"rank": "latest", "n": 1}]})
assert page["controls"]["highlight"]["overridden"] is True
assert [i["label"] for i in page["controls"]["highlight"]["items"]] == ["Évolution 11"]
none = preview(evo, {"source": "evolution", "x": "age", "y": "views", "highlight": hl}, {"highlight": []})
assert "mise en avant" not in none["explanation"] and not any(r.get("hl") for r in none["spec"]["data"]["values"])
# boîtes : une ligne par-dessus, à l'âge de chaque étape (axe linéaire, 1.3.2)
box = keep(preview(evo, {"source": "evolution", "x": "age", "y": "views", "type": "boxplot",
"split_channels": False, "highlight": hl[:1]}), "hl box")
line = next(layer for layer in box["spec"]["layer"] if layer["mark"].get("style") == "hl-line")
assert line["encoding"]["x"]["field"] == "x" and line["encoding"]["x"]["type"] == "quantitative"
assert {r["x"] for r in box["spec"]["data"]["values"] if r.get("hl")} <= {h for _, _, h in chart_catalog.STEPS}
# barres : repère par-dessus, aucune barre ajoutée (largeur inchangée)
bars = keep(preview(evo, {"source": "evolution", "x": "age", "y": "views", "type": "bar",
"highlight": hl[:1]}), "hl bars")
kinds = [layer["mark"]["type"] for layer in body_of(bars["spec"])["layer"]]
assert kinds.count("bar") == 1 and "line" in kinds # ses relevés reliés, marqués de sa forme
# un point par relevé : la trajectoire de la vidéo, dans l'ordre des étapes
pairs = keep(preview(evo, {"source": "evolution", "x": "likes", "y": "views", "split_channels": False,
"highlight": hl[:1]}), "hl pairs")
path = next(layer for layer in pairs["spec"]["layer"] if layer["mark"]["type"] == "line")
assert path["encoding"]["order"] == {"field": "sid"}
# vidéo introuvable : signalée, et gardée dans les commandes pour pouvoir la retirer
missing = preview(evo, {"source": "evolution", "x": "age", "y": "views",
"highlight": [{"rank": "views", "n": 400}]})
assert "mise en avant introuvable : 400e plus vue" in missing["explanation"]
assert missing["controls"]["highlight"]["items"][0]["missing"] is True
def test_highlight_j7(app_client, clean_db, monkeypatch):
seed_videos(clean_db["owner"])
login(app_client)
hl = [{"rank": "views", "n": 1}, {"rank": "latest", "n": 2}]
scatter = keep(preview(app_client, {"x": "views", "y": "likes", "highlight": hl}), "hl scatter")
assert "mises en avant : la plus vue : « <b>Short 29</b> », 2e plus récente : « <b>Short 28</b> »" \
in scatter["explanation"]
points = [layer for layer in scatter["spec"]["layer"] if layer["mark"].get("style") == "hl-point"]
assert points[0]["encoding"]["shape"]["scale"] == {"domain": ["<b>Short 29</b>", "<b>Short 28</b>"],
"range": ["diamond", "triangle-up"]}
assert not any(layer["mark"]["type"] == "text" for layer in scatter["spec"]["layer"])
# barres par catégorie : point sur la catégorie, pas de barre ajoutée
bars = keep(preview(app_client, {"x": "weekday", "y": "views", "type": "bar", "highlight": hl}), "hl j7 bars")
layers = body_of(bars["spec"])["layer"]
assert [layer["mark"]["type"] for layer in layers].count("bar") == 1
pt = next(layer for layer in layers if layer["mark"].get("style") == "hl-point")
assert pt["encoding"]["x"]["type"] == "ordinal" and "aggregate" not in pt["encoding"]["y"]
# histogramme (comptage) : un trait à la valeur
hist = keep(preview(app_client, {"x": "views", "y": "count", "type": "histogram", "highlight": hl}), "hl hist")
assert any(layer["mark"]["type"] == "rule" for layer in body_of(hist["spec"])["layer"])
# titres (mieux classées) : seulement si la vidéo y est déjà
titles = keep(preview(app_client, {"x": "title", "y": "views", "highlight": [{"rank": "views", "n": 1}]}),
"hl titles")
assert "mise en avant" in titles["explanation"]
monkeypatch.setattr(charts, "TOP_TITLES", 5) # la vidéo la moins vue n'est pas dans les 5 premières
deep = preview(app_client, {"x": "title", "y": "views", "highlight": [{"video": "vid00000000"}]})
assert "sans valeur ici : « <b>Short 0</b> »" in deep["explanation"]
assert not any(r.get("hl") for r in deep["spec"]["data"]["values"]) # aucune ligne ajoutée
# plusieurs ordonnées : couleur de la série, chaque catégorie avec son échelle
many = keep(preview(app_client, {"x": "weekday", "y": "views", "y_more": ["likes"], "type": "bar",
"type2": "line", "highlight": hl}), "hl j7 multi")
for group in body_of(many["spec"])["layer"]:
hl_layers = [layer for layer in group["layer"] if layer["mark"].get("style") == "hl-point"]
assert hl_layers and hl_layers[0]["encoding"]["color"]["field"] == "s"
def test_highlight_styles_and_hiding(evo):
styled = [{"rank": "views", "n": 1, "shape": "circle", "dash": "dotted"}, {"rank": "views", "n": 2}]
cfg = chart_config.validate_config({"source": "evolution", "x": "age", "y": "views", "highlight": styled})
assert cfg.highlight[0] == {"rank": "views", "n": 1, "shape": "circle", "dash": "dotted"}
for bad in ([{"rank": "views", "shape": "étoile"}], [{"rank": "views", "dash": "vague"}],
[{"rank": "views", "hidden": True}]): # 1.2.5 : masquer passe par la légende
with pytest.raises(chart_catalog.ChartError):
chart_config.validate_config({"x": "views", "y": "likes", "highlight": bad})
with pytest.raises(chart_catalog.ChartError):
chart_view.parse_view({"highlight": [{"rank": "views", "hidden": True}]}, cfg)
out = keep(preview(evo, {"source": "evolution", "x": "age", "y": "views", "split_channels": False,
"highlight": styled}), "hl styled")
path = next(layer for layer in out["spec"]["layer"] if layer["mark"].get("style") == "hl-line")
dots = next(layer for layer in out["spec"]["layer"] if layer["mark"].get("style") == "hl-point")
assert dots["encoding"]["shape"]["scale"]["range"] == ["circle", "triangle-up"] # 2e : forme par défaut
assert path["encoding"]["strokeDash"]["scale"]["range"] == [[1.5, 3], [1, 0]]
assert path["mark"]["clip"] is True and dots["mark"]["clip"] is True
# légende : deux icônes (dessinées par la page), place pour elles avant le titre
assert dots["encoding"]["shape"]["legend"]["labelOffset"] == 18
items = out["controls"]["highlight"]["items"]
assert [(i["shape"], i["dash"]) for i in items] == [("circle", "dotted"), ("triangle-up", "solid")]
assert all("hidden" not in i for i in items)
assert set(out["controls"]["highlight"]["shapes"]) >= {"diamond", "circle", "cross"}
legend = next(leg for leg in out["controls"]["legends"] if leg["field"] == "hn")
assert legend == {"field": "hn", "title": highlight.LEGEND_TITLE, "values": [i["label"] for i in items],
"hidden": []}
# masquée d'un clic sur la légende : plus dessinée, toujours dans la légende (grisée)
page = preview(evo, {"source": "evolution", "x": "age", "y": "views", "split_channels": False,
"highlight": styled}, {"hidden": {"hn": [items[0]["label"]]}})
dots = next(layer for layer in page["spec"]["layer"] if layer["mark"].get("style") == "hl-point")
assert dots["encoding"]["shape"]["scale"]["domain"] == [i["label"] for i in items]
assert {r["hn"] for r in page["spec"]["data"]["values"] if r.get("hl")} == {items[1]["label"]}
assert "masqué : « Évolution 11 »" in page["explanation"] and items[0]["label"] == "Évolution 11"
assert next(leg for leg in page["controls"]["legends"] if leg["field"] == "hn")["hidden"] == ["Évolution 11"]
every = preview(evo, {"source": "evolution", "x": "age", "y": "views", "highlight": styled},
{"hidden": {"hn": [i["label"] for i in items]}})
assert not any(r.get("hl") for r in every["spec"]["data"]["values"])
with pytest.raises(chart_catalog.ChartError):
chart_view.parse_view({"hidden": {"t": ["x"]}}, cfg) # champ non masquable
def test_video_search(app_client, clean_db):
seed_videos(clean_db["owner"])
assert app_client.get("/api/videos/search?q=Short").status_code == 401
login(app_client)
found = app_client.get("/api/videos/search?q=short 2").json()
assert found and all("Short 2" in v["title"] for v in found) and found[0]["channel"] == "Ma chaîne"
assert app_client.get("/api/videos/search?q=vid00000004").json()[0]["id"] == "vid00000004"
assert app_client.get("/api/videos/search?q=https://youtube.com/shorts/vid00000005").json()[0]["id"] == "vid00000005"
assert app_client.get("/api/videos/search?q=%25").json() == [] # caractères spéciaux échappés
assert app_client.get(f"/api/videos/search?q=Short&channels={OTHER}").json() == []
assert app_client.get("/api/videos/search?q=").json() == []
def test_highlight_follows_step_filter(evo):
"""Étapes filtrées (« Âge de la vidéo ») : la vidéo mise en avant aussi, sinon ses
étapes hors plage s'ajouteraient au bout de l'axe."""
cfg = {"source": "evolution", "x": "age", "y": "views", "split_channels": False,
"highlight": [{"rank": "views", "n": 1}], "defaults": {"filters": {"age": {"min": 3, "max": 6}}}}
out = keep(preview(evo, cfg), "hl step filter")
rows = out["spec"]["data"]["values"]
main = {r["x"] for r in rows if not r.get("hl")}
hl = [r for r in rows if r.get("hl")]
assert hl and {r["x"] for r in hl} <= main and all(3 <= r["sid"] <= 6 for r in hl)
every = preview(evo, {**cfg, "defaults": {}})
assert len([r for r in every["spec"]["data"]["values"] if r.get("hl")]) > len(hl)
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"]
hl_points = [layer["mark"] for layer in layers if layer["mark"].get("style") == "hl-point"]
assert sorted(m["strokeWidth"] for m in hl_lines) == [2.5, 6.0] # normale, très épaisse
assert sorted(m["size"] for m in hl_points) == [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"]
def test_dotted_highlights_through_the_api(evo): # noqa: F811 (fixture)
hl = [{"rank": "latest", "n": 1, "shape": "triangle-up", "dash": "dotted"},
{"rank": "latest", "n": 2, "shape": "triangle-down", "dash": "dotted"},
{"rank": "latest", "n": 3, "shape": "triangle-up", "dash": "solid", "size": "large"}]
for cfg, view in [
({"source": "evolution", "x": "age", "y": "views", "split_channels": False}, None),
({"source": "evolution", "x": "age", "y": "views", "type": "boxplot"}, None),
({"source": "evolution", "x": "age", "y": "views", "split_channels": False}, {"individual": True}),
# cas signalé : barres des vues et courbe du taux de like, taux masqué d'un clic sur la légende
({"source": "evolution", "x": "age", "y": "views", "y_more": ["like_rate"], "type": "bar", "type2": "line"},
{"hidden": {"s": ["Taux de like (% des vues)"]}}),
]:
out = preview(evo, {**cfg, "highlight": hl}, view)
spec = out["spec"]
_check_path(_hl_layers(spec.get("spec", spec)))