173 lines
10 KiB
Python
173 lines
10 KiB
Python
"""1.3.0 : nouveau calendrier des relevés (migration 008) et diagrammes renumérotés."""
|
|
|
|
import json
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import psycopg
|
|
import pytest
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from shortstats import collector, migrate
|
|
from shortstats.config import MigrateConfig
|
|
from shortstats.web import charts, transfer
|
|
|
|
from .conftest import add_channel
|
|
from .fake_youtube import CHANNEL, OTHER, FakeYouTube
|
|
from .test_collector import NOW, client, iso
|
|
|
|
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)])
|
|
|
|
|
|
def test_new_schedule_in_python():
|
|
labels = [label for _, label, _ in charts.STEPS]
|
|
assert len(labels) == 151 == len(set(labels))
|
|
assert labels[:24] == [f"{h} h" for h in range(1, 25)]
|
|
assert labels[24:40] == ["1 j 3 h", "1 j 6 h", "1 j 9 h", "1 j 12 h", "1 j 15 h", "1 j 18 h", "1 j 21 h", "2 j",
|
|
"2 j 3 h", "2 j 6 h", "2 j 9 h", "2 j 12 h", "2 j 15 h", "2 j 18 h", "2 j 21 h", "3 j"]
|
|
assert labels[40:56] == ["3 j 6 h", "3 j 12 h", "3 j 18 h", "4 j", "4 j 6 h", "4 j 12 h", "4 j 18 h", "5 j",
|
|
"5 j 6 h", "5 j 12 h", "5 j 18 h", "6 j", "6 j 6 h", "6 j 12 h", "6 j 18 h", "7 j"]
|
|
assert labels[56:79] == [f"{d} j" for d in range(8, 31)]
|
|
assert labels[79:127] == [f"{w} sem." for w in range(5, 53)]
|
|
assert labels[127:] == [f"{m} mois" for m in range(13, 37)]
|
|
hours = [h for _, _, h in charts.STEPS]
|
|
assert hours == sorted(hours) and len(set(hours)) == 151
|
|
assert charts.J7_STEP == 56 and charts.STEP_BY_ID[56] == ("7 j", 168.0)
|
|
# rythme annoncé dans les menus
|
|
assert charts.step_period(24) == "Toutes les heures (1 à 24 h)"
|
|
assert charts.step_period(27) == "Toutes les 3 h (jusqu'à 3 j)"
|
|
assert charts.step_period(168) == "Toutes les 6 h (jusqu'à 7 j)"
|
|
assert charts.step_period(30 * 24) == "Tous les jours (8 à 30 j)"
|
|
assert charts.step_period(52 * 168) == "Toutes les semaines (5 à 52 sem.)"
|
|
assert charts.step_period(13 * 730.5) == "Tous les mois (13 à 36 mois)"
|
|
# les étapes à 3 chiffres sont des clés valables
|
|
assert charts.field("views@151").label == "Vues à 36 mois"
|
|
with pytest.raises(charts.ChartError):
|
|
charts.validate_config({"x": "views@152", "y": "views"})
|
|
|
|
|
|
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 charts.STEPS}
|
|
got = {OLD_LABELS[old - 1]: new[nid] for old, nid in charts.LEGACY_STEP_MAP.items()}
|
|
assert len(got) == 60 and len(set(charts.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 _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 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 charts.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()) == \
|
|
charts.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 charts.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():
|
|
charts.validate_config(cfg) # toujours valables
|
|
|
|
|
|
def test_collector_follows_new_schedule(clean_db):
|
|
add_channel(clean_db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
fake.add_short("sched000001", iso(NOW - timedelta(hours=7, minutes=10)), views=10, listed=False)
|
|
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
|
|
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status)
|
|
VALUES ('sched000001', %s, %s, 'pending')""", (CHANNEL, NOW - timedelta(hours=7, minutes=10)))
|
|
taken = []
|
|
with psycopg.connect(clean_db["collector"], autocommit=True) as conn:
|
|
# 7 h, 8 h, 9 h... : un relevé par heure le premier jour, puis toutes les 3 h
|
|
for minutes in [0] + [60 * k for k in range(1, 25)]:
|
|
collector.take_snapshots(conn, client(fake), NOW + timedelta(minutes=minutes))
|
|
taken = [r[0] for r in conn.execute(
|
|
"""SELECT st.label FROM shortstats.video_snapshot sn JOIN shortstats.snapshot_step st USING (step_id)
|
|
ORDER BY step_id""")]
|
|
assert taken[:4] == ["7 h", "8 h", "9 h", "10 h"] and "24 h" in taken
|
|
assert taken[-2:] == ["1 j 3 h", "1 j 6 h"] and "1 j 4 h" not in taken
|
|
# prochaine étape annoncée : selon le nouveau calendrier
|
|
with psycopg.connect(clean_db["web"]) as conn:
|
|
nxt = conn.execute("""SELECT st.label FROM shortstats.snapshot_step st JOIN shortstats.video v
|
|
ON st.step_id > v.snapshot_step ORDER BY st.step_id LIMIT 1""").fetchone()[0]
|
|
assert nxt == "1 j 9 h"
|
|
|
|
|
|
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": "step", "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"
|