CLI fuel-advisor (collect/status) avec verrou par collecteur, delais maximaux, durees et erreurs conservees, etat par source distinguant date de collecte et date d observation. Le planificateur interne n est plus qu une bibliotheque appelee par cron. Bouton renomme Actualiser maintenant, meme chemin et memes verrous. Installation versionnee dans deploy/ adaptee a busybox crond (Alpine).
107 lines
4.7 KiB
Python
107 lines
4.7 KiB
Python
"""Ordonnanceur : cadences propres à chaque source, fenêtres, supervision, résilience."""
|
||
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
import collector
|
||
import scheduler
|
||
import storage
|
||
|
||
|
||
def test_registry_covers_every_source_with_its_own_cadence():
|
||
expected = {
|
||
"local_prices",
|
||
"market_daily",
|
||
"ecb_fx",
|
||
"eu_bulletin",
|
||
"dgec_monthly",
|
||
"portwatch",
|
||
"news_geo",
|
||
"promotions",
|
||
}
|
||
assert expected <= set(scheduler.JOBS)
|
||
for name, job in scheduler.JOBS.items():
|
||
assert job["source"] and job["frequency"], name
|
||
assert job["cadence_seconds"] > 0, name
|
||
assert callable(job["window"]), name
|
||
assert hasattr(collector, job["func"]), name
|
||
assert scheduler.JOBS["local_prices"]["cadence_seconds"] == 3600, "prix locaux : toutes les heures"
|
||
assert scheduler.JOBS["news_geo"]["cadence_seconds"] == 7200, "actualités : toutes les 2 heures"
|
||
|
||
|
||
def test_job_is_due_only_within_its_window(store, monkeypatch):
|
||
monkeypatch.setattr(scheduler, "JOBS", dict(scheduler.JOBS, ecb_fx=dict(scheduler.JOBS["ecb_fx"])))
|
||
saturday = datetime(2026, 9, 12, 17, 0, tzinfo=timezone.utc) # samedi 19 h à Paris
|
||
monday_morning = datetime(2026, 9, 14, 8, 0, tzinfo=timezone.utc) # lundi 10 h
|
||
monday_evening = datetime(2026, 9, 14, 14, 30, tzinfo=timezone.utc) # lundi 16 h 30
|
||
assert scheduler.is_due("ecb_fx", now=monday_evening) is True
|
||
assert scheduler.is_due("ecb_fx", now=saturday) is False
|
||
assert scheduler.is_due("ecb_fx", now=monday_morning) is False
|
||
assert scheduler.is_due("local_prices", now=saturday) is True
|
||
|
||
|
||
def test_cadence_and_retry_after_failure(store):
|
||
now = datetime(2026, 9, 14, 12, 0, tzinfo=timezone.utc)
|
||
storage.job_record("news_geo", "src", "freq", 7200, "ok", now=now)
|
||
assert scheduler.is_due("news_geo", now=now + timedelta(minutes=30)) is False
|
||
assert scheduler.is_due("news_geo", now=now + timedelta(hours=2)) is True
|
||
storage.job_record("news_geo", "src", "freq", 7200, "error", now=now)
|
||
assert scheduler.is_due("news_geo", now=now + timedelta(minutes=31)) is True, "réessai après échec"
|
||
|
||
|
||
def test_next_run_respects_window(store):
|
||
sunday = datetime(2026, 9, 13, 10, 0, tzinfo=timezone.utc) # dimanche
|
||
upcoming = scheduler.next_run("eu_bulletin", now=sunday)
|
||
assert datetime.fromisoformat(upcoming).astimezone(storage.PARIS).weekday() == 3, "jeudi"
|
||
|
||
|
||
def test_run_records_supervision_and_survives_failures(store, monkeypatch):
|
||
calls = []
|
||
|
||
def good(force=False):
|
||
calls.append("local_prices")
|
||
return dict(status="ok", stored=3, last_observation_at="2026-09-12T18:00:00", detail="3 changements")
|
||
|
||
def broken(force=False):
|
||
calls.append("portwatch")
|
||
raise OSError("source hors ligne")
|
||
|
||
monkeypatch.setattr(collector, "job_local_prices", good)
|
||
monkeypatch.setattr(collector, "job_portwatch", broken)
|
||
monkeypatch.setattr(
|
||
scheduler,
|
||
"JOBS",
|
||
{
|
||
name: dict(scheduler.JOBS[name], window=lambda now=None: True)
|
||
for name in ("local_prices", "portwatch")
|
||
},
|
||
)
|
||
outcome = scheduler.run(names=["local_prices", "portwatch"], force=True)
|
||
# Un échec rend le bilan « partial » : le code retour de la commande sera non nul, ce que
|
||
# cron journalise, sans empêcher les autres collecteurs de tourner.
|
||
assert outcome["status"] == "partial"
|
||
assert outcome["failures"] == 1
|
||
assert outcome["results"]["local_prices"]["status"] == "ok"
|
||
assert outcome["results"]["portwatch"]["status"] == "error"
|
||
assert "job_local_prices" not in str(outcome)
|
||
state = storage.job_get("local_prices")
|
||
assert state["status"] == "ok" and state["stored"] == 3
|
||
assert state["last_observation_at"] == "2026-09-12T18:00:00"
|
||
assert state["last_success_at"] and state["next_run_at"]
|
||
failed = storage.job_get("portwatch")
|
||
assert failed["status"] == "error" and failed["fail_count"] == 1
|
||
assert "OSError" in failed["detail"]
|
||
# La dernière erreur est conservée, avec sa date et la durée de la tentative.
|
||
assert "source hors ligne" in failed["last_error"]
|
||
assert failed["last_error_at"] and failed["duration_s"] is not None
|
||
assert failed["last_attempt_at"]
|
||
assert state["duration_s"] is not None and state["items"] >= 0
|
||
|
||
|
||
def test_inventory_exposes_source_frequency_state_and_next_run(store):
|
||
rows = {row["name"]: row for row in scheduler.inventory()}
|
||
assert rows["local_prices"]["source"].startswith("prix-carburants.gouv.fr")
|
||
assert rows["eu_bulletin"]["frequency"].startswith("le jeudi")
|
||
assert rows["promotions"]["status"] == "never"
|
||
assert rows["dgec_monthly"]["next_run_at"]
|
||
assert "n’historise un événement" in rows["local_prices"]["note"]
|