shortstats/tests/test_v124.py
ploush ce32a27ac6
All checks were successful
build / test (push) Successful in 7m31s
build / images (collector) (push) Successful in 23s
build / images (web) (push) Successful in 18s
UPGRADE 1.3.3
2026-11-29 01:02:52 +01:00

411 lines
26 KiB
Python

"""1.2.4 : un point par relevé, vidéos mises en avant, export et import, partage public."""
import json
import os
import psycopg
import pytest
from shortstats.web import charts, evolution, highlight, transfer
from shortstats.web.app import RateLimit
from .test_evolution import evo, preview, seed_snapshots # noqa: F401 (fixtures)
from .test_live import login_as, two_users # noqa: F401
from .test_multi_y import multi_rows
from .test_charts import fake_rows
from .test_web import CH, ORIGIN, OTHER, app_client, login, seed_videos, users_file # noqa: F401
DUMP = os.environ.get("DUMP_SPECS_V124")
_dumped: list = []
H = {"Origin": ORIGIN}
def body_of(spec):
return spec.get("spec", spec)
def keep(out, name):
if DUMP and out.get("spec"):
_dumped.append({"name": name, "spec": out["spec"]})
return out
# -- 1. un point par relevé -------------------------------------------------------
def test_pairs_validation():
cfg = charts.validate_config({"source": "evolution", "x": "likes", "y": "views"})
assert evolution.is_pairs(cfg) and evolution.mode(cfg, None) == "pairs"
assert evolution.resolved_type(cfg) == "scatter"
assert charts.validate_config({"source": "evolution", "x": "likes", "y": "views", "color": "period"}).color == "period"
for raw, msg in [
({"source": "evolution", "x": "likes", "y": "views", "type": "line"}, "un point par relevé : nuage de points"),
({"source": "evolution", "x": "age", "y": "views", "type": "scatter"}, "statistique à toutes les étapes"),
({"source": "evolution", "x": "age", "y": "views", "color": "period"}, "couleur"),
({"source": "evolution", "x": "duration", "y": "views"}, "Abscisse invalide"),
]:
with pytest.raises(charts.ChartError, match=msg):
charts.validate_config(raw)
assert evolution.compatible_types("likes")["scatter"] is None
assert evolution.compatible_types("likes")["line"]
assert evolution.compatible_types("age")["scatter"]
def test_pairs_api(evo):
out = keep(preview(evo, {"source": "evolution", "x": "likes", "y": "views", "split_channels": False}), "pairs")
recs = out["spec"]["data"]["values"]
with psycopg.connect(os.environ["TEST_OWNER_URL"]) as conn:
expected = conn.execute("SELECT count(*) FROM shortstats.video_snapshot "
"WHERE view_count IS NOT NULL AND like_count IS NOT NULL").fetchone()[0]
assert len(recs) == expected # un point par relevé
assert all(r["y"] // 20 == r["x"] for r in recs) # les deux valeurs du même relevé
assert {"lab", "sid", "t"} <= set(recs[0])
assert out["resolved"]["mode"] == "pairs" and out["resolved"]["type"] == "scatter"
assert "un point par relevé : vues et likes pris au même relevé" in out["explanation"]
assert out["title"] == "Vues selon likes (chaque relevé)"
enc = out["spec"]["encoding"]
assert enc["x"]["scale"].get("zero") is True or enc["x"]["scale"].get("domainMin") == 0
assert out["controls"]["x_filter"] == "likes"
assert {"likes", "views", "age"} <= {f["key"] for f in out["controls"]["filters"]}
assert [a["label"] for a in out["controls"]["y_axes"]] == ["Vues"]
assert out["controls"]["individual"]["available"] is False
# curseur sous l'axe X et filtre d'étapes appliqués en SQL
early = sorted(r["x"] for r in recs if 3 <= r["sid"] <= 6)
lo = early[len(early) // 2]
some = preview(evo, {"source": "evolution", "x": "likes", "y": "views", "split_channels": False},
{"filters": {"likes": {"min": lo}, "age": {"min": 3, "max": 6}}})
assert some["spec"]["data"]["values"] and all(r["x"] >= lo and 3 <= r["sid"] <= 6
for r in some["spec"]["data"]["values"])
assert some["spec"]["encoding"]["x"]["scale"]["domain"][0] == lo
# couleur par période (dégradé ordonné), et par chaîne
period = keep(preview(evo, {"source": "evolution", "x": "likes", "y": "views", "color": "period",
"split_channels": False}), "pairs period")
color = period["spec"]["encoding"]["color"]
assert {k: color[k] for k in ("field", "type", "title")} == {"field": "c", "type": "ordinal",
"title": "Période du relevé"}
present = {r["c"] for r in period["spec"]["data"]["values"]}
assert present <= set(evolution.PERIODS)
# domaine fixé (1.2.5, légende cliquable) : périodes présentes, dans l'ordre
assert color["scale"]["domain"] == [p for p in evolution.PERIODS if p in present]
by_channel = keep(preview(evo, {"source": "evolution", "x": "likes", "y": "views"}), "pairs channels")
assert by_channel["resolved"]["split"] == "color"
def test_pairs_multi_and_cap(evo, monkeypatch):
out = keep(preview(evo, {"source": "evolution", "x": "views", "y": "likes", "y_more": ["like_rate"],
"split_channels": False}), "pairs multi")
body = out["spec"]
assert [layer["mark"]["type"] for layer in body["layer"]] == ["point", "point"]
assert out["resolved"]["types"] == ["scatter", "scatter"]
assert {r["s"] for r in body["data"]["values"]} == {"Likes", "Taux de like (% des vues)"}
assert out["title"] == "Likes et Taux de like (% des vues) selon vues (chaque relevé)"
monkeypatch.setattr(evolution, "MAX_PAIRS", 10)
capped = preview(evo, {"source": "evolution", "x": "likes", "y": "views", "split_channels": False})
assert len(capped["spec"]["data"]["values"]) == 10
assert "les 10 relevés les plus récents" in capped["explanation"]
# -- 2. vidéos mises en avant ---------------------------------------------------------
def test_highlight_validation():
assert highlight.validate(None) == ()
ok = highlight.validate([{"video": "evo00000003", "title": "Ma vidéo"}, {"rank": "views", "n": 2},
{"rank": "views", "n": 2}])
assert ok == ({"video": "evo00000003", "title": "Ma vidéo"}, {"rank": "views", "n": 2}) # sans doublon
for bad in ([{"video": "x"}], [{"rank": "inconnu"}], [{"rank": "views", "n": 0}], [{"rank": "views", "n": True}],
[{"video": "evo00000003", "autre": 1}], [{}] , "x", [{"rank": "views"}] * 4,
[{"video": "evo00000003", "title": "t" * 201}]):
with pytest.raises(charts.ChartError):
highlight.validate(bad)
assert highlight.describe({"rank": "latest", "n": 1}) == "la plus récente"
assert highlight.describe({"rank": "views", "n": 3}) == "3e plus vue"
assert highlight.describe({"rank": "like_rate", "n": 1}) == "au meilleur taux de like"
assert highlight.short("x" * 40) == "x" * 29 + "…"
cfg = charts.validate_config({"x": "views", "y": "likes", "highlight": [{"rank": "views", "n": 1}]})
assert cfg.to_dict()["highlight"] == [{"rank": "views", "n": 1}]
assert charts.validate_config({"x": "views", "y": "likes"}).to_dict()["highlight"] == []
view = charts.parse_view({"highlight": []}, cfg)
assert view.highlight == () # liste vide : aucune (remplace celle du diagramme)
assert charts.parse_view({}, cfg).highlight is None
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 charts.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 = charts.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(charts.ChartError):
charts.validate_config({"x": "views", "y": "likes", "highlight": bad})
with pytest.raises(charts.ChartError):
charts.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(charts.ChartError):
charts.parse_view({"hidden": {"t": ["x"]}}, cfg) # champ non masquable
def test_highlight_decorate_widens_log_axis():
cfg = charts.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_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() == []
# -- 3. export et import -------------------------------------------------------------
def test_transfer_parse():
configs, warnings = transfer.parse(json.dumps(transfer.export(
[{"x": "views", "y": "likes", "channels": [CH], "title": "A"}, {"x": "weekday", "y": "views"}], "2026-11-04")),
{OTHER})
assert [c.title for c in configs] == ["A", ""] and "chaîne(s) inconnue(s)" in warnings[0]
assert len(transfer.parse('[{"x": "views", "y": "likes"}]', set())[0]) == 1 # liste
assert len(transfer.parse('{"x": "views", "y": "likes"}', set())[0]) == 1 # une seule
assert len(transfer.parse('{"charts": [{"config": {"x": "views", "y": "likes"}}]}', set())[0]) == 1
for text, msg in [("", "Collez"), ("{", "ligne 1"), ('{"format": "autre", "charts": []}', "pas un export"),
('{"charts": []}', "Aucun diagramme"), ('{"charts": [{"x": 1}], "version": 9}', "plus récente"),
(json.dumps([{"x": "views", "y": "likes"}] * 51), "50 diagrammes"),
('[{"x": "views", "y": "likes"}, {"x": "nope", "y": "likes"}]', "diagramme 2 : Abscisse")]:
with pytest.raises(charts.ChartError, match=msg):
transfer.parse(text, set())
def test_export_import_between_accounts(two_users, clean_db):
c = two_users
login_as(c, "alice")
for cfg in ({"x": "views", "y": "likes", "title": "Un"},
{"source": "evolution", "x": "likes", "y": "views", "highlight": [{"rank": "views", "n": 1}]}):
assert c.post("/api/charts", json={"config": cfg}, headers=H).status_code == 201
exported = transfer.export([ch["config"] for ch in c.get("/api/charts").json()], "2026-11-04")
login_as(c, "bob")
assert c.get("/api/charts").json() == []
r = c.post("/api/charts/import", json={"text": json.dumps(exported)}, headers=H)
assert r.status_code == 201 and r.json()["created"] == 2
mine = c.get("/api/charts").json()
assert [ch["config"]["title"] for ch in mine] == ["Un", ""]
assert mine[1]["config"]["highlight"] == [{"rank": "views", "n": 1}]
# un diagramme refusé : rien n'est importé
bad = c.post("/api/charts/import", json={"text": json.dumps([{"x": "views", "y": "likes"}, {"x": "?"}])},
headers=H)
assert bad.status_code == 400 and "Rien n'a été importé" in bad.json()["error"]
assert len(c.get("/api/charts").json()) == 2
assert c.post("/api/charts/import", json={"text": "{}"}).status_code == 403 # origine exigée
login_as(c, "alice")
assert len(c.get("/api/charts").json()) == 2 # alice inchangée
# -- 4. partage public -------------------------------------------------------------------
def test_share_flow(two_users, clean_db):
c = two_users
seed_snapshots(clean_db["owner"])
login_as(c, "alice")
cid = c.post("/api/charts", json={"config": {"source": "evolution", "x": "age", "y": "views",
"channels": [CH], "title": "Mon partage"}},
headers=H).json()["id"]
assert c.get(f"/api/charts/{cid}/share").json() == {"shared": False}
first = c.post(f"/api/charts/{cid}/share", headers=H).json()
token = first["url"].rsplit("/", 1)[1]
assert first["shared"] and first["url"] == f"{ORIGIN}/shared/{token}" and len(token) == 32
assert c.post(f"/api/charts/{cid}/share", headers=H).json()["url"] == first["url"] # même lien
assert c.get("/api/charts").json()[0]["share"] == token
# bob ne peut pas partager le diagramme d'alice
login_as(c, "bob")
assert c.post(f"/api/charts/{cid}/share", headers=H).status_code == 404
assert c.delete(f"/api/charts/{cid}/share", headers=H).status_code == 404
# sans connexion : la page, le rendu et ses filtres, la recherche (chaînes du diagramme seulement)
c.post("/logout", headers=H)
page = c.get(f"/shared/{token}")
assert page.status_code == 200 and "Mon partage" in page.text and "Se déconnecter" not in page.text
assert "shared.js" in page.text and 'data-token="' + token + '"' in page.text
out = c.post(f"/shared/{token}/render", json={"view": {"filters": {"age": {"min": 1, "max": 6}}}},
headers=H).json()
assert out["spec"] and out["title"] == "Mon partage" and out["controls"]["filters"]
hl = c.post(f"/shared/{token}/render", json={"view": {"highlight": [{"rank": "views", "n": 1}]}},
headers=H).json()
assert "mise en avant" in hl["explanation"]
found = c.get(f"/shared/{token}/videos?q=Évolution").json()
assert found and all(v["channel"] == "Ma chaîne" for v in found)
assert c.post(f"/shared/{token}/render", json={"view": None}).status_code == 403 # origine
assert c.put(f"/api/charts/{cid}", json={"config": {"x": "views", "y": "likes"}}, headers=H).status_code == 401
for bad in ("x" * 32, "court", token[:-1] + "!"):
r = c.get(f"/shared/{bad}", headers={"Accept": "text/html"})
assert r.status_code == 404 and "Lien de partage inconnu" in r.text
assert c.post(f"/shared/{'y' * 32}/render", json={}, headers=H).status_code == 404
# désactivé : le lien ne marche plus ; un nouveau partage donne un autre lien
login_as(c, "alice")
assert c.delete(f"/api/charts/{cid}/share", headers=H).status_code == 204
assert c.get(f"/shared/{token}").status_code == 404
again = c.post(f"/api/charts/{cid}/share", headers=H).json()["url"]
assert again != first["url"]
# supprimé : plus de lien non plus
c.delete(f"/api/charts/{cid}", headers=H)
assert c.get(again.replace(ORIGIN, "")).status_code == 404
def test_share_token_format_enforced(clean_db):
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
cid = conn.execute("""INSERT INTO shortstats.chart (config, created_by, position)
VALUES ('{"x": "views", "y": "likes"}', 'alice', 1) RETURNING chart_id""").fetchone()[0]
with pytest.raises(psycopg.errors.CheckViolation):
conn.execute("UPDATE shortstats.chart SET share_token = 'trop-court' WHERE chart_id = %s", (cid,))
def test_rate_limit():
rl = RateLimit(3, 60)
assert [rl.allow("ip", now=t) for t in (0, 1, 2, 3)] == [True, True, True, False]
assert rl.allow("autre", now=3) is True
assert rl.allow("ip", now=61) is True # fenêtre glissante
def test_shared_pages_are_rate_limited(app_client, monkeypatch):
from shortstats.web import app as app_module
limiter = RateLimit(2, 60)
monkeypatch.setattr(app_module, "RateLimit", lambda *a: limiter)
from shortstats.config import WebConfig
from fastapi.testclient import TestClient
cfg = WebConfig(database_url=os.environ["TEST_WEB_URL"], secret_key="x" * 40, users_file="/dev/null",
session_max_age_s=3600, cookie_secure=False, login_max_failures=3, login_lock_minutes=15)
with TestClient(app_module.create_app(cfg), base_url=ORIGIN) as c:
codes = [c.get(f"/shared/{'z' * 32}").status_code for _ in range(3)]
assert codes == [404, 404, 429]
assert c.get("/login").status_code == 200 # le reste du site n'est pas concerné
def teardown_module(_module):
if DUMP and _dumped:
with open(DUMP, "w") as fh:
json.dump(_dumped, fh)