Historiser les sources amont officielles (DGEC, bulletin UE, detroits IMF)

Nouveau module upstream : parseurs testables des xlsx DGEC (Brent mensuel, marge brute de raffinage, prix HTT et TTC France par carburant) et du bulletin petrolier europeen (France TTC et hors taxes), plus les passages quotidiens par detroit via IMF PortWatch utilise par l IEA. Historisation idempotente dans upstream_series, chokepoint_daily et upstream_runs, collecte amont independante des favoris et endpoint /api/upstream. Chaque valeur porte date, source et fraicheur reelle.
This commit is contained in:
root
2026-09-12 22:27:58 +02:00
parent 081bd0734e
commit a2434836c4
11 changed files with 904 additions and 36 deletions

View File

@@ -1,5 +1,7 @@
"""Fixtures partagées : aucune base de production, aucun accès réseau."""
import importlib
import pytest
import brands
@@ -15,6 +17,9 @@ def isolated_database(tmp_path, monkeypatch):
# 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.
collector = importlib.import_module("collector")
monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {})
return tmp_path

View File

@@ -20,11 +20,11 @@ def test_collect_overlapping_favorites_once_daily(store, collector):
calls.append(1)
return [sample(datetime.now(timezone.utc))]
out = collector.collect(load, lambda: {"trend": "unknown"}, force=True)
out = collector.collect(load, force=True)
assert out["status"] == "ok"
assert out["count"] == 1
assert len(calls) == 1
assert collector.collect(load, lambda: {}, force=False)["status"] == "skipped"
assert collector.collect(load, force=False)["status"] == "skipped"
assert len(calls) == 1
with store.connect() as db:
assert db.execute("select count(*) from observations").fetchone()[0] == 1
@@ -36,8 +36,8 @@ def test_failed_collection_logged_and_retryable(store, collector):
def fail():
raise OSError("source inaccessible")
assert collector.collect(fail, lambda: {}, force=True)["status"] == "error"
out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], lambda: {}, force=False)
assert collector.collect(fail, force=True)["status"] == "error"
out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], force=False)
assert out["status"] == "ok"
@@ -45,4 +45,4 @@ def test_empty_favorites_does_not_download(store, collector):
def forbidden():
raise AssertionError("Aucun téléchargement sans favori")
assert collector.collect(forbidden, forbidden)["status"] == "no_favorites"
assert collector.collect(forbidden)["status"] == "no_favorites"

119
tests/test_upstream.py Normal file
View File

@@ -0,0 +1,119 @@
"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
import io
import json
import zipfile
import pytest
import upstream
def make_xlsx(sheet_name, cells, strings=None):
"""Construit un classeur minimal respectant la structure réelle lue sur la VM."""
text_values = {ref: value for ref, value in cells.items() if isinstance(value, str)}
numeric = {ref: value for ref, value in cells.items() if not isinstance(value, str)}
shared = list(dict.fromkeys(text_values.values()))
index = {value: position for position, value in enumerate(shared)}
def cell_xml(ref, value):
if isinstance(value, str):
return f'<c r="{ref}" t="s"><v>{index[value]}</v></c>'
return f'<c r="{ref}"><v>{value}</v></c>'
sheet_rows = {}
for ref in list(numeric) + list(text_values):
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>')
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)
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(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})
out = upstream.parse_dgec_brent(raw)
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'}))
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}]
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}}]
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}}]
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}}]
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})
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()
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
def test_parse_chokepoints_rejects_garbage():
with pytest.raises(ValueError):
upstream.parse_chokepoints(b'{"error": "bad query"}')
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}

View File

@@ -0,0 +1,98 @@
"""Historisation des séries amont et orchestration de la collecte amont."""
from datetime import datetime, timezone
import collector
import storage
def test_upstream_series_roundtrip_and_deduplication(store):
rows = [dict(day="2026-01-01", value=80.0), dict(day="2026-02-01", value=82.5)]
assert storage.save_upstream("dgec_brent_usd", rows, "USD/baril", "DGEC", datetime.now(timezone.utc)) == 2
assert [r["value"] for r in storage.upstream_series("dgec_brent_usd")] == [80.0, 82.5]
storage.save_upstream("dgec_brent_usd", [dict(day="2026-02-01", value=83.0)], "USD/baril", "DGEC")
assert [r["value"] for r in storage.upstream_series("dgec_brent_usd")] == [80.0, 83.0]
def test_save_upstream_ignores_invalid_values(store):
assert (
storage.save_upstream(
"x",
[
dict(day="2026-01-01", value=float("nan")),
dict(day=None, value=1.0),
dict(day="2026-01-02", value="n/a"),
],
"unit",
"src",
)
== 0
)
assert storage.upstream_series("x") == []
def test_latest_upstream_reports_real_freshness(store):
today = datetime.now(timezone.utc).date()
store.save_upstream("s1", [dict(day=today.isoformat(), value=1.0)], "EUR/L", "src")
store.save_upstream("s2", [dict(day="2015-01-01", value=2.0)], "EUR/L", "src")
latest = store.latest_upstream()
assert latest["s1"]["freshness"] == "fresh"
assert latest["s2"]["freshness"] == "stale"
assert latest["s2"]["age_days"] > 1000
def test_chokepoints_history_keeps_days(store):
entries = {
"Strait of Hormuz": dict(
day="2026-09-06",
transit_tankers=2,
transit_total=6,
capacity_tankers=60280,
capacity_total=150000,
)
}
assert store.save_chokepoints(entries, "IMF PortWatch") == 1
store.save_chokepoints(entries, "IMF PortWatch")
history = store.chokepoint_daily(60)
assert list(history) == ["Strait of Hormuz"]
assert len(history["Strait of Hormuz"]) == 1
assert history["Strait of Hormuz"][0]["transit_tankers"] == 2
def test_collect_upstream_runs_once_per_day_and_lists_failures(store, monkeypatch):
calls = []
def good():
calls.append("good")
return [
dict(series="test_series", unit="EUR/L", source="test", rows=[dict(day="2026-09-01", value=1.5)])
]
def broken():
calls.append("broken")
raise OSError("source en panne")
assert collector.collect_upstream(force=True, sources={"good": good})["status"] == "ok"
assert collector.collect_upstream(sources={"good": good})["status"] == "skipped"
assert calls.count("good") == 1
# Un échec partiel ne doit pas empêcher une nouvelle tentative le même jour.
out = collector.collect_upstream(force=True, sources={"good": good, "broken": broken})
assert out["status"] == "partial"
assert "broken" in out["detail"] and "OSError" in out["detail"]
assert store.upstream_series("test_series")[0]["value"] == 1.5
def test_collect_upstream_reports_total_failure(store):
def broken():
raise OSError("hors ligne")
out = collector.collect_upstream(force=True, sources={"broken": broken})
assert out["status"] == "error"
assert store.latest_upstream() == {}
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