218 lines
13 KiB
Python
218 lines
13 KiB
Python
"""Thèmes : page, enregistrement, vérification en direct, classement dans la base."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
import psycopg
|
|
|
|
from shortstats.regex_adapter import to_postgres
|
|
|
|
from ..outils.base import add_comments, seed_comments, seed_videos
|
|
from ..outils.collecte import TEXTS, U_E9
|
|
from ..outils.site import ORIGIN, H, login
|
|
|
|
DIFF = [
|
|
(r"\bchat\b", None, 0), (r"apple ?pie", None, 0), (r"saison (2|deux)", None, 0),
|
|
(r"ép(isode)?\s*[0-9]+", None, 0), (r"^merci", None, 0), (r"merci$", None, 0), (r"merci\s*$", None, 0),
|
|
(r"1\.5", None, 0), (r"\d{2,}", None, 0), (r"a{0,2}b", None, 0), (r"a{,1}b", r"a{0,1}b", 0),
|
|
(r"\Bat\b", None, 0), (r"(?=.*chat)(?=.*chien)", None, 0), (r"(?<!non )merci", None, 0),
|
|
(r"[^\w\s]{3}", None, 0), (r"\w+é", None, 0), (r"(?m)^bravo$", r"^bravo$", re.M), (r"\s$", None, 0),
|
|
(r"(?x) chat \s+ noir # couleur", r"chat \s+ noir # couleur", re.X), (r"(\w)\1", None, 0),
|
|
(r"x*?y", None, 0), (r"\Qa.b\E", r"a\.b", 0), (r"\x{e9}t\xe9", "été", 0),
|
|
(r"\h", r"[ \t]", 0), (r"\p{L}{4}", r"[^\W\d_]{4}", 0), (r"\N+fin", r"[^\n]+fin", 0),
|
|
(r"(?-i)TV", "TV", -1), (r"(?<n>la)\s(?P<m>la)", r"(la)\s(la)", 0), (r"\Afin\z", r"\Afin\Z", 0),
|
|
(r"fin\Z", r"fin(?=\n?\Z)", 0), (r"a.b", None, 0), (r"\bété\b", None, 0), (r"[[:alpha:]]+!", r"[^\W\d_]+!", 0),
|
|
(r"(?i)été", "été", 0), (r"\R", r"(?:\r\n|\n|\r)", 0), (r"^$", None, 0), (r"\.\.\.$", None, 0),
|
|
]
|
|
|
|
|
|
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 test_themes_page_and_crud(app_client, clean_db):
|
|
seed_videos(clean_db["owner"])
|
|
seed_comments(clean_db["owner"])
|
|
login(app_client)
|
|
h = {"Origin": ORIGIN}
|
|
r = app_client.post("/themes", data={"name": "Saison", "pattern": ["saison 2", "saison deux", ""]}, headers=h,
|
|
follow_redirects=False)
|
|
assert r.headers["location"] == "/themes?msg=created"
|
|
page = app_client.get("/themes").text
|
|
assert "Saison" in page and 'value="saison 2"' in page and 'value="saison deux"' in page
|
|
# comptes : commentaires reconnus et vidéos concernées (« saison 2 » : 1 commentaire sur 4 environ)
|
|
with psycopg.connect(clean_db["owner"]) as conn:
|
|
n = conn.execute("""SELECT count(*), count(DISTINCT c.video_id) FROM shortstats.comment c
|
|
WHERE c.text ~* 'saison (2|deux)'""").fetchone()
|
|
stored = conn.execute("""SELECT count(*) FROM shortstats.comment_theme ct JOIN shortstats.theme t
|
|
USING (theme_id) WHERE t.name = 'Saison'""").fetchone()[0]
|
|
assert n[0] > 0 and stored == n[0]
|
|
assert f"{n[0]} commentaire(s) dans {n[1]} vidéo(s)" in page
|
|
# doublon de nom : page réaffichée avec la saisie
|
|
r = app_client.post("/themes", data={"name": "Saison", "pattern": "x"}, headers=h, follow_redirects=False)
|
|
assert r.status_code == 400 and "Un thème porte déjà ce nom." in r.text
|
|
r = app_client.post("/themes", data={"name": "", "pattern": "x"}, headers=h, follow_redirects=False)
|
|
assert r.status_code == 400 and "Nom du thème" in r.text
|
|
r = app_client.post("/themes", data={"name": "Vide", "pattern": ["", " "]}, headers=h, follow_redirects=False)
|
|
assert r.status_code == 400 and "Au moins une expression régulière" in r.text
|
|
|
|
|
|
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"] == []
|
|
|
|
|
|
def test_same_results_as_pcre(clean_db):
|
|
"""Chaque expression traduite reconnaît dans PostgreSQL (~*, comme pour les
|
|
thèmes) exactement les textes que l'expression d'origine reconnaît avec les
|
|
réglages i, s et u de regex101 (Python re, mêmes règles sur ces exemples)."""
|
|
diffs = []
|
|
with psycopg.connect(clean_db["web"]) as conn:
|
|
for pcre, py, flags in DIFF:
|
|
pg = to_postgres(pcre)
|
|
py_flags = re.S if flags == -1 else re.I | re.S | flags
|
|
compiled = re.compile(py if py is not None else pcre, py_flags)
|
|
got = conn.execute("SELECT array_agg(t ~* %s ORDER BY i) FROM unnest(%s::text[]) WITH ORDINALITY u (t, i)",
|
|
(pg, TEXTS)).fetchone()[0]
|
|
for text, ok in zip(TEXTS, got):
|
|
if bool(compiled.search(text)) != ok:
|
|
diffs.append((pcre, pg, text, ok))
|
|
assert diffs == []
|
|
|
|
|
|
def test_themes_are_written_in_regex101_syntax(app_client, clean_db):
|
|
owner = clean_db["owner"]
|
|
with psycopg.connect(owner, autocommit=True) as conn:
|
|
# thème d'avant la 1.3.1 : syntaxe PostgreSQL, sans saisie gardée
|
|
conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Ancien', ARRAY['\\mchat\\M', '(?c)TV'])")
|
|
add_comments(owner, ["Un chat noir", "le château", "TV et tv", "tv seulement", "l'été arrive"])
|
|
login(app_client)
|
|
r = app_client.post("/themes", data={"name": "Été", "pattern": [r"\bété\b", r"\x{e9}t\xe9$"]}, headers=H,
|
|
follow_redirects=False)
|
|
assert r.status_code == 303, r.text
|
|
with psycopg.connect(clean_db["web"]) as conn:
|
|
rows = dict((r[0], r[1:]) for r in conn.execute(
|
|
"SELECT name, patterns, pattern_sources FROM shortstats.theme"))
|
|
assert rows["Été"] == ([r"\yété\y", U_E9 + "t" + U_E9 + r"(?=\n?\Z)"], [r"\bété\b", r"\x{e9}t\xe9$"])
|
|
assert rows["Ancien"][1] is None
|
|
page = app_client.get("/themes").text
|
|
# saisie réaffichée telle quelle ; ancien thème retraduit
|
|
assert 'value="\\bété\\b"' in page and 'value="\\x{e9}t\\xe9$"' in page
|
|
assert 'value="\\bchat\\b"' in page and 'value="(?-i)TV"' in page
|
|
assert "regex101" in page and "\\mchat" not in page
|
|
got = themes_of(owner)
|
|
assert got["rgx00000000"] == ["Ancien"] and got["rgx00000002"] == ["Ancien"] and got["rgx00000004"] == ["Été"]
|
|
# réenregistré depuis la page (expressions retraduites), l'ancien thème classe pareil
|
|
with psycopg.connect(clean_db["web"]) as conn:
|
|
tid = conn.execute("SELECT theme_id FROM shortstats.theme WHERE name = 'Ancien'").fetchone()[0]
|
|
r = app_client.post(f"/themes/{tid}", data={"name": "Ancien", "pattern": [r"\b(?=\w)chat\b(?<=\w)", "(?-i)TV"]},
|
|
headers=H, follow_redirects=False)
|
|
assert r.status_code == 303 and themes_of(owner) == got
|
|
|
|
|
|
def test_untranslatable_expressions_are_refused(app_client, clean_db):
|
|
login(app_client)
|
|
r = app_client.post("/themes", data={"name": "PG", "pattern": ["ok", r"\mchat\M", "a++", "(?>x)"]}, headers=H,
|
|
follow_redirects=False)
|
|
assert r.status_code == 400
|
|
page = r.text
|
|
assert "3 expression(s) régulière(s) invalide(s)" in page
|
|
assert "Sans équivalent dans la base : \\m (début de mot) est propre à PostgreSQL : écrivez \\b" in page
|
|
assert "quantificateur possessif" in page and "groupe atomique" in page
|
|
assert 'value="\\mchat\\M"' in page
|
|
with psycopg.connect(clean_db["web"]) as conn:
|
|
assert conn.execute("SELECT count(*) FROM shortstats.theme WHERE name = 'PG'").fetchone()[0] == 0
|
|
|
|
|
|
def test_live_check_shows_the_translation(app_client, clean_db):
|
|
add_comments(clean_db["owner"], ["Un chat", "château", "merci\n", "Café"])
|
|
login(app_client)
|
|
data = app_client.post("/api/themes/check", headers=H, json={
|
|
"patterns": [r"\bchat\b", r"\bch\w+", r"merci$", r"\x{e9}", r"\xe9", "a++", "("]}).json()
|
|
by = {p["pattern"]: p for p in data["patterns"]}
|
|
assert by[r"\bchat\b"] == {"pattern": r"\bchat\b", "ok": True, "error": None, "matches": 1,
|
|
"translated": r"\ychat\y"}
|
|
assert by[r"\bch\w+"]["matches"] == 2
|
|
assert by["merci$"]["matches"] == 1 and by["merci$"]["translated"] == r"merci(?=\n?\Z)"
|
|
# deux saisies, une même traduction : comptées chacune
|
|
assert by[r"\x{e9}"]["matches"] == by[r"\xe9"]["matches"] == 1
|
|
assert by["a++"]["ok"] is False and by["a++"]["error"].startswith("Sans équivalent dans la base : ")
|
|
assert by["a++"]["translated"] is None and by["a++"]["matches"] is None
|
|
assert by["("]["ok"] is False and "parenthèses" in by["("]["error"]
|
|
assert data["total"] == 4
|