"""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