shortstats/tests/test_charts.py
2026-10-31 23:25:50 +01:00

152 lines
5.4 KiB
Python

import itertools
import json
from datetime import date, timedelta
import pytest
from shortstats.web import charts
from shortstats.web.charts import ChartError, FIELDS, build, choose_type, validate_config
def fake_rows(cfg: charts.ChartConfig, n: int = 40) -> list[tuple]:
"""Lignes plausibles pour n'importe quelle combinaison de données."""
def value(key, i):
kind = charts.field(key).kind
if key == "count":
return 1
if key == "title":
return f"Short n°{i}"
if key == "channel":
return ["Chaîne principale", "Chaîne secondaire"][i % 2]
if key == "theme":
return ["Apothecary Diaries", "applepie", "Aucun thème"][i % 3]
if key == "weekday":
return charts.WEEKDAYS[i % 7]
if key == "publish_hour":
return (i * 5) % 24
if kind == "T":
return date(2026, 6, 1) + timedelta(days=i * 3)
return (i + 1) * 137 if key != "like_rate" else 1.5 + i / 10
rows = []
for i in range(n):
row = [f"vid{i:08d}", f"Short n°{i}", value(cfg.x, i), value(cfg.y, i)]
if cfg.color:
row.append(value(cfg.color, i))
rows.append(tuple(row))
return rows
ALL_X = list(FIELDS)
ALL_Y = list(FIELDS) + ["count"]
@pytest.mark.parametrize("x,y", list(itertools.product(ALL_X, ALL_Y)))
def test_every_pair_builds_in_auto_mode(x, y):
cfg = validate_config({"x": x, "y": y})
out = build(cfg, fake_rows(cfg))
assert out["spec"] is not None
json.dumps(out["spec"]) # sérialisable
assert out["resolved"]["type"] in charts.CHART_TYPES
# le type automatique doit toujours être compatible avec les données
assert charts.incompatibility(out["resolved"]["type"], FIELDS[x].kind, charts.field(y).kind) is None
@pytest.mark.parametrize("x,y,ctype", [
(x, y, t) for x in ALL_X for y in ALL_Y for t in charts.CHART_TYPES if t != "auto"
])
def test_every_compatible_type_builds(x, y, ctype):
reason = charts.incompatibility(ctype, FIELDS[x].kind, charts.field(y).kind)
if reason:
with pytest.raises(ChartError):
validate_config({"x": x, "y": y, "type": ctype})
return
for color in (None, "theme", "views"):
cfg = validate_config({"x": x, "y": y, "type": ctype, "color": color})
out = build(cfg, fake_rows(cfg))
assert out["spec"]["mark"]
@pytest.mark.parametrize("xk,yk,median,expected", [
("Q", "Q", None, "scatter"),
("T", "Q", None, "line"),
("O", "Q", 10, "boxplot"),
("N", "Q", 2, "bar"),
("Q", "N", 8, "boxplot"),
("Q", "C", None, "histogram"),
("T", "C", None, "bar"),
("O", "C", None, "bar"),
("O", "N", None, "heatmap"),
("I", "Q", None, "bar"),
("T", "T", None, "scatter"),
])
def test_auto_choice(xk, yk, median, expected):
assert choose_type(xk, yk, median)[0] == expected
def test_log_scale_auto_for_wide_spread():
cfg = validate_config({"x": "views", "y": "likes"})
rows = [(f"v{i}", "t", 10 ** (i % 6), i + 1) for i in range(30)]
out = build(cfg, rows)
assert out["spec"]["encoding"]["x"]["scale"]["type"] == "log"
assert "x" in out["resolved"]["log_axes"]
def test_symlog_when_zero_present():
cfg = validate_config({"x": "views", "y": "comment_likes", "scale": "log"})
rows = [(f"v{i}", "t", 100 * (i + 1), i) for i in range(10)] # y contient 0
out = build(cfg, rows)
assert out["spec"]["encoding"]["y"]["scale"]["type"] == "symlog"
def test_bar_never_log():
cfg = validate_config({"x": "weekday", "y": "views", "type": "bar", "scale": "log"})
out = build(cfg, fake_rows(cfg))
assert "scale" not in out["spec"]["encoding"]["y"]
assert "non applicable" in out["explanation"]
def test_titles_limited_to_top():
cfg = validate_config({"x": "title", "y": "views"})
out = build(cfg, fake_rows(cfg, n=80))
values = out["spec"]["data"]["values"]
assert len(values) == charts.TOP_TITLES
assert values[0]["y"] == max(v["y"] for v in values)
def test_nulls_excluded_and_counted():
cfg = validate_config({"x": "views", "y": "likes"})
rows = [("a", "t", 10, None), ("b", "t", 20, 3), ("c", "t", None, 4), ("d", "t", 5, 1)]
out = build(cfg, rows)
assert out["n"] == 2 and out["excluded"] == 2
def test_empty_data():
out = build(validate_config({"x": "views", "y": "likes"}), [])
assert out["spec"] is None and "Aucune" in out["explanation"]
def test_weekday_sorted_monday_first():
cfg = validate_config({"x": "weekday", "y": "views", "type": "bar"})
out = build(cfg, fake_rows(cfg))
assert out["spec"]["encoding"]["x"]["sort"][0] == "Lundi"
@pytest.mark.parametrize("raw,message", [
({"x": "nope", "y": "views"}, "Abscisse"),
({"x": "views", "y": "nope"}, "Ordonnée"),
({"x": "views", "y": "likes", "type": "pie"}, "Type"),
({"x": "views", "y": "likes", "color": "title"}, "couleur"),
({"x": "views", "y": "likes", "sql": "DROP TABLE"}, "inconnus"),
({"x": "views", "y": "likes", "title": "x" * 200}, "Titre"),
({"x": "views", "y": "count", "type": "scatter"}, "impossible"),
("pas un objet", "objet"),
])
def test_validation_errors(raw, message):
with pytest.raises(ChartError, match=message):
validate_config(raw)
def test_data_query_uses_only_catalog_sql():
cfg = validate_config({"x": "weekday", "y": "views", "color": "theme"})
q = charts.data_query(cfg)
assert "v.view_count AS y" in q and "WHERE v.status = 'collected'" in q