134 lines
6.8 KiB
Python
134 lines
6.8 KiB
Python
"""Configurations, exports et expressions des versions précédentes toujours lus de la même façon."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import psycopg
|
|
import pytest
|
|
|
|
from shortstats.regex_adapter import RegexTranslationError, to_pcre, to_postgres
|
|
from shortstats.web import chart_catalog, chart_config, evolution, transfer
|
|
|
|
from ..outils.collecte import TEXTS, U_E9
|
|
|
|
OLD_LABELS = (["1 h", "2 h", "3 h", "4 h", "5 h", "6 h", "9 h", "12 h", "15 h", "18 h", "21 h", "24 h"]
|
|
+ [f"{d} j" for d in range(2, 8)] + [f"{w} sem." for w in range(2, 9)]
|
|
+ [f"{m} mois" for m in range(2, 37)])
|
|
|
|
LEGACY = [r"\mchat\M", r"\m(chat)\M", r"\mc?hat\M", r"\mé\w*", r"\w+é\M", r"[[:<:]]la[[:>:]]",
|
|
r"\yfin\y", r"(?c)TV", r"merci$", r"^merci", r"apple ?pie", r"\mfrieren\M", r"ch[aâ]t\M",
|
|
r"\d{2,}", U_E9 + "t" + U_E9, r"(?cw)^bravo$", r"(a|b)\1"]
|
|
|
|
|
|
def test_legacy_map():
|
|
"""Anciennes étapes : même âge, sauf 2 à 12 mois rattachés à la semaine la plus proche."""
|
|
new = {sid: label for sid, label, _ in chart_catalog.STEPS}
|
|
got = {OLD_LABELS[old - 1]: new[nid] for old, nid in chart_config.LEGACY_STEP_MAP.items()}
|
|
assert len(got) == 60 and len(set(chart_config.LEGACY_STEP_MAP.values())) == 60
|
|
for label in ["1 h", "6 h", "9 h", "24 h", "2 j", "7 j", "5 sem.", "8 sem."] + [f"{m} mois" for m in range(13, 37)]:
|
|
assert got[label] == label
|
|
assert [got[f"{w} sem."] for w in (2, 3, 4)] == ["14 j", "21 j", "28 j"]
|
|
assert [got[f"{m} mois"] for m in range(2, 13)] == [
|
|
"9 sem.", "13 sem.", "17 sem.", "22 sem.", "26 sem.", "30 sem.", "35 sem.", "39 sem.", "43 sem.",
|
|
"48 sem.", "52 sem."]
|
|
|
|
|
|
def test_import_of_old_exports_is_remapped():
|
|
old = {"format": transfer.FORMAT, "version": 1, "charts": [
|
|
{"x": "views@6", "y": "views@18", "y_more": ["likes@36"],
|
|
"defaults": {"filters": {"views@6": {"min": 1, "max": 5}}}},
|
|
{"source": "evolution", "x": "age", "y": "views", "type": "boxplot",
|
|
"defaults": {"filters": {"age": {"min": 13, "max": 18}}}},
|
|
]}
|
|
configs, warnings = transfer.parse(json.dumps(old), set())
|
|
assert warnings == []
|
|
assert (configs[0].x, configs[0].y, configs[0].y_more) == ("views@6", "views@56", ("likes@127",))
|
|
assert configs[0].defaults["filters"] == {"views@6": {"min": 1, "max": 5}}
|
|
assert configs[1].defaults["filters"]["age"] == {"min": 32, "max": 56}
|
|
# export actuel : format 3, relu sans changement
|
|
current = transfer.export([c.to_dict() for c in configs], "2026-11-06")
|
|
assert current["version"] == 3
|
|
again, _ = transfer.parse(json.dumps(current), set())
|
|
assert [c.to_dict() for c in again] == [c.to_dict() for c in configs]
|
|
# une configuration seule (sans enveloppe) est lue au format actuel
|
|
bare, _ = transfer.parse(json.dumps({"x": "views@18", "y": "views"}), set())
|
|
assert bare[0].x == "views@18"
|
|
|
|
|
|
def test_import_of_pinned_exports():
|
|
from shortstats.web import transfer
|
|
old = {"format": transfer.FORMAT, "version": 2, "charts": [
|
|
{"x": "publish_date", "y": "views", "color": "theme_each",
|
|
"defaults": {"filters": {"theme_each": {"in": ["x"]}, "views": {"min": 1}}}},
|
|
]}
|
|
configs, _ = transfer.parse(json.dumps(old), set())
|
|
assert configs[0].color is None and configs[0].defaults == {"filters": {"views": {"min": 1, "max": None}}}
|
|
with pytest.raises(chart_catalog.ChartError, match="Diagramme à modifier"):
|
|
transfer.parse(json.dumps({**old, "charts": [{"x": "theme", "y": "views"}]}), set())
|
|
|
|
|
|
def test_saved_pinned_chart_reports_clearly(themed, clean_db):
|
|
"""Diagramme enregistré avant la 1.3.0 sur le thème du commentaire épinglé (migration 010)."""
|
|
from psycopg.types.json import Jsonb
|
|
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
|
|
cid = conn.execute("INSERT INTO shortstats.chart (config, created_by) VALUES (%s, 'alice') RETURNING chart_id",
|
|
(Jsonb({"x": "pinned_theme", "y": "views"}),)).fetchone()[0]
|
|
r = themed.get(f"/api/charts/{cid}/render")
|
|
assert r.status_code == 200 and r.json()["spec"] is None
|
|
assert "Diagramme à modifier : le thème du commentaire épinglé n'existe plus" in r.json()["explanation"]
|
|
assert any(c["id"] == cid for c in themed.get("/api/charts").json()) # toujours listé (à modifier)
|
|
|
|
|
|
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 = chart_config.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"]
|
|
|
|
|
|
@pytest.mark.parametrize("pg, pcre", [
|
|
(r"\mchat\M", r"\bchat\b"), # lettre à côté : \b suffit
|
|
(r"\m(chat)\M", r"\b(?=\w)(chat)\b(?<=\w)"),
|
|
(r"\mc?hat\M", r"\b(?=\w)c?hat\b"),
|
|
(r"a+\M", r"a+\b(?<=\w)"),
|
|
(r"\ychat\y", r"\bchat\b"),
|
|
(r"(?c)TV", r"(?-i)TV"),
|
|
(r"(?cw)a$", r"(?m-i)a$"),
|
|
(r"[[:<:]]chat[[:>:]]", r"\bchat\b"),
|
|
(U_E9 + "t", r"\x{e9}t"),
|
|
(r"a\Zb\Bc\bd", r"a\zb\\c\x{8}d"),
|
|
(r"\[spoiler\]", r"\[spoiler\]"),
|
|
(r"^_^ \$", r"^_^ \$"),
|
|
(r"merci$", r"merci\z"), # fin du texte seulement, comme avant
|
|
(r"(?n)a.b", r"(?n)a.b"), # sans équivalent : gardée, refusée à l'enregistrement
|
|
(r"a{2,3}b{x", r"a{2,3}b\{x"),
|
|
(r"merci(?=\n?\Z)", r"merci$"),
|
|
])
|
|
def test_legacy_expressions_are_shown_in_regex101_syntax(pg, pcre):
|
|
"""Thèmes d'avant la 1.3.1 (syntaxe PostgreSQL) : retraduits pour l'affichage
|
|
(l'équivalence au réenregistrement : test suivant)."""
|
|
assert to_pcre(pg) == pcre
|
|
if pg.startswith("(?n)"):
|
|
with pytest.raises(RegexTranslationError, match="option"):
|
|
to_postgres(pcre)
|
|
|
|
|
|
def test_legacy_expressions_classify_the_same_after_round_trip(clean_db):
|
|
"""Expression d'avant la 1.3.1, affichée en syntaxe regex101 puis réenregistrée :
|
|
PostgreSQL reconnaît exactement les mêmes textes."""
|
|
diffs = []
|
|
with psycopg.connect(clean_db["web"]) as conn:
|
|
for pg in LEGACY:
|
|
back = to_postgres(to_pcre(pg))
|
|
got = conn.execute(
|
|
"""SELECT array_agg(t ~* %s ORDER BY i), array_agg(t ~* %s ORDER BY i)
|
|
FROM unnest(%s::text[]) WITH ORDINALITY u (t, i)""", (pg, back, TEXTS)).fetchone()
|
|
diffs += [(pg, back, t) for t, a, b in zip(TEXTS, *got) if a != b]
|
|
assert diffs == []
|