shortstats/tests/test_v130_themes.py
ploush 8481edf66e
All checks were successful
build / test (push) Successful in 6m34s
build / images (collector) (push) Successful in 20s
build / images (web) (push) Successful in 23s
upgrade 1.3.1
2026-11-07 01:44:37 +01:00

189 lines
10 KiB
Python

"""1.3.0 : thèmes définis par des expressions régulières (migration 009, page, test en direct)."""
from datetime import datetime, timezone
import psycopg
import pytest
from shortstats import migrate
from shortstats.web.data import clean_patterns, excerpt, MARK_CLOSE, MARK_OPEN
from .test_v130_schedule import _owner_cfg
from .test_web import CH, ORIGIN, app_client, login, users_file # noqa: F401
H = {"Origin": ORIGIN}
def add_comments(owner_url, comments):
"""Une vidéo et ses commentaires relevés (du plus ancien au plus récent), classés comme par le collecteur."""
from shortstats import comment_themes
with psycopg.connect(owner_url, autocommit=True) as conn:
conn.execute("""INSERT INTO shortstats.channel (channel_id, youtube_title)
VALUES (%s, 'Ma chaîne') ON CONFLICT DO NOTHING""", (CH,))
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, title)
VALUES ('rgxvideo001', %s, %s, 'pending', 'Short des commentaires')
ON CONFLICT DO NOTHING""", (CH, datetime(2026, 9, 1, tzinfo=timezone.utc)))
ids = []
for i, text in enumerate(comments):
conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text)
VALUES (%s, 'rgxvideo001', %s, %s)""",
(f"rgx{i:08d}", datetime(2026, 9, 2 + i, tzinfo=timezone.utc), text))
ids.append(f"rgx{i:08d}")
comment_themes.classify(conn, ids)
def themes_of(url):
"""{commentaire: [thèmes]}."""
with psycopg.connect(url) as conn:
rows = conn.execute("""SELECT ct.comment_id, t.name FROM shortstats.comment_theme ct
JOIN shortstats.theme t USING (theme_id) ORDER BY 1, 2""").fetchall()
out: dict = {}
for cid, name in rows:
out.setdefault(cid, []).append(name)
return out
def add_pinned(owner_url, comments):
"""Avant la 1.3.0 (migrations 008 et 009) : une vidéo relevée par commentaire épinglé."""
with psycopg.connect(owner_url, autocommit=True) as conn:
conn.execute("""INSERT INTO shortstats.channel (channel_id, author_channel_id, youtube_title)
VALUES (%s, %s, 'Ma chaîne') ON CONFLICT DO NOTHING""", (CH, CH))
for i, text in enumerate(comments):
conn.execute(
"""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, collected_at, title,
view_count, author_comment_status, author_comment_text)
VALUES (%s, %s, %s, 'collected', now(), %s, 100, 'found', %s)""",
(f"rgx{i:08d}", CH, datetime(2026, 9, 1 + i, tzinfo=timezone.utc), f"Short {i}", text))
def pinned_themes_of(url):
with psycopg.connect(url) as conn:
rows = conn.execute("SELECT video_id, name FROM shortstats.video_theme ORDER BY video_id, name").fetchall()
out: dict = {}
for vid, name in rows:
out.setdefault(vid, []).append(name)
return out
def test_clean_patterns():
assert clean_patterns(["a", "", " ", "a", " b "]) == ["a", " b "] # les espaces comptent
assert clean_patterns("x") == ["x"]
for bad, msg in [([], "Au moins"), (["", " "], "Au moins"), (["x" * 301], "trop longue"),
([str(i) for i in range(21)], "20 expressions"), (["a\x00"], "nul"), ([3], "invalide")]:
with pytest.raises(ValueError, match=msg):
clean_patterns(bad)
def test_excerpt():
text = "x" * 100 + "début " + MARK_OPEN + "Apple Pie" + MARK_CLOSE + " fin\n\nde texte" + "y" * 100
out = excerpt("v", "Titre", text)
assert out["match"] == "Apple Pie" and out["before"].startswith("…") and out["before"].endswith("début ")
assert out["after"].startswith(" fin de texte") and out["after"].endswith("…")
@pytest.fixture()
def before_009(clean_db):
owner = clean_db["owner"]
with psycopg.connect(owner, autocommit=True) as conn:
conn.execute("DROP SCHEMA shortstats CASCADE")
migrate.run(_owner_cfg(owner), stop_after="008")
yield clean_db
migrate.run(_owner_cfg(owner))
def test_migration_009_keeps_matches(before_009):
owner = before_009["owner"]
with psycopg.connect(owner, autocommit=True) as conn:
conn.execute("DELETE FROM shortstats.theme")
conn.execute("""INSERT INTO shortstats.theme (name, keywords) VALUES
('Tarte', ARRAY['apple pie', 'applepie']), ('Version', ARRAY['v1.5 (beta)', 'c++']),
('Crochets', ARRAY['[spoiler]', 'a\\b', '^_^ $'])""")
add_pinned(owner, ["J'adore l'Apple Pie !", "v1.5 (BETA) dispo, en C++", "v1x5 (beta", "[SPOILER] a\\b",
"trop mignon ^_^ $$", "rien"])
before = pinned_themes_of(owner)
migrate.run(_owner_cfg(owner), stop_after="009")
with psycopg.connect(owner) as conn:
patterns = dict(conn.execute("SELECT name, patterns FROM shortstats.theme").fetchall())
cols = {r[0] for r in conn.execute("""SELECT column_name FROM information_schema.columns
WHERE table_schema = 'shortstats' AND table_name = 'theme'""")}
assert patterns == {"Tarte": ["apple pie", "applepie"], "Version": [r"v1\.5 \(beta\)", r"c\+\+"],
"Crochets": [r"\[spoiler\]", r"a\\b", r"\^_\^ \$"]}
assert "keywords" not in cols
after = pinned_themes_of(owner)
assert after == before == {"rgx00000000": ["Tarte"], "rgx00000001": ["Version"], "rgx00000003": ["Crochets"],
"rgx00000004": ["Crochets"]}
with psycopg.connect(owner, autocommit=True) as conn, pytest.raises(psycopg.errors.CheckViolation):
conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('vide', '{}')")
def test_regex_themes_are_not_exclusive(app_client, clean_db):
"""Thèmes enregistrés sur le site : appliqués aussitôt à tous les commentaires déjà lus."""
owner = clean_db["owner"]
add_comments(owner, ["Apothecary Diaries et une applepie", "apothecary diaries", "Chat noir", "château",
"TV et tv", "tv seulement"])
login(app_client)
for name, patterns in [("Chat", [r"\bchat\b"]), ("Majuscules", ["(?-i)TV"]),
("Apothecary large", [r"apothecary\s+diaries"])]:
r = app_client.post("/themes", data={"name": name, "pattern": patterns}, headers=H, follow_redirects=False)
assert r.status_code == 303, r.text
got = themes_of(owner)
assert got["rgx00000000"] == ["Apothecary Diaries", "Apothecary large", "applepie"] # trois thèmes à la fois
assert got["rgx00000001"] == ["Apothecary large"]
assert got["rgx00000002"] == ["Chat"] and "rgx00000003" not in got # mot entier
assert got["rgx00000004"] == ["Majuscules"] and "rgx00000005" not in got # (?-i) : casse respectée
page = app_client.get("/themes").text
assert 'value="(?-i)TV"' in page and "1 commentaire(s) dans 1 vidéo(s)" in page
# modifier un thème reclasse les commentaires ; le supprimer les retire
with psycopg.connect(clean_db["web"]) as conn:
tid = conn.execute("SELECT theme_id FROM shortstats.theme WHERE name = 'Chat'").fetchone()[0]
app_client.post(f"/themes/{tid}", data={"name": "Chat", "pattern": ["ch[aâ]t"]}, headers=H)
got = themes_of(owner)
assert got["rgx00000002"] == ["Chat"] and got["rgx00000003"] == ["Chat"]
app_client.post(f"/themes/{tid}/delete", headers=H)
assert "rgx00000002" not in themes_of(owner)
def test_invalid_regex_is_refused_with_the_input_kept(app_client, clean_db):
login(app_client)
r = app_client.post("/themes", data={"name": "Cassé", "pattern": ["ok", "(saison", "[z-a]", "*x", "a{3,1}"]},
headers=H, follow_redirects=False)
assert r.status_code == 400
page = r.text
assert "4 expression(s) régulière(s) invalide(s)" in page
for text in ("parenthèses ( ) non équilibrées", "plage de caractères invalide", "sans rien à répéter",
"nombre de répétitions"):
assert text in page, text
assert 'value="Cassé"' in page and 'value="(saison"' in page and 'value="ok"' in page
assert "Cassé" not in app_client.get("/themes").text # rien d'enregistré
# modification d'un thème existant : même chose, le thème garde ses expressions
with psycopg.connect(clean_db["web"]) as conn:
tid = conn.execute("SELECT theme_id FROM shortstats.theme WHERE name = 'applepie'").fetchone()[0]
r = app_client.post(f"/themes/{tid}", data={"name": "applepie", "pattern": ["("]}, headers=H)
assert r.status_code == 400 and 'value="("' in r.text
with psycopg.connect(clean_db["web"]) as conn:
assert conn.execute("SELECT patterns FROM shortstats.theme WHERE theme_id = %s", (tid,)).fetchone()[0] == \
["applepie"]
def test_live_check_api(app_client, clean_db):
add_comments(clean_db["owner"], ["Une Apple Pie maison", "applepie !", "rien à voir", "APPLE PIE"])
assert app_client.post("/api/themes/check", json={"patterns": ["x"]}, headers=H).status_code == 401
login(app_client)
r = app_client.post("/api/themes/check", json={"patterns": [r"apple\s*pie", "pie$", "(", "", "pie$"]}, headers=H)
assert r.status_code == 200, r.text
data = r.json()
assert data["comments"] == 4 and data["total"] == 3 and data["sample_size"] == 20000
by = {p["pattern"]: p for p in data["patterns"]}
assert list(by) == [r"apple\s*pie", "pie$", "("] # vides et doublons retirés
assert by[r"apple\s*pie"] == {"pattern": r"apple\s*pie", "ok": True, "error": None, "matches": 3,
"translated": None}
assert by["pie$"]["matches"] == 1
assert by["("]["ok"] is False and "parenthèses" in by["("]["error"] and by["("]["matches"] is None
samples = data["samples"]
assert [s["match"] for s in samples] == ["APPLE PIE", "applepie", "Apple Pie"] # les plus récents d'abord
assert samples[2]["before"] == "Une " and samples[2]["after"] == " maison"
assert app_client.post("/api/themes/check", json={"patterns": ["x"] * 21}, headers=H).status_code == 400
assert app_client.post("/api/themes/check", json={"patterns": ["x" * 301]}, headers=H).status_code == 400
# aucune expression valable : rien à compter
empty = app_client.post("/api/themes/check", json={"patterns": ["("]}, headers=H).json()
assert empty["total"] == 0 and empty["samples"] == []