Corrige la purge qui detruisait les archives, la completude du backfill et published_at
Purge: liste blanche explicite des origines purgables (live). Les archives importees et toute origine non declaree sont conservees, quelle que soit leur anciennete. Le backfill considere une annee complete seulement si ses lignes sont encore presentes (colonne stored) : une annee marquee reussie mais videe est restauree sans doublon. published_at: le bug positionnel de record_observations ecrivait le prix dans published_at et la date declaree dans fetched_at ; corrige, avec validation qui refuse une valeur numerique. Script de reparation avec trace dans db_maintenance (462+462 lignes). 311 tests.
This commit is contained in:
49
tests/test_backfill_restore.py
Normal file
49
tests/test_backfill_restore.py
Normal file
@@ -0,0 +1,49 @@
|
||||
"""Une année marquée réussie ne prouve rien : le backfill doit pouvoir la restaurer."""
|
||||
|
||||
from test_backfill import archive_bytes
|
||||
|
||||
import backfill
|
||||
import storage
|
||||
|
||||
|
||||
def prepare(monkeypatch):
|
||||
monkeypatch.setattr(backfill, "download_year", lambda year, timeout=None: archive_bytes())
|
||||
monkeypatch.setattr(backfill, "targets", lambda margin_deg=0.15, fuel=None: (None, set()))
|
||||
|
||||
|
||||
def test_incomplete_year_is_not_considered_done(store):
|
||||
"""Le bug : statut ok + lignes disparues => l'année doit repartir en import."""
|
||||
assert backfill.year_is_complete(2007, None) is False
|
||||
assert backfill.year_is_complete(2007, {"status": "ok", "stored": 0}) is False
|
||||
assert backfill.year_is_complete(2007, {"status": "ok", "stored": 5}) is False
|
||||
with store.connect() as db:
|
||||
db.execute(
|
||||
"INSERT INTO observations VALUES('1','Gazole','2007-01-04',1.0,'2007-01-04T10:00:00',"
|
||||
"'2026-09-15T09:00:00',44.0,-0.5,NULL,NULL,'archive:2007')"
|
||||
)
|
||||
assert backfill.year_is_complete(2007, {"status": "ok", "stored": 1}) is True
|
||||
|
||||
|
||||
def test_disappeared_year_is_restored_without_duplicates(store, monkeypatch):
|
||||
prepare(monkeypatch)
|
||||
first = backfill.backfill(years=[2007])
|
||||
imported = first["years"][0]["imported"]
|
||||
assert imported > 0
|
||||
assert store.archive_rows_present(2007) == imported
|
||||
|
||||
# Incident de purge : l'année disparaît alors que backfill_runs reste « ok ».
|
||||
with store.connect() as db:
|
||||
db.execute("DELETE FROM observations WHERE origin='archive:2007'")
|
||||
assert store.archive_rows_present(2007) == 0
|
||||
assert storage.backfill_runs()[2007]["status"] == "ok"
|
||||
assert storage.backfill_runs()[2007]["stored"] == imported
|
||||
|
||||
restored = backfill.backfill(years=[2007])
|
||||
assert restored["restored"] == [2007]
|
||||
assert store.archive_rows_present(2007) == imported
|
||||
|
||||
# Idempotent : une seconde passe ne recrée aucun doublon.
|
||||
again = backfill.backfill(years=[2007])
|
||||
assert again["years"] == []
|
||||
assert again["skipped"] == 1
|
||||
assert store.archive_rows_present(2007) == imported
|
||||
77
tests/test_published_at.py
Normal file
77
tests/test_published_at.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""published_at ne doit jamais contenir un prix : validation, ingestion, réparation."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
import repair_columns
|
||||
import storage
|
||||
|
||||
COLUMNS = "station_id,fuel,day,price,source_updated,collected_at,lat,lon,published_at,fetched_at,origin"
|
||||
|
||||
|
||||
def test_price_is_refused_as_publication_date(store):
|
||||
with pytest.raises(ValueError, match="prix"):
|
||||
store.valid_published_at("0.817")
|
||||
with pytest.raises(ValueError, match="prix"):
|
||||
store.valid_published_at("2.829")
|
||||
with pytest.raises(ValueError, match="date valide"):
|
||||
store.valid_published_at("pas une date")
|
||||
assert store.valid_published_at(None) is None
|
||||
assert store.valid_published_at("") is None
|
||||
assert store.valid_published_at("2026-09-04") == "2026-09-04"
|
||||
assert store.valid_published_at("2026-09-04T13:00:00+00:00").startswith("2026-09-04T13")
|
||||
|
||||
|
||||
def test_record_observations_writes_dates_not_prices(store):
|
||||
rows = [
|
||||
dict(id="1", lat=44.0, lon=-0.5, prices={"Gazole": 1.719}, updates={"Gazole": "2026-09-01T08:00:00"})
|
||||
]
|
||||
assert store.record_observations(rows) == 1
|
||||
with store.connect() as db:
|
||||
row = db.execute("SELECT * FROM observations").fetchone()
|
||||
assert row["published_at"] is None
|
||||
assert row["fetched_at"] == row["collected_at"]
|
||||
assert row["fetched_at"] != row["source_updated"]
|
||||
assert row["source_updated"] == "2026-09-01T08:00:00"
|
||||
assert row["price"] == pytest.approx(1.719)
|
||||
|
||||
|
||||
def test_repair_clears_legacy_corruption(store):
|
||||
"""Reproduit l'ancien bug positionnel, puis vérifie la réparation et sa trace."""
|
||||
with store.connect() as db:
|
||||
db.execute(
|
||||
f"INSERT INTO observations({COLUMNS}) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
"1",
|
||||
"Gazole",
|
||||
"2026-09-14",
|
||||
1.719,
|
||||
"2026-09-14T08:00:00",
|
||||
"2026-09-14T09:00:00",
|
||||
44.0,
|
||||
-0.5,
|
||||
"1.719",
|
||||
"2026-09-14T08:00:00",
|
||||
"live",
|
||||
),
|
||||
)
|
||||
survey = repair_columns.survey()
|
||||
assert survey["published_at_non_dates"] == 1
|
||||
assert survey["fetched_at_permute"] == 1
|
||||
|
||||
assert repair_columns.repair(apply=False)["applied"] is False
|
||||
|
||||
result = repair_columns.repair(apply=True, now=datetime(2026, 9, 15, tzinfo=timezone.utc))
|
||||
assert result["cleared_published_at"] == 1
|
||||
assert result["restored_fetched_at"] == 1
|
||||
assert result["apres"]["published_at_non_dates"] == 0
|
||||
assert result["apres"]["fetched_at_permute"] == 0
|
||||
with store.connect() as db:
|
||||
row = db.execute("SELECT * FROM observations").fetchone()
|
||||
assert row["published_at"] is None
|
||||
assert row["fetched_at"] == "2026-09-14T09:00:00"
|
||||
assert row["price"] == pytest.approx(1.719)
|
||||
trace = storage.maintenance_log()
|
||||
assert trace and trace[0]["operation"] == "repair_observation_columns"
|
||||
assert trace[0]["affected"] == 2
|
||||
57
tests/test_retention.py
Normal file
57
tests/test_retention.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""Rétention : seules les collectes courantes sont purgées, jamais les archives."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import collector
|
||||
|
||||
COLUMNS = "station_id,fuel,day,price,source_updated,collected_at,lat,lon,published_at,fetched_at,origin"
|
||||
|
||||
|
||||
def insert(store, station, day, origin, declared="2026-09-15T08:00:00", price=1.7):
|
||||
with store.connect() as db:
|
||||
db.execute(
|
||||
f"INSERT INTO observations({COLUMNS}) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
station,
|
||||
"Gazole",
|
||||
day,
|
||||
price,
|
||||
declared,
|
||||
"2026-09-15T09:00:00",
|
||||
44.0,
|
||||
-0.5,
|
||||
None,
|
||||
"2026-09-15T09:00:00",
|
||||
origin,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_old_archive_row_survives_purge(store):
|
||||
"""Une archive de 2008 doit survivre même vieille de plus de 730 jours."""
|
||||
insert(store, "1", "2008-05-05", "archive:2008")
|
||||
insert(store, "2", "2026-09-10", "live")
|
||||
purged = collector.purge_old_observations(now=datetime(2026, 9, 15, tzinfo=timezone.utc))
|
||||
assert purged == 0
|
||||
assert store.archive_rows_present(2008) == 1
|
||||
with store.connect() as db:
|
||||
assert db.execute("SELECT count(*) FROM observations").fetchone()[0] == 2
|
||||
|
||||
|
||||
def test_old_live_row_is_purged(store):
|
||||
"""La collecte courante, elle, reste soumise à la rétention."""
|
||||
insert(store, "1", "2024-01-01", "live")
|
||||
insert(store, "2", "2024-01-01", "archive:2024")
|
||||
purged = collector.purge_old_observations(now=datetime(2026, 9, 15, tzinfo=timezone.utc))
|
||||
assert purged == 1
|
||||
with store.connect() as db:
|
||||
remaining = [row[0] for row in db.execute("SELECT origin FROM observations")]
|
||||
assert remaining == ["archive:2024"]
|
||||
|
||||
|
||||
def test_unknown_origin_is_never_purged(store):
|
||||
"""Seule la liste blanche est purgée : une origine non déclarée est conservée."""
|
||||
insert(store, "9", "2015-01-01", "future:origine")
|
||||
assert collector.purge_old_observations(now=datetime(2026, 9, 15, tzinfo=timezone.utc)) == 0
|
||||
with store.connect() as db:
|
||||
assert db.execute("SELECT count(*) FROM observations").fetchone()[0] == 1
|
||||
Reference in New Issue
Block a user