shortstats/tests/non_regression/test_migrations.py
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

249 lines
15 KiB
Python

"""Migrations rejouées sur une base de la version précédente : aucune donnée perdue."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import psycopg
import pytest
from psycopg.types.json import Jsonb
from shortstats import comment_themes, migrate
from shortstats.config import MigrateConfig
from shortstats.web import chart_catalog, chart_config
from ..outils.base import add_pinned
from ..outils.fake_youtube import CHANNEL, OTHER
from ..outils.site import CH
@pytest.fixture()
def before_010(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="009")
yield clean_db
migrate.run(_owner_cfg(owner))
def _owner_cfg(url):
return MigrateConfig(database_url=url, timezone="Europe/Paris",
collector_role="shortstats_collector", web_role="shortstats_web")
@pytest.fixture()
def legacy_db(clean_db):
"""Base remise à l'état 1.2.5 (migrations 001 à 007), puis rendue à jour par le test."""
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="007")
yield clean_db
migrate.run(_owner_cfg(owner)) # quoi qu'il arrive, la base finit à jour
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
@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))
@pytest.fixture()
def before_011(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="010")
yield clean_db
migrate.run(_owner_cfg(owner))
def test_migration_008_keeps_every_snapshot(legacy_db):
owner = legacy_db["owner"]
pub = datetime(2023, 1, 2, 12, 0, tzinfo=timezone.utc)
with psycopg.connect(owner, autocommit=True) as conn:
assert conn.execute("SELECT count(*) FROM shortstats.snapshot_step").fetchone()[0] == 60
conn.execute("INSERT INTO shortstats.channel (channel_id, author_channel_id) VALUES (%s, %s)", (CHANNEL, OTHER))
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, snapshot_step)
VALUES ('legacy00001', %s, %s, 'too_old', 27), ('legacy00002', %s, %s, 'too_old', 18)""",
(CHANNEL, pub, CHANNEL, pub))
# un relevé à chacune des 60 anciennes étapes, valeur = ancien numéro
for sid in range(1, 61):
conn.execute("""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count)
SELECT 'legacy00001', step_id, %s + age, nominal_hours, %s
FROM shortstats.snapshot_step WHERE step_id = %s""", (pub, sid, sid))
configs = {
"j7": {"x": "views@6", "y": "views@18", "y_more": ["views@26", "likes@37", "views"],
"defaults": {"filters": {"views@6": {"min": 1, "max": 9}, "duration": {"min": 1, "max": 50}}}},
"evo": {"source": "evolution", "x": "age", "y": "views",
"defaults": {"filters": {"age": {"min": 7, "max": 26}}, "individual": True}},
"plain": {"x": "publish_date", "y": "views", "title": "views@6 reste un titre"},
}
for name, cfg in configs.items():
conn.execute("INSERT INTO shortstats.chart (config, created_by) VALUES (%s, %s)", (Jsonb(cfg), name))
applied = migrate.run(_owner_cfg(owner))
assert applied[0] == "008_snapshot_schedule.sql"
new = {sid: label for sid, label, _ in chart_catalog.STEPS}
with psycopg.connect(owner) as conn:
assert conn.execute("SELECT count(*) FROM shortstats.snapshot_step").fetchone()[0] == 151
# même correspondance que celle du site (import des anciens exports)
assert dict(conn.execute("SELECT old_id, new_id FROM shortstats.step_map_v1").fetchall()) == \
chart_config.LEGACY_STEP_MAP
rows = conn.execute("""SELECT sn.view_count, st.label, sn.age_hours::float FROM shortstats.video_snapshot sn
JOIN shortstats.snapshot_step st USING (step_id) ORDER BY st.step_id""").fetchall()
assert len(rows) == 60 # aucun relevé perdu
assert [r[0] for r in rows] == list(range(1, 61)) # ordre chronologique conservé
by_old = {r[0]: r[1] for r in rows}
assert by_old[18] == "7 j" and by_old[26] == "9 sem." and by_old[60] == "36 mois"
assert all(by_old[old] == new[nid] for old, nid in chart_config.LEGACY_STEP_MAP.items())
assert dict((r[0], r[2]) for r in rows)[26] == 1461.0 # âge réel inchangé (2 mois)
steps = dict(conn.execute("SELECT video_id, snapshot_step FROM shortstats.video").fetchall())
assert new[steps["legacy00001"]] == "13 sem." and new[steps["legacy00002"]] == "7 j"
saved = dict(conn.execute("SELECT created_by, config FROM shortstats.chart").fetchall())
assert saved["j7"]["x"] == "views@6" and saved["j7"]["y"] == "views@56"
assert saved["j7"]["y_more"] == ["views@84", "likes@128", "views"]
assert saved["j7"]["defaults"]["filters"] == {"views@6": {"min": 1, "max": 9}, "duration": {"min": 1, "max": 50}}
assert saved["evo"]["defaults"] == {"filters": {"age": {"min": 9, "max": 84}}, "individual": True}
assert saved["plain"] == configs["plain"]
for cfg in saved.values():
chart_config.validate_config(cfg) # toujours valables
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_migration_010(before_010):
owner = before_010["owner"]
pub = datetime.now(timezone.utc) - timedelta(hours=5, minutes=10)
with psycopg.connect(owner, autocommit=True) as conn:
conn.execute("INSERT INTO shortstats.channel (channel_id, author_channel_id) VALUES (%s, %s)", (CHANNEL, CHANNEL))
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, snapshot_step,
comment_count, author_comment_status, author_comment_text,
collected_at)
VALUES ('vid00000001', %s, %s, 'pending', 2, NULL, NULL, NULL, NULL),
('vid00000002', %s, %s, 'collected', NULL, 7, 'found', 'frieren', now())""",
(CHANNEL, pub, CHANNEL, pub - timedelta(days=400)))
conn.execute("""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, comment_count)
VALUES ('vid00000001', 1, %s, 1, 0), ('vid00000001', 2, %s, 2, 4)""",
(pub + timedelta(hours=1), pub + timedelta(hours=2)))
from psycopg.types.json import Jsonb
conn.execute("INSERT INTO shortstats.chart (config, created_by) VALUES (%s, 'a'), (%s, 'a'), (%s, 'a')", (
Jsonb({"x": "theme", "y": "views", "color": "channel"}),
Jsonb({"x": "publish_date", "y": "views", "color": "theme_each",
"defaults": {"filters": {"theme": {"values": ["x"]}, "views": {"min": 1}}}}),
Jsonb({"source": "evolution", "x": "age", "y": "views", "color": "comment_likes"}),
))
assert migrate.run(_owner_cfg(owner), stop_after="010") == ["010_comment_themes.sql"]
with psycopg.connect(owner) as conn:
cols = {r[0] for r in conn.execute("""SELECT column_name FROM information_schema.columns
WHERE table_schema = 'shortstats' AND table_name = 'video'""")}
assert not {c for c in cols if c.startswith("author_comment") or c == "comment_author_channel_id"}
assert conn.execute("SELECT to_regclass('shortstats.video_theme')").fetchone()[0] is None
assert conn.execute("SELECT comment_scope FROM shortstats.channel").fetchone()[0] == "top"
v = dict((r[0], r[1:]) for r in conn.execute(
"""SELECT v.video_id, v.comment_count_latest, st.label FROM shortstats.video v
LEFT JOIN shortstats.snapshot_step st ON st.step_id = v.next_step ORDER BY 1"""))
assert v["vid00000001"] == (4, "3 h") and v["vid00000002"] == (7, "1 h")
assert conn.execute("SELECT array_agg(comments_read ORDER BY step_id) FROM shortstats.video_snapshot"
).fetchone()[0] == [0, None]
charts = [r[0] for r in conn.execute("SELECT config FROM shortstats.chart ORDER BY chart_id")]
assert charts[0] == {"x": "pinned_theme", "y": "views", "color": "channel"}
assert charts[1] == {"x": "publish_date", "y": "views", "defaults": {"filters": {"views": {"min": 1}}}}
assert charts[2] == {"source": "evolution", "x": "age", "y": "views"}
def test_migration_011(before_011):
owner = before_011["owner"]
pub = datetime(2026, 9, 1, 12, 0, tzinfo=timezone.utc)
with psycopg.connect(owner, autocommit=True) as conn:
conn.execute("INSERT INTO shortstats.channel (channel_id) VALUES (%s)", (CH,))
conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Tarte', ARRAY['\\mapple ?pie\\M'])")
for vid, count in (("late0000001", 4), ("empt0000001", 0)):
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status,
comment_count_latest, comment_count_read, comments_read_at, comment_scope_read)
VALUES (%s, %s, %s, 'pending', %s, %s, %s, %s)""",
(vid, CH, pub, count, 4 if count else None,
pub + timedelta(hours=6, minutes=1) if count else None, "top" if count else None))
conn.execute("""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count,
like_count, comment_count)
VALUES (%s, 6, %s, 6.02, 100, 10, %s)""", (vid, pub + timedelta(hours=6, minutes=1), count))
for i, minutes in enumerate((20, 90, 150, 330)):
conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text)
VALUES (%s, 'late0000001', %s, %s)""",
(f"late0000001-{i}", pub + timedelta(minutes=minutes), "Apple Pie" if i % 2 == 0 else "autre"))
comment_themes.classify(conn, [f"late0000001-{i}" for i in range(4)])
conn.execute("UPDATE shortstats.video_snapshot SET comments_read = 4 WHERE video_id = 'late0000001'")
conn.execute("""INSERT INTO shortstats.snapshot_theme (video_id, step_id, theme_id, comments)
SELECT 'late0000001', 6, theme_id, 2 FROM shortstats.theme WHERE name = 'Tarte'""")
assert migrate.run(_owner_cfg(owner)) == ["011_comment_steps.sql"]
def snapshot(conn):
est = conn.execute("""SELECT video_id, step_id, taken_at, age_hours, comments_read
FROM shortstats.comment_estimate ORDER BY 1, 2""").fetchall()
themes = conn.execute("SELECT video_id, step_id, theme_id, comments FROM shortstats.snapshot_theme "
"ORDER BY 1, 2, 3").fetchall()
reads = conn.execute("SELECT video_id, step_id, comments_read FROM shortstats.video_snapshot "
"ORDER BY 1, 2").fetchall()
return est, themes, reads
with psycopg.connect(owner, autocommit=True) as conn:
migrated = snapshot(conn)
est, themes, reads = migrated
# vidéo sans commentaire : 0 jusqu'à son dernier relevé (6 h) ; l'autre, d'après les dates
assert [(v, s, n) for v, s, _t, _a, n in est] == [("empt0000001", s, 0) for s in range(1, 6)] + [
("late0000001", 1, 1), ("late0000001", 2, 2), ("late0000001", 3, 3), ("late0000001", 4, 3),
("late0000001", 5, 3)]
assert [(v, s, n) for v, s, _t, n in themes] == [("late0000001", s, n) for s, n in
((1, 1), (2, 1), (3, 2), (4, 2), (5, 2), (6, 2))]
assert reads == [("empt0000001", 6, 0), ("late0000001", 6, 4)]
v = conn.execute("""SELECT comment_count_read, comment_scope_read, comments_read_at IS NOT NULL
FROM shortstats.video WHERE video_id = 'empt0000001'""").fetchone()
assert v == (0, "top", True)
# mêmes résultats que le calcul du collecteur
with conn.transaction():
comment_themes.refresh_videos(conn, ["late0000001", "empt0000001"])
assert snapshot(conn) == migrated
assert conn.execute("SELECT pattern_sources FROM shortstats.theme").fetchone()[0] is None
with pytest.raises(psycopg.errors.CheckViolation):
conn.execute("UPDATE shortstats.theme SET pattern_sources = ARRAY['a', 'b']")
def test_migration_renumbers_positions_per_owner(clean_db):
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
assert conn.execute("SELECT 1 FROM pg_indexes WHERE indexname = 'chart_owner_idx'").fetchone()