Ordonnanceur multi-frequences, supervision, promotions et metadonnees temporelles
Chaque source a sa cadence et sa fenetre (prix locaux horaires 24/7, BCE jours ouvres apres 16h15, bulletin UE le jeudi, DGEC mensuel avec detection de nouvelle periode, PortWatch quotidien avec fenetre glissante pour les revisions, actualites toutes les 2 heures, promotions 3 fois par jour). Supervision persistante (table jobs) exposee par /api/jobs et une fenetre dediee. Evenements prix uniquement en cas de changement de prix ou d horodatage declare, actualisation forcee du flux local au-dela de 15 minutes lors d un conseil. Extraction Ollama (mistral-small3.2:24b) des actualites geopolitiques et des operations commerciales, sans jamais decider du conseil, avec observed_at, published_at, fetched_at, valid_from et valid_until distincts.
This commit is contained in:
@@ -1,23 +1,32 @@
|
||||
"""Fixtures partagées : aucune base de production, aucun accès réseau."""
|
||||
"""Fixtures partagées : aucune base de production, aucun accès réseau, aucun appel de modèle."""
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
|
||||
import brands
|
||||
import llm
|
||||
import market
|
||||
import news
|
||||
import promotions
|
||||
import storage
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_database(tmp_path, monkeypatch):
|
||||
"""Toutes les bases pointent vers un fichier temporaire, jamais /var/lib."""
|
||||
def isolated_environment(tmp_path, monkeypatch):
|
||||
"""Bases temporaires, aucune source réseau, aucun appel Ollama."""
|
||||
for module in (storage, brands, market):
|
||||
monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3")
|
||||
# Aucun test ne doit interroger Nominatim ou un fournisseur de cours.
|
||||
monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: [])
|
||||
monkeypatch.setattr(market, "PROVIDERS", {})
|
||||
# Aucun test ne doit sortir sur le réseau pour les sources amont.
|
||||
monkeypatch.setattr(news, "gather", lambda *args, **kwargs: ([], []))
|
||||
monkeypatch.setattr(promotions, "gather", lambda *args, **kwargs: ([], []))
|
||||
monkeypatch.setattr(
|
||||
llm,
|
||||
"extract",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("Ollama non appelé pendant les tests")),
|
||||
)
|
||||
monkeypatch.setattr(llm, "available", lambda *args, **kwargs: [])
|
||||
collector = importlib.import_module("collector")
|
||||
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
||||
return tmp_path
|
||||
|
||||
194
tests/test_collectors.py
Normal file
194
tests/test_collectors.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Événements prix (changement uniquement), actualités structurées et opérations commerciales."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
import collector
|
||||
import llm
|
||||
import news
|
||||
import promotions
|
||||
import storage
|
||||
|
||||
|
||||
def flux_row(price=1.9, declared="2026-09-12 08:00:00", station="S1", fuel="Gazole"):
|
||||
return {
|
||||
"id": station,
|
||||
"name": "RUE TEST",
|
||||
"city": "Nantes",
|
||||
"lat": 48.8,
|
||||
"lon": 2.3,
|
||||
"prices": {fuel: price},
|
||||
"updates": {fuel: declared},
|
||||
}
|
||||
|
||||
|
||||
def test_price_events_only_on_change(store):
|
||||
now = datetime(2026, 9, 12, 10, 0, tzinfo=timezone.utc)
|
||||
assert storage.record_price_events([flux_row()], now) == 1, "première observation"
|
||||
assert storage.record_price_events([flux_row()], now + timedelta(hours=1)) == 0, "identique"
|
||||
assert storage.record_price_events([flux_row(price=1.87)], now + timedelta(hours=2)) == 1
|
||||
assert storage.record_price_events([flux_row(price=1.87)], now + timedelta(hours=3)) == 0
|
||||
assert (
|
||||
storage.record_price_events(
|
||||
[flux_row(price=1.87, declared="2026-09-12 12:00:00")], now + timedelta(hours=4)
|
||||
)
|
||||
== 1
|
||||
), "nouvel horodatage déclaré par la station"
|
||||
events = storage.price_events(days=30)
|
||||
assert len(events) == 3, "pas de doublon pour un prix identique"
|
||||
baisse = [event for event in events if event["price"] == 1.87 and event["previous_price"] == 1.9]
|
||||
assert len(baisse) == 1, "baisse de 3 c€ enregistrée"
|
||||
redeclared = [event for event in events if event["declared_at"] == "2026-09-12 12:00:00"][0]
|
||||
assert redeclared["price"] == 1.87 and redeclared["previous_price"] == 1.87, (
|
||||
"même prix mais nouvel horodatage déclaré"
|
||||
)
|
||||
assert redeclared["fetched_at"] and redeclared["fetched_at"] != redeclared["declared_at"], (
|
||||
"la date de téléchargement ne remplace pas la date d’observation"
|
||||
)
|
||||
assert redeclared["source"].startswith("prix-carburants.gouv.fr")
|
||||
|
||||
|
||||
def test_local_prices_job_needs_favorites_and_records_events(store):
|
||||
assert collector.job_local_prices(load=lambda: [flux_row()])["status"] == "unchanged"
|
||||
store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=5))
|
||||
out = collector.job_local_prices(load=lambda: [flux_row()])
|
||||
assert out["status"] == "ok" and out["events"] == 1
|
||||
assert out["last_observation_at"] == "2026-09-12 08:00:00"
|
||||
assert collector.job_local_prices(load=lambda: [flux_row()])["events"] == 0
|
||||
|
||||
|
||||
def test_rss_articles_keep_publication_date_and_source():
|
||||
xml = b"""<?xml version="1.0"?><rss version="2.0"><channel>
|
||||
<item><title>Attaque en mer Rouge sur un pétrolier</title>
|
||||
<link>https://exemple.fr/a1</link><pubDate>Fri, 11 Sep 2026 09:30:00 GMT</pubDate>
|
||||
<source>Agence Test</source><description><p>Un pétrolier visé.</p></description></item>
|
||||
</channel></rss>"""
|
||||
articles = news.parse_rss(xml, "Google News", "suez_babelmandeb")
|
||||
assert len(articles) == 1
|
||||
article = articles[0]
|
||||
assert article["published_at"] == "2026-09-11", "date de publication conservée"
|
||||
assert article["observed_at"] == "2026-09-11"
|
||||
assert article["source"] == "Agence Test"
|
||||
assert "<" not in article["title"] and "pétrolier" in article["title"]
|
||||
assert len(article["hash"]) == 32
|
||||
|
||||
|
||||
def test_news_only_calls_llm_for_new_articles(store, monkeypatch):
|
||||
article = dict(
|
||||
hash="h1",
|
||||
url="https://exemple.fr/a1",
|
||||
title="Ormuz bloqué",
|
||||
topic="ormuz",
|
||||
source="Test",
|
||||
published_at="2026-09-11",
|
||||
observed_at="2026-09-11",
|
||||
summary="Détroit fermé.",
|
||||
)
|
||||
monkeypatch.setattr(news, "gather", lambda *a, **k: ([article], []))
|
||||
calls = []
|
||||
|
||||
def fake_extract(prompt, models=None):
|
||||
calls.append(prompt)
|
||||
return {
|
||||
"pertinent": True,
|
||||
"evenements": [
|
||||
{
|
||||
"type": "chokepoint",
|
||||
"direction": "hausse",
|
||||
"magnitude": "forte",
|
||||
"carburants": ["gazole"],
|
||||
"zone": "Ormuz",
|
||||
"horizon_jours": 12,
|
||||
"confiance": 0.7,
|
||||
"debut": "2026-09-11",
|
||||
"fin": None,
|
||||
}
|
||||
],
|
||||
}, "mistral-small3.2:24b"
|
||||
|
||||
monkeypatch.setattr(llm, "extract", fake_extract)
|
||||
first = news.collect()
|
||||
assert first["analysed"] == 1 and first["events"] == 1
|
||||
assert len(calls) == 1
|
||||
second = news.collect()
|
||||
assert second["analysed"] == 0, "aucun nouvel article, aucun appel au modèle"
|
||||
assert len(calls) == 1
|
||||
events = storage.news_events()
|
||||
assert events[0]["direction"] == "hausse"
|
||||
assert events[0]["valid_from"] == "2026-09-11" and events[0]["valid_until"] == "2026-09-23"
|
||||
assert events[0]["source_url"] == "https://exemple.fr/a1", "aucun signal sans source"
|
||||
assert events[0]["extracted_by"] == "mistral-small3.2:24b"
|
||||
|
||||
|
||||
def test_news_rejects_unrelated_article(store, monkeypatch):
|
||||
article = dict(
|
||||
hash="h2",
|
||||
url="https://exemple.fr/a2",
|
||||
title="Recette de cuisine",
|
||||
topic="ormuz",
|
||||
source="Test",
|
||||
published_at="2026-09-11",
|
||||
observed_at="2026-09-11",
|
||||
summary="Gâteau.",
|
||||
)
|
||||
monkeypatch.setattr(news, "gather", lambda *a, **k: ([article], []))
|
||||
monkeypatch.setattr(llm, "extract", lambda prompt, models=None: ({"pertinent": False}, "m"))
|
||||
out = news.collect()
|
||||
assert out["events"] == 0 and storage.news_events() == []
|
||||
|
||||
|
||||
def test_promotions_extraction_keeps_only_sourced_and_known_brands(store, monkeypatch):
|
||||
article = dict(
|
||||
hash="p1",
|
||||
url="https://exemple.fr/promo",
|
||||
title="Carburant à prix coûtant chez E.Leclerc",
|
||||
topic="_general",
|
||||
source="Test",
|
||||
published_at="2026-09-12",
|
||||
observed_at="2026-09-12",
|
||||
summary="Ce week-end, E.Leclerc vend le gazole à prix coûtant.",
|
||||
)
|
||||
monkeypatch.setattr(promotions, "gather", lambda use_gdelt=True: ([article], []))
|
||||
monkeypatch.setattr(
|
||||
llm,
|
||||
"extract",
|
||||
lambda prompt, models=None: (
|
||||
{
|
||||
"operations": [
|
||||
{
|
||||
"enseigne": "E.Leclerc",
|
||||
"nature": "prix_coutant",
|
||||
"remise_par_litre": None,
|
||||
"carburants": ["gazole"],
|
||||
"zone": "France",
|
||||
"debut": "2026-09-13",
|
||||
"fin": "2026-09-14",
|
||||
"confiance": 0.9,
|
||||
},
|
||||
{"enseigne": "Enseigne Inventée", "nature": "remise_litre", "debut": "2026-09-13"},
|
||||
]
|
||||
},
|
||||
"mistral-small3.2:24b",
|
||||
),
|
||||
)
|
||||
out = promotions.collect()
|
||||
assert out["promotions"] == 1, "enseigne absente du texte rejetée"
|
||||
rows = storage.promotions(today=datetime(2026, 9, 13, tzinfo=timezone.utc).date())
|
||||
assert rows[0]["brand"] == "E.Leclerc"
|
||||
assert rows[0]["valid_from"] == "2026-09-13" and rows[0]["valid_until"] == "2026-09-14"
|
||||
assert rows[0]["confidence"] == pytest.approx(0.9)
|
||||
assert rows[0]["source_url"] == "https://exemple.fr/promo"
|
||||
assert rows[0]["observed_at"] == "2026-09-12"
|
||||
active = promotions.active(today=datetime(2026, 9, 13, tzinfo=timezone.utc).date())
|
||||
assert active[0]["state"] == "en cours"
|
||||
announced = promotions.active(today=datetime(2026, 9, 12, tzinfo=timezone.utc).date())
|
||||
assert announced[0]["state"] == "annoncée"
|
||||
|
||||
|
||||
def test_llm_json_parsing_tolerates_wrapping():
|
||||
data, _ = llm.parse_json('```json\n{"pertinent": true, "evenements": []}\n```'), None
|
||||
assert data["pertinent"] is True
|
||||
assert llm.parse_json('Voici : {"a": 1} voilà') == {"a": 1}
|
||||
with pytest.raises(ValueError):
|
||||
llm.parse_json("aucun json ici")
|
||||
@@ -122,12 +122,63 @@ def test_http_history_exposes_average_and_stations(server, store):
|
||||
assert out["stations_series"][0]["station_id"] == "A"
|
||||
|
||||
|
||||
def test_http_jobs_inventory_exposes_sources_and_schedules(server):
|
||||
code, out = request(server, "GET", "/api/jobs")
|
||||
assert code == 200
|
||||
jobs = {job["name"]: job for job in out["jobs"]}
|
||||
assert jobs["local_prices"]["source"].startswith("prix-carburants.gouv.fr")
|
||||
assert jobs["local_prices"]["frequency"] == "chaque heure, 24/7, pour chaque zone favorite"
|
||||
assert jobs["eu_bulletin"]["frequency"] == "le jeudi (publication hebdomadaire)"
|
||||
assert jobs["news_geo"]["frequency"] == "toutes les 2 heures"
|
||||
assert jobs["ecb_fx"]["frequency"].startswith("jours ouvrés")
|
||||
for job in jobs.values():
|
||||
assert job["next_run_at"] and job["status"] in ("never", "ok", "unchanged", "error")
|
||||
|
||||
|
||||
def test_http_advice_reports_refresh_and_promotions(server, store, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
app.collector,
|
||||
"ensure_fresh_local",
|
||||
lambda max_age_seconds=900: dict(refreshed=True, age_seconds=1200.0),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
app.promotions,
|
||||
"active",
|
||||
lambda: [
|
||||
dict(
|
||||
brand="E.Leclerc",
|
||||
nature="prix_coutant",
|
||||
fuels="Gazole",
|
||||
state="en cours",
|
||||
valid_from="2026-09-12",
|
||||
valid_until="2026-09-13",
|
||||
stations="",
|
||||
source_url="https://exemple.fr/promo",
|
||||
confidence=0.9,
|
||||
discount_per_liter=None,
|
||||
)
|
||||
],
|
||||
)
|
||||
row = sample(datetime.now(timezone.utc))
|
||||
row.update(name="A", city="Paris", address="Rue")
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [row])
|
||||
code, out = request(
|
||||
server, "POST", "/api/advice", {"lat": 48.8, "lon": 2.3, "radius_km": 15, "fuel": "Gazole"}
|
||||
)
|
||||
assert code == 200
|
||||
assert out["local_refresh"]["refreshed"] is True
|
||||
assert out["promotions"][0]["brand"] == "E.Leclerc"
|
||||
assert "pas forcément la moins chère" in out["promotions_note"]
|
||||
|
||||
|
||||
def test_http_ui_and_validation(server):
|
||||
status, html = request(server, "GET", "/")
|
||||
assert status == 200
|
||||
assert "Autonomie restante" in html
|
||||
assert "Mes favoris" in html
|
||||
assert "Supervision" in html
|
||||
code, js = request(server, "GET", "/ui.js")
|
||||
assert "loadJobs" in js and "promotionsBlock" in js
|
||||
assert code == 200
|
||||
assert "stationCards" in js and "averageChart" in js
|
||||
assert (
|
||||
|
||||
98
tests/test_scheduler.py
Normal file
98
tests/test_scheduler.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""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)
|
||||
assert outcome["status"] == "ok"
|
||||
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"]
|
||||
|
||||
|
||||
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"]
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
@@ -22,89 +23,139 @@ def make_xlsx(sheet_name, cells, strings=None):
|
||||
|
||||
sheet_rows = {}
|
||||
for ref in list(numeric) + list(text_values):
|
||||
row = ''.join(ch for ch in ref if ch.isdigit())
|
||||
row = "".join(ch for ch in ref if ch.isdigit())
|
||||
sheet_rows.setdefault(int(row), []).append(cell_xml(ref, {**numeric, **text_values}[ref]))
|
||||
body = ''.join(f'<row r="{number}">{"".join(cells_xml)}</row>' for number, cells_xml in sorted(sheet_rows.items()))
|
||||
shared_xml = ('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
+ ''.join(f'<si><t>{value}</t></si>' for value in shared) + '</sst>')
|
||||
workbook = ('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
f'<sheets><sheet name="{sheet_name}" sheetId="1" r:id="rId1"/></sheets></workbook>')
|
||||
rels = ('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>')
|
||||
sheet = ('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
f'<sheetData>{body}</sheetData></worksheet>')
|
||||
body = "".join(
|
||||
f'<row r="{number}">{"".join(cells_xml)}</row>' for number, cells_xml in sorted(sheet_rows.items())
|
||||
)
|
||||
shared_xml = (
|
||||
'<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
+ "".join(f"<si><t>{value}</t></si>" for value in shared)
|
||||
+ "</sst>"
|
||||
)
|
||||
workbook = (
|
||||
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
|
||||
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
f'<sheets><sheet name="{sheet_name}" sheetId="1" r:id="rId1"/></sheets></workbook>'
|
||||
)
|
||||
rels = (
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>'
|
||||
)
|
||||
sheet = (
|
||||
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
f"<sheetData>{body}</sheetData></worksheet>"
|
||||
)
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, 'w') as archive:
|
||||
archive.writestr('xl/workbook.xml', workbook)
|
||||
archive.writestr('xl/_rels/workbook.xml.rels', rels)
|
||||
archive.writestr('xl/sharedStrings.xml', shared_xml)
|
||||
archive.writestr('xl/worksheets/sheet1.xml', sheet)
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("xl/workbook.xml", workbook)
|
||||
archive.writestr("xl/_rels/workbook.xml.rels", rels)
|
||||
archive.writestr("xl/sharedStrings.xml", shared_xml)
|
||||
archive.writestr("xl/worksheets/sheet1.xml", sheet)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_excel_date_conversion_and_rejection():
|
||||
assert upstream.excel_date(42005) == '2015-01-01'
|
||||
assert upstream.excel_date(46272) == '2026-09-07'
|
||||
assert upstream.excel_date('2025') is None
|
||||
assert upstream.excel_date(42005) == "2015-01-01"
|
||||
assert upstream.excel_date(46272) == "2026-09-07"
|
||||
assert upstream.excel_date("2025") is None
|
||||
assert upstream.excel_date(None) is None
|
||||
|
||||
|
||||
def test_parse_dgec_brent_keeps_monthly_rows_only():
|
||||
raw = make_xlsx('Cours du Brent', {'A3': 42005, 'B3': 47.708, 'A4': 42036, 'B4': 58.0955, 'A157': '2025', 'B157': 69.1})
|
||||
raw = make_xlsx(
|
||||
"Cours du Brent",
|
||||
{"A3": 42005, "B3": 47.708, "A4": 42036, "B4": 58.0955, "A157": "2025", "B157": 69.1},
|
||||
)
|
||||
out = upstream.parse_dgec_brent(raw)
|
||||
assert out == [{'day': '2015-01-01', 'value': 47.71}, {'day': '2015-02-01', 'value': 58.1}]
|
||||
assert out == [{"day": "2015-01-01", "value": 47.71}, {"day": "2015-02-01", "value": 58.1}]
|
||||
|
||||
|
||||
def test_parse_dgec_brent_rejects_garbage():
|
||||
with pytest.raises(ValueError):
|
||||
upstream.parse_dgec_brent(make_xlsx('Cours du Brent', {'B1': 'rien'}))
|
||||
upstream.parse_dgec_brent(make_xlsx("Cours du Brent", {"B1": "rien"}))
|
||||
|
||||
|
||||
def test_parse_dgec_margin_keeps_both_units():
|
||||
raw = make_xlsx('Marge brute raffinage sur Brent', {'A3': 42005, 'B3': 6.9877, 'C3': 45.253})
|
||||
assert upstream.parse_dgec_margin(raw) == [{'day': '2015-01-01', 'usd_per_bbl': 6.99, 'eur_per_tonne': 45.25}]
|
||||
raw = make_xlsx("Marge brute raffinage sur Brent", {"A3": 42005, "B3": 6.9877, "C3": 45.253})
|
||||
assert upstream.parse_dgec_margin(raw) == [
|
||||
{"day": "2015-01-01", "usd_per_bbl": 6.99, "eur_per_tonne": 45.25}
|
||||
]
|
||||
|
||||
|
||||
def test_parse_dgec_prices_splits_htt_and_ttc():
|
||||
cells = {'A3': 46272, 'B2': 'Gazole', 'H2': 'Gazole', 'B3': 1.653, 'H3': 1.99}
|
||||
out = upstream.parse_dgec_prices(make_xlsx('Carburants routiers', cells))
|
||||
assert out == [{'day': '2026-09-07', 'htt': {'Gazole': 1.653}, 'ttc': {'Gazole': 1.99}}]
|
||||
cells = {"A3": 46272, "B2": "Gazole", "H2": "Gazole", "B3": 1.653, "H3": 1.99}
|
||||
out = upstream.parse_dgec_prices(make_xlsx("Carburants routiers", cells))
|
||||
assert out == [{"day": "2026-09-07", "htt": {"Gazole": 1.653}, "ttc": {"Gazole": 1.99}}]
|
||||
|
||||
|
||||
def test_parse_eu_bulletin_converts_thousands_of_litres():
|
||||
cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_with_tax_diesel', 'CN4': 2041.66,
|
||||
'CO1': 'FR_price_with_tax_euro95', 'CO4': 1899.99}
|
||||
out = upstream.parse_eu_bulletin(make_xlsx('Prices with taxes', cells))
|
||||
assert out == [{'day': '2026-09-07', 'prices': {'diesel': 2.042, 'euro95': 1.9}}]
|
||||
cells = {
|
||||
"A3": "Date",
|
||||
"A4": 46272,
|
||||
"CN1": "FR_price_with_tax_diesel",
|
||||
"CN4": 2041.66,
|
||||
"CO1": "FR_price_with_tax_euro95",
|
||||
"CO4": 1899.99,
|
||||
}
|
||||
out = upstream.parse_eu_bulletin(make_xlsx("Prices with taxes", cells))
|
||||
assert out == [{"day": "2026-09-07", "prices": {"diesel": 2.042, "euro95": 1.9}}]
|
||||
|
||||
|
||||
def test_parse_eu_bulletin_accepts_without_tax_sheet():
|
||||
# Le bulletin nomme le second onglet « Prices wo taxes » : les en-têtes diffèrent.
|
||||
cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_wo_tax_diesel', 'CN4': 1500.0}
|
||||
out = upstream.parse_eu_bulletin(make_xlsx('Prices wo taxes', cells), 'FR', 'Prices wo taxes')
|
||||
assert out == [{'day': '2026-09-07', 'prices': {'diesel': 1.5}}]
|
||||
cells = {"A3": "Date", "A4": 46272, "CN1": "FR_price_wo_tax_diesel", "CN4": 1500.0}
|
||||
out = upstream.parse_eu_bulletin(make_xlsx("Prices wo taxes", cells), "FR", "Prices wo taxes")
|
||||
assert out == [{"day": "2026-09-07", "prices": {"diesel": 1.5}}]
|
||||
|
||||
|
||||
def test_parse_eu_bulletin_rejects_missing_country():
|
||||
raw = make_xlsx('Prices with taxes', {'A3': 'Date', 'A4': 46272, 'CN1': 'BE_price_with_tax_diesel', 'CN4': 1500})
|
||||
raw = make_xlsx(
|
||||
"Prices with taxes", {"A3": "Date", "A4": 46272, "CN1": "BE_price_with_tax_diesel", "CN4": 1500}
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
upstream.parse_eu_bulletin(raw)
|
||||
|
||||
|
||||
def test_parse_chokepoints_keeps_latest_per_watched_strait():
|
||||
payload = json.dumps({'features': [
|
||||
{'attributes': {'date': '2026-08-30', 'portname': 'Strait of Hormuz', 'n_tanker': 40, 'n_total': 90}},
|
||||
{'attributes': {'date': '2026-09-06', 'portname': 'Strait of Hormuz', 'n_tanker': 2, 'n_total': 6,
|
||||
'capacity_tanker': 60280, 'capacity': 150000}},
|
||||
{'attributes': {'date': '2026-09-06', 'portname': 'Bab el-Mandeb Strait', 'n_tanker': 6, 'n_total': 23}},
|
||||
{'attributes': {'date': '2026-09-06', 'portname': 'Port of Nantes', 'n_tanker': 99}},
|
||||
]}).encode()
|
||||
payload = json.dumps(
|
||||
{
|
||||
"features": [
|
||||
{
|
||||
"attributes": {
|
||||
"date": "2026-08-30",
|
||||
"portname": "Strait of Hormuz",
|
||||
"n_tanker": 40,
|
||||
"n_total": 90,
|
||||
}
|
||||
},
|
||||
{
|
||||
"attributes": {
|
||||
"date": "2026-09-06",
|
||||
"portname": "Strait of Hormuz",
|
||||
"n_tanker": 2,
|
||||
"n_total": 6,
|
||||
"capacity_tanker": 60280,
|
||||
"capacity": 150000,
|
||||
}
|
||||
},
|
||||
{
|
||||
"attributes": {
|
||||
"date": "2026-09-06",
|
||||
"portname": "Bab el-Mandeb Strait",
|
||||
"n_tanker": 6,
|
||||
"n_total": 23,
|
||||
}
|
||||
},
|
||||
{"attributes": {"date": "2026-09-06", "portname": "Port of Nantes", "n_tanker": 99}},
|
||||
]
|
||||
}
|
||||
).encode()
|
||||
out = upstream.parse_chokepoints(payload)
|
||||
assert set(out) == {'Strait of Hormuz', 'Bab el-Mandeb Strait'}
|
||||
assert out['Strait of Hormuz']['day'] == '2026-09-06'
|
||||
assert out['Strait of Hormuz']['transit_tankers'] == 2
|
||||
assert out['Strait of Hormuz']['capacity_total'] == 150000
|
||||
assert set(out) == {"Strait of Hormuz", "Bab el-Mandeb Strait"}
|
||||
assert out["Strait of Hormuz"]["day"] == "2026-09-06"
|
||||
assert out["Strait of Hormuz"]["transit_tankers"] == 2
|
||||
assert out["Strait of Hormuz"]["capacity_total"] == 150000
|
||||
|
||||
|
||||
def test_parse_chokepoints_rejects_garbage():
|
||||
@@ -113,7 +164,11 @@ def test_parse_chokepoints_rejects_garbage():
|
||||
|
||||
|
||||
def test_freshness_never_assumes_current():
|
||||
assert upstream.freshness('2026-09-10', today=__import__('datetime').date(2026, 9, 12)) == {
|
||||
'state': 'fresh', 'age_days': 2}
|
||||
assert upstream.freshness('2026-07-01', today=__import__('datetime').date(2026, 9, 12))['state'] == 'stale'
|
||||
assert upstream.freshness(None) == {'state': 'unknown', 'age_days': None}
|
||||
assert upstream.freshness("2026-09-10", today=__import__("datetime").date(2026, 9, 12)) == {
|
||||
"state": "fresh",
|
||||
"age_days": 2,
|
||||
}
|
||||
assert (
|
||||
upstream.freshness("2026-07-01", today=__import__("datetime").date(2026, 9, 12))["state"] == "stale"
|
||||
)
|
||||
assert upstream.freshness(None) == {"state": "unknown", "age_days": None}
|
||||
|
||||
@@ -92,7 +92,6 @@ def test_collect_upstream_reports_total_failure(store):
|
||||
|
||||
|
||||
def test_collect_still_returns_no_favorites_with_upstream(store, monkeypatch):
|
||||
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
|
||||
out = collector.collect(lambda: [], force=True)
|
||||
assert out["status"] == "no_favorites"
|
||||
assert "upstream" in out
|
||||
|
||||
Reference in New Issue
Block a user