Modele J+0 vers J+21 : benchmarks simples, unites en centimes, regimes et couverture par carburant
Cinq modeles sont compares sur des previsions directes par horizon (naive, tendance locale, autoregressif pompe, ridge marche, k-NN borne), sans bibliotheque scientifique et avec une selection faite sur une fin d apprentissage chronologique, jamais sur le test. Les cibles sont exprimees en centimes par litre sur le panel comparable, avec intervalle et probabilites. La serie BZ=F est reconnue comme un future Brent : renommee, jamais utilisee en niveau absolu, avec detection des changements de contrat et conservation de la reference mensuelle DGEC a cote. Une date available_at explicite separe desormais periode decrite, publication reelle et disponibilite, avec des hypotheses conservatrices marquees comme estimees. Le backtest rend les performances par carburant, par horizon et par regime (Covid, 2022, periode calme, crise actuelle), refuse une forte confiance pendant un choc, et teste la strategie sur quatre profils d usage.
This commit is contained in:
@@ -20,16 +20,14 @@ def isolated_environment(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3")
|
||||
monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: [])
|
||||
monkeypatch.setattr(market, "PROVIDERS", {})
|
||||
monkeypatch.setattr(routing, "PROVIDERS", {"osrm": lambda *a, **k: {}, "google": lambda *a, **k: {}})
|
||||
monkeypatch.setattr(routing, "PROVIDERS", {"osrm": lambda *a, **k: {},
|
||||
"google": lambda *a, **k: {}})
|
||||
monkeypatch.delenv("FUEL_ROUTING_PROVIDERS", raising=False)
|
||||
monkeypatch.delenv("FUEL_GOOGLE_MAPS_API_KEY", raising=False)
|
||||
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, "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", {})
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Discipline as-of : aucune information future, publications différées respectées."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
@@ -9,173 +8,122 @@ import features
|
||||
|
||||
|
||||
def test_publication_lag_depends_on_the_source():
|
||||
assert (
|
||||
asof.availability_day(dict(observed_at="2026-09-06", series="chokepoint_daily"), "portwatch")
|
||||
== "2026-09-13"
|
||||
)
|
||||
assert (
|
||||
asof.availability_day(dict(observed_at="2026-08-01", series="dgec_brent_usd"), "dgec") == "2026-09-01"
|
||||
)
|
||||
assert (
|
||||
asof.availability_day(dict(observed_at="2026-09-11", series="usd_per_eur"), "usd_per_eur")
|
||||
== "2026-09-11"
|
||||
)
|
||||
assert asof.availability_day(dict(day="2026-09-12", origin="live"), "instantane") == "2026-09-12"
|
||||
assert asof.availability_day(dict(observed_at='2026-09-06', series='chokepoint_daily'),
|
||||
'portwatch') == '2026-09-16'
|
||||
assert asof.availability_day(dict(observed_at='2026-08-01', series='dgec_brent_usd'),
|
||||
'dgec_brent') == '2026-09-15'
|
||||
assert asof.availability_day(dict(observed_at='2026-09-11', series='usd_per_eur'),
|
||||
'usd_per_eur') == '2026-09-11'
|
||||
assert asof.availability_day(dict(day='2026-09-12', origin='live'), 'instantane') == '2026-09-12'
|
||||
|
||||
|
||||
def test_explicit_publication_date_wins_over_the_lag():
|
||||
row = dict(observed_at="2026-09-06", published_at="2026-09-11", series="chokepoint_daily")
|
||||
assert asof.availability_day(row) == "2026-09-11"
|
||||
row = dict(observed_at='2026-09-06', published_at='2026-09-11', series='chokepoint_daily')
|
||||
assert asof.availability_day(row) == '2026-09-11'
|
||||
|
||||
|
||||
def test_a_delayed_publication_is_not_visible_before_its_date():
|
||||
"""PortWatch décrit le 6 septembre mais n'est publié que le 11 : invisible le 8."""
|
||||
rows = [dict(day="2026-09-06", observed_at="2026-09-06", value=42)]
|
||||
assert asof.available_rows(rows, "2026-09-08", family="portwatch") == []
|
||||
assert len(asof.available_rows(rows, "2026-09-13", family="portwatch")) == 1
|
||||
assert asof.latest_available(rows, "2026-09-08", family="portwatch") is None
|
||||
frame = asof.asof_frame(rows, "2026-09-08", family="portwatch")
|
||||
assert frame["last"] is None and frame["stale_days"] is None
|
||||
rows = [dict(day='2026-09-06', observed_at='2026-09-06', value=42)]
|
||||
assert asof.available_rows(rows, '2026-09-10', family='portwatch') == []
|
||||
assert len(asof.available_rows(rows, '2026-09-16', family='portwatch')) == 1
|
||||
assert asof.latest_available(rows, '2026-09-08', family='portwatch') is None
|
||||
frame = asof.asof_frame(rows, '2026-09-08', family='portwatch')
|
||||
assert frame['last'] is None and frame['stale_days'] is None
|
||||
|
||||
|
||||
def test_stale_features_are_absent_rather_than_eternal():
|
||||
rows = [dict(day="2026-01-01", observed_at="2026-01-01", value=1.5)]
|
||||
assert asof.latest_available(rows, "2026-03-15", family="brent") is None
|
||||
assert asof.latest_available(rows, "2026-01-20", family="brent")["stale_days"] == 19
|
||||
rows = [dict(day='2026-01-01', observed_at='2026-01-01', value=1.5)]
|
||||
assert asof.latest_available(rows, '2026-03-15', family='brent') is None
|
||||
assert asof.latest_available(rows, '2026-01-20', family='brent')['stale_days'] == 19
|
||||
|
||||
|
||||
def test_asof_percentile_ignores_the_future():
|
||||
points = [dict(day=f"2026-01-{day:02d}", value=2.00) for day in range(1, 11)]
|
||||
points += [dict(day="2026-02-01", value=1.00), dict(day="2026-02-02", value=1.00)]
|
||||
early = asof.asof_percentile(points, "2026-01-05", value=2.00)
|
||||
assert early["count"] == 5, "rien après le 5 janvier"
|
||||
assert early["percentile"] == 1.0
|
||||
late = asof.asof_percentile(points, "2026-02-02", value=1.00)
|
||||
assert late["count"] == 12
|
||||
assert late["percentile"] < 0.5
|
||||
points = [dict(day=f'2026-01-{day:02d}', value=2.00) for day in range(1, 11)]
|
||||
points += [dict(day='2026-02-01', value=1.00), dict(day='2026-02-02', value=1.00)]
|
||||
early = asof.asof_percentile(points, '2026-01-05', value=2.00)
|
||||
assert early['count'] == 5, 'rien après le 5 janvier'
|
||||
assert early['percentile'] == 1.0
|
||||
late = asof.asof_percentile(points, '2026-02-02', value=1.00)
|
||||
assert late['count'] == 12
|
||||
assert late['percentile'] < 0.5
|
||||
|
||||
|
||||
def test_moving_average_only_looks_backwards():
|
||||
points = [dict(day=f"2026-01-{day:02d}", value=float(day)) for day in range(1, 11)]
|
||||
assert asof.moving_average(points, "2026-01-03", window=10) == 2.0
|
||||
assert asof.moving_average(points, "2026-01-10", window=3) == 9.0
|
||||
assert asof.moving_average(points, "2025-12-31", window=3) is None
|
||||
points = [dict(day=f'2026-01-{day:02d}', value=float(day)) for day in range(1, 11)]
|
||||
assert asof.moving_average(points, '2026-01-03', window=10) == 2.0
|
||||
assert asof.moving_average(points, '2026-01-10', window=3) == 9.0
|
||||
assert asof.moving_average(points, '2025-12-31', window=3) is None
|
||||
|
||||
|
||||
def test_scaler_is_fitted_on_train_only():
|
||||
train = [dict(day=f"2026-01-{day:02d}", value=float(day)) for day in range(1, 11)]
|
||||
scaler = asof.fit_scaler(
|
||||
[point["value"] for point in train], fitted_until=max(point["day"] for point in train)
|
||||
)
|
||||
assert scaler["fitted_until"] == "2026-01-10"
|
||||
asof.assert_scaler_uses_only_train(scaler, [point["day"] for point in train], ["2026-02-01"])
|
||||
train = [dict(day=f'2026-01-{day:02d}', value=float(day)) for day in range(1, 11)]
|
||||
scaler = asof.fit_scaler([point['value'] for point in train],
|
||||
fitted_until=max(point['day'] for point in train))
|
||||
assert scaler['fitted_until'] == '2026-01-10'
|
||||
asof.assert_scaler_uses_only_train(scaler, [point['day'] for point in train], ['2026-02-01'])
|
||||
with pytest.raises(ValueError) as error:
|
||||
asof.assert_scaler_uses_only_train(
|
||||
dict(scaler, fitted_until="2026-03-01"), [point["day"] for point in train], ["2026-02-01"]
|
||||
)
|
||||
assert "fuite de données" in str(error.value)
|
||||
asof.assert_scaler_uses_only_train(dict(scaler, fitted_until='2026-03-01'),
|
||||
[point['day'] for point in train], ['2026-02-01'])
|
||||
assert 'fuite de données' in str(error.value)
|
||||
|
||||
|
||||
def test_feature_matrix_reports_real_periods_not_wishful_ones(store):
|
||||
store.save_upstream(
|
||||
"dgec_brent_usd",
|
||||
[dict(day="2015-06-01", value=60.0), dict(day="2015-07-01", value=62.0)],
|
||||
"USD/baril",
|
||||
"DGEC",
|
||||
)
|
||||
store.save_chokepoints(
|
||||
[
|
||||
(
|
||||
"Strait of Hormuz",
|
||||
dict(
|
||||
day="2019-03-01",
|
||||
transit_tankers=40,
|
||||
transit_total=90,
|
||||
capacity_tankers=1,
|
||||
capacity_total=2,
|
||||
),
|
||||
),
|
||||
(
|
||||
"Strait of Hormuz",
|
||||
dict(
|
||||
day="2019-03-02",
|
||||
transit_tankers=41,
|
||||
transit_total=91,
|
||||
capacity_tankers=1,
|
||||
capacity_total=2,
|
||||
),
|
||||
),
|
||||
],
|
||||
"IMF PortWatch",
|
||||
)
|
||||
matrix = {item["key"]: item for item in features.availability_matrix("Gazole")}
|
||||
assert matrix["dgec_margin"]["first"] == "2015-06-01"
|
||||
assert matrix["dgec_margin"]["points"] == 2
|
||||
assert matrix["portwatch_traffic"]["first"] == "2019-03-01"
|
||||
assert matrix["brent_eur"]["status"] == "absent", "aucune cotation quotidienne en base"
|
||||
assert matrix["news_events"]["status"] == "absent"
|
||||
store.save_upstream('dgec_brent_usd', [dict(day='2015-06-01', value=60.0),
|
||||
dict(day='2015-07-01', value=62.0)],
|
||||
'USD/baril', 'DGEC')
|
||||
store.save_chokepoints([('Strait of Hormuz', dict(day='2019-03-01', transit_tankers=40,
|
||||
transit_total=90, capacity_tankers=1,
|
||||
capacity_total=2)),
|
||||
('Strait of Hormuz', dict(day='2019-03-02', transit_tankers=41,
|
||||
transit_total=91, capacity_tankers=1,
|
||||
capacity_total=2))],
|
||||
'IMF PortWatch')
|
||||
matrix = {item['key']: item for item in features.availability_matrix('Gazole')}
|
||||
assert matrix['brent_spot_reference']['first'] == '2015-06-01'
|
||||
assert matrix['brent_spot_reference']['points'] == 2
|
||||
assert matrix['portwatch_traffic']['first'] == '2019-03-01'
|
||||
assert matrix['brent_futures']['status'] == 'absent', 'aucune cotation quotidienne en base'
|
||||
assert matrix['news_events']['status'] == 'absent'
|
||||
|
||||
|
||||
def test_portwatch_history_is_never_projected_back_to_2007(store):
|
||||
store.save_chokepoints(
|
||||
[
|
||||
(
|
||||
"Strait of Hormuz",
|
||||
dict(
|
||||
day=(date(2019, 1, 1) + timedelta(days=offset)).isoformat(),
|
||||
transit_tankers=40,
|
||||
transit_total=90,
|
||||
capacity_tankers=1,
|
||||
capacity_total=2,
|
||||
),
|
||||
)
|
||||
for offset in range(60)
|
||||
],
|
||||
"IMF PortWatch",
|
||||
)
|
||||
matrix = {item["key"]: item for item in features.availability_matrix("Gazole")}
|
||||
assert matrix["portwatch_traffic"]["first"] == "2019-01-01"
|
||||
assert matrix["portwatch_traffic"]["expected_from"] == "2019-01-01"
|
||||
periods = {item["key"]: item for item in features.variant_periods(list(matrix.values()))}
|
||||
enriched = periods["enriched"]
|
||||
assert "portwatch_traffic" in enriched["members"], "le trafic est exploitable sur cette période"
|
||||
assert enriched["start"] is not None and enriched["start"] >= "2019-01-01"
|
||||
assert "news_events" not in enriched["features"], (
|
||||
"les événements, disponibles depuis 2026 seulement, ne sont jamais recopiés sur 2019"
|
||||
)
|
||||
assert enriched["trainable"] is False, "le niveau local manque dans cette base de test"
|
||||
assert "local_price_level" in enriched["blockers"]
|
||||
[('Strait of Hormuz', dict(day=(date(2019, 1, 1) + timedelta(days=offset)).isoformat(),
|
||||
transit_tankers=40, transit_total=90, capacity_tankers=1,
|
||||
capacity_total=2)) for offset in range(60)], 'IMF PortWatch')
|
||||
matrix = {item['key']: item for item in features.availability_matrix('Gazole')}
|
||||
assert matrix['portwatch_traffic']['first'] == '2019-01-01'
|
||||
assert matrix['portwatch_traffic']['expected_from'] == '2019-01-01'
|
||||
periods = {item['key']: item for item in features.variant_periods(
|
||||
list(matrix.values()))}
|
||||
enriched = periods['enriched']
|
||||
assert 'portwatch_traffic' in enriched['members'], 'le trafic est exploitable sur cette période'
|
||||
assert 'brent_futures' not in enriched['members'], 'le Brent futures manque dans cette base'
|
||||
assert enriched['start'] is not None and enriched['start'] >= '2019-01-01'
|
||||
assert 'news_events' not in enriched['features'], \
|
||||
'les événements, disponibles depuis 2026 seulement, ne sont jamais recopiés sur 2019'
|
||||
assert enriched['trainable'] is False, 'le niveau local manque dans cette base de test'
|
||||
assert 'local_price_level' in enriched['blockers']
|
||||
|
||||
|
||||
def test_variant_start_is_the_youngest_member(store):
|
||||
store.save_upstream(
|
||||
"dgec_brent_usd",
|
||||
[
|
||||
dict(day=(date(2015, 6, 1) + timedelta(days=offset)).isoformat(), value=60.0)
|
||||
for offset in range(120)
|
||||
],
|
||||
"USD/baril",
|
||||
"DGEC",
|
||||
)
|
||||
store.save_upstream(
|
||||
"usd_per_eur",
|
||||
[
|
||||
dict(day=(date(2018, 5, 1) + timedelta(days=offset)).isoformat(), value=1.18)
|
||||
for offset in range(120)
|
||||
],
|
||||
"USD/EUR",
|
||||
"BCE",
|
||||
)
|
||||
matrix = {item["key"]: item for item in features.availability_matrix("Gazole")}
|
||||
periods = {item["key"]: item for item in features.variant_periods(list(matrix.values()))}
|
||||
start = periods["market"]["start"]
|
||||
assert start == "2018-05-01", "la variante commence quand toutes ses variables existent"
|
||||
store.save_upstream('dgec_brent_usd',
|
||||
[dict(day=(date(2015, 6, 1) + timedelta(days=offset)).isoformat(),
|
||||
value=60.0) for offset in range(120)], 'USD/baril', 'DGEC')
|
||||
store.save_upstream('usd_per_eur',
|
||||
[dict(day=(date(2018, 5, 1) + timedelta(days=offset)).isoformat(),
|
||||
value=1.18) for offset in range(120)], 'USD/EUR', 'BCE')
|
||||
matrix = {item['key']: item for item in features.availability_matrix('Gazole')}
|
||||
periods = {item['key']: item for item in features.variant_periods(list(matrix.values()))}
|
||||
start = periods['market']['start']
|
||||
assert start == '2018-05-01', 'la variante commence quand toutes ses variables existent'
|
||||
|
||||
|
||||
def test_report_states_periods_and_statuses(store):
|
||||
store.save_upstream(
|
||||
"usd_per_eur", [dict(day=f"2026-08-{day:02d}", value=1.17) for day in range(1, 31)], "USD/EUR", "BCE"
|
||||
)
|
||||
text = features.report(features.availability_matrix("Gazole"))
|
||||
assert "Taux BCE USD/EUR" in text and "disponible" in text
|
||||
assert "aucune donnée en base" in text or "absent" in text
|
||||
store.save_upstream('usd_per_eur',
|
||||
[dict(day=f'2026-08-{day:02d}', value=1.17) for day in range(1, 31)],
|
||||
'USD/EUR', 'BCE')
|
||||
text = features.report(features.availability_matrix('Gazole'))
|
||||
assert 'Taux BCE USD/EUR' in text and 'disponible' in text
|
||||
assert 'aucune donnée en base' in text or 'absent' in text
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Archives officielles : formats, sélection, dates réelles, et aucune continuité inventée."""
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
@@ -27,105 +26,102 @@ XML = """<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?><pdv_liste>
|
||||
</pdv>
|
||||
</pdv_liste>"""
|
||||
|
||||
BBOX = (44.5, 45.0, -0.9, -0.2) # Gironde
|
||||
BBOX = (44.5, 45.0, -0.9, -0.2) # Gironde
|
||||
|
||||
|
||||
def archive_bytes(xml=XML):
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("PrixCarburants_annuel_2007.xml", xml.encode("iso-8859-1"))
|
||||
with zipfile.ZipFile(buffer, 'w') as archive:
|
||||
archive.writestr('PrixCarburants_annuel_2007.xml', xml.encode('iso-8859-1'))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_price_formats_both_eras_are_accepted():
|
||||
assert backfill.parse_price("999") == 0.999, "millièmes d’euro (premières années)"
|
||||
assert backfill.parse_price("1.707") == 1.707, "euros décimaux (années récentes)"
|
||||
assert backfill.parse_price("1,707") == 1.707
|
||||
assert backfill.parse_price("") is None
|
||||
assert backfill.parse_price('999') == 0.999, 'millièmes d’euro (premières années)'
|
||||
assert backfill.parse_price('1.707') == 1.707, 'euros décimaux (années récentes)'
|
||||
assert backfill.parse_price('1,707') == 1.707
|
||||
assert backfill.parse_price('') is None
|
||||
assert backfill.parse_price(None) is None
|
||||
assert backfill.parse_price("0") is None, "valeur nulle : pas un prix"
|
||||
assert backfill.parse_price("99") is None, "0,099 €/L : implausible"
|
||||
assert backfill.parse_price("20000") is None, "20 €/L : implausible"
|
||||
assert backfill.parse_price('0') is None, 'valeur nulle : pas un prix'
|
||||
assert backfill.parse_price('99') is None, '0,099 €/L : implausible'
|
||||
assert backfill.parse_price('20000') is None, '20 €/L : implausible'
|
||||
|
||||
|
||||
def test_declared_dates_both_formats():
|
||||
assert backfill.parse_declared("2007-01-04 18:43:38.841521") == "2007-01-04T18:43:38"
|
||||
assert backfill.parse_declared("2025-01-02T00:37:00") == "2025-01-02T00:37:00"
|
||||
assert backfill.parse_declared("0000-00-00 00:00:00") is None
|
||||
assert backfill.parse_declared("") is None
|
||||
assert backfill.parse_declared('2007-01-04 18:43:38.841521') == '2007-01-04T18:43:38'
|
||||
assert backfill.parse_declared('2025-01-02T00:37:00') == '2025-01-02T00:37:00'
|
||||
assert backfill.parse_declared('0000-00-00 00:00:00') is None
|
||||
assert backfill.parse_declared('') is None
|
||||
assert backfill.parse_declared(None) is None
|
||||
|
||||
|
||||
def test_fuel_names_are_normalised():
|
||||
assert backfill.normalize_fuel("Gazole") == "Gazole"
|
||||
assert backfill.normalize_fuel("SP95-E10") == "E10"
|
||||
assert backfill.normalize_fuel("e10") == "E10"
|
||||
assert backfill.normalize_fuel("GPLc") == "GPLc"
|
||||
assert backfill.normalize_fuel("SP95") == "SP95"
|
||||
assert backfill.normalize_fuel("inconnu") is None
|
||||
assert backfill.normalize_fuel('Gazole') == 'Gazole'
|
||||
assert backfill.normalize_fuel('SP95-E10') == 'E10'
|
||||
assert backfill.normalize_fuel('e10') == 'E10'
|
||||
assert backfill.normalize_fuel('GPLc') == 'GPLc'
|
||||
assert backfill.normalize_fuel('SP95') == 'SP95'
|
||||
assert backfill.normalize_fuel('inconnu') is None
|
||||
|
||||
|
||||
def test_scan_keeps_only_the_target_box_and_the_declared_dates():
|
||||
rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole", "E10"))
|
||||
assert set(stations) == {"1111111", "3333333"}, "Paris est hors zone"
|
||||
by_key = {(row["station_id"], row["fuel"], row["day"]): row for row in rows}
|
||||
assert ("1111111", "Gazole", "2007-01-04") in by_key, "la date est celle déclarée"
|
||||
assert by_key[("1111111", "Gazole", "2007-01-04")]["price"] == 1.005, "dernière valeur du jour"
|
||||
assert by_key[("1111111", "Gazole", "2007-01-04")]["declared_at"] == "2007-01-04T21:10:00"
|
||||
assert by_key[("1111111", "Gazole", "2007-03-13")]["price"] == 1.009
|
||||
assert by_key[("1111111", "E10", "2007-03-13")]["price"] == 1.052
|
||||
assert ("1111111", "E85", "2007-03-13") not in by_key, "carburant non demandé"
|
||||
assert not any(row["price"] in (0.0, 1.111, 20.0) for row in rows), "valeurs invalides écartées"
|
||||
assert stations["1111111"]["first_day"] == "2007-01-04"
|
||||
assert stations["1111111"]["last_day"] == "2007-03-13"
|
||||
assert stations["1111111"]["days"] == 2
|
||||
rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole', 'E10'))
|
||||
assert set(stations) == {'1111111', '3333333'}, 'Paris est hors zone'
|
||||
by_key = {(row['station_id'], row['fuel'], row['day']): row for row in rows}
|
||||
assert ('1111111', 'Gazole', '2007-01-04') in by_key, 'la date est celle déclarée'
|
||||
assert by_key[('1111111', 'Gazole', '2007-01-04')]['price'] == 1.005, 'dernière valeur du jour'
|
||||
assert by_key[('1111111', 'Gazole', '2007-01-04')]['declared_at'] == '2007-01-04T21:10:00'
|
||||
assert by_key[('1111111', 'Gazole', '2007-03-13')]['price'] == 1.009
|
||||
assert by_key[('1111111', 'E10', '2007-03-13')]['price'] == 1.052
|
||||
assert ('1111111', 'E85', '2007-03-13') not in by_key, 'carburant non demandé'
|
||||
assert not any(row['price'] in (0.0, 1.111, 20.0) for row in rows), 'valeurs invalides écartées'
|
||||
assert stations['1111111']['first_day'] == '2007-01-04'
|
||||
assert stations['1111111']['last_day'] == '2007-03-13'
|
||||
assert stations['1111111']['days'] == 2
|
||||
|
||||
|
||||
def test_stations_outside_the_box_are_ignored_even_when_targeted_by_id():
|
||||
rows, stations = backfill.scan_archive(
|
||||
archive_bytes(), bbox=BBOX, fuels=("Gazole",), station_ids={"2222222"}
|
||||
)
|
||||
assert "2222222" in stations, "un identifiant suivi est repris même hors zone"
|
||||
assert "1111111" in stations, "et la zone reste prise en compte"
|
||||
assert any(
|
||||
row["station_id"] == "2222222" and row["day"] == "2007-02-02" and row["price"] == 1.05 for row in rows
|
||||
)
|
||||
rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole',),
|
||||
station_ids={'2222222'})
|
||||
assert '2222222' in stations, 'un identifiant suivi est repris même hors zone'
|
||||
assert '1111111' in stations, 'et la zone reste prise en compte'
|
||||
assert any(row['station_id'] == '2222222' and row['day'] == '2007-02-02'
|
||||
and row['price'] == 1.05 for row in rows)
|
||||
|
||||
|
||||
def test_no_price_is_ever_invented_for_an_absent_year():
|
||||
"""Une archive sans la station ne produit aucune ligne : aucune continuité fabriquée."""
|
||||
empty = XML.split('<pdv id="3333333"')[0] + "</pdv_liste>"
|
||||
rows, stations = backfill.scan_archive(archive_bytes(empty), bbox=BBOX, fuels=("Gazole",))
|
||||
assert "3333333" not in stations
|
||||
assert {row["station_id"] for row in rows} == {"1111111"}
|
||||
empty = XML.split('<pdv id="3333333"')[0] + '</pdv_liste>'
|
||||
rows, stations = backfill.scan_archive(archive_bytes(empty), bbox=BBOX, fuels=('Gazole',))
|
||||
assert '3333333' not in stations
|
||||
assert {row['station_id'] for row in rows} == {'1111111'}
|
||||
|
||||
|
||||
def test_import_marks_origin_and_keeps_declared_dates(store):
|
||||
rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole", "E10"))
|
||||
imported = store.save_archive_observations(rows, "archive:2007")
|
||||
rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole', 'E10'))
|
||||
imported = store.save_archive_observations(rows, 'archive:2007')
|
||||
assert imported == len(rows) > 0
|
||||
with store.connect() as db:
|
||||
sample = db.execute("SELECT * FROM observations ORDER BY station_id, day LIMIT 1").fetchone()
|
||||
assert sample["origin"] == "archive:2007"
|
||||
assert sample["day"] == "2007-01-04" and sample["source_updated"].startswith("2007-01-04T21:10")
|
||||
assert sample["fetched_at"] and not sample["fetched_at"].startswith("2007"), (
|
||||
"l’heure d’import est distincte de la date déclarée"
|
||||
)
|
||||
assert store.save_archive_observations(rows, "archive:2007") == 0, "import idempotent"
|
||||
sample = db.execute('SELECT * FROM observations ORDER BY station_id, day LIMIT 1').fetchone()
|
||||
assert sample['origin'] == 'archive:2007'
|
||||
assert sample['day'] == '2007-01-04' and sample['source_updated'].startswith('2007-01-04T21:10')
|
||||
assert sample['fetched_at'] and not sample['fetched_at'].startswith('2007'), \
|
||||
'l’heure d’import est distincte de la date déclarée'
|
||||
assert store.save_archive_observations(rows, 'archive:2007') == 0, 'import idempotent'
|
||||
|
||||
|
||||
def test_archived_rows_never_pass_as_todays_prices(store):
|
||||
"""Un import historique ne doit jamais être présenté comme un prix du jour."""
|
||||
rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole",))
|
||||
store.save_archive_observations(rows, "archive:2007")
|
||||
history = store.history(44.7737872, -0.5595029, 15, "Gazole")
|
||||
assert history["days"] == 0, "les lignes importées ne comptent pas comme relevés récents"
|
||||
assert store.fresh_price(rows[0]["declared_at"]) is False
|
||||
rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole',))
|
||||
store.save_archive_observations(rows, 'archive:2007')
|
||||
history = store.history(44.7737872, -0.5595029, 15, 'Gazole')
|
||||
assert history['days'] == 0, 'les lignes importées ne comptent pas comme relevés récents'
|
||||
assert store.fresh_price(rows[0]['declared_at']) is False
|
||||
|
||||
|
||||
def test_backfill_runs_are_recorded_per_year(store):
|
||||
store.save_backfill_run(2007, "ok", 3, 42, "détail")
|
||||
store.save_backfill_run(2008, "error", 0, 0, "HTTP 404")
|
||||
store.save_backfill_run(2007, 'ok', 3, 42, 'détail')
|
||||
store.save_backfill_run(2008, 'error', 0, 0, 'HTTP 404')
|
||||
runs = store.backfill_runs()
|
||||
assert runs[2007]["status"] == "ok" and runs[2007]["prices"] == 42
|
||||
assert runs[2008]["status"] == "error"
|
||||
assert runs[2007]['status'] == 'ok' and runs[2007]['prices'] == 42
|
||||
assert runs[2008]['status'] == 'error'
|
||||
|
||||
132
tests/test_backtest.py
Normal file
132
tests/test_backtest.py
Normal file
@@ -0,0 +1,132 @@
|
||||
"""Backtest : unités en c€/L, régimes séparés, confiance tenue pendant les chocs."""
|
||||
import backtest
|
||||
import validation
|
||||
|
||||
|
||||
def prediction(day, horizon=7, mu=2.0, actual=2.5, confidence=0.7, price=2.0,
|
||||
trained_until='2019-12-31'):
|
||||
"""Prédiction de test : jamais entraînée après la date prédite (sinon fuite détectée)."""
|
||||
return dict(day=day, horizon=horizon, predicted_price=price + mu / 100,
|
||||
actual_price=price + actual / 100, last_known_price=price,
|
||||
predicted_change=mu, actual_change=actual, confidence=confidence,
|
||||
interval=(mu - 1.0, mu + 1.0), p_up=confidence, trained_until=trained_until)
|
||||
|
||||
|
||||
def test_metrics_are_converted_to_cents():
|
||||
rows = [prediction('2026-01-01', mu=2.0, actual=3.0), prediction('2026-01-02', mu=-1.0,
|
||||
actual=-2.0)]
|
||||
metrics = backtest.metrics_in_cents(validation.evaluate(rows, horizon=7))
|
||||
assert metrics['mae_cents'] == 1.0, '1 c€/L d’erreur moyenne, exprimée en centimes'
|
||||
assert metrics['improvement_pct'] is not None
|
||||
assert metrics['naive']['mae_cents'] is not None
|
||||
|
||||
|
||||
def test_amplitude_reports_predicted_and_actual():
|
||||
rows = [prediction('2026-01-01', mu=2.0, actual=-4.0), prediction('2026-01-02', mu=-2.0,
|
||||
actual=2.0)]
|
||||
out = backtest.amplitude(rows)
|
||||
assert out['predicted_cents'] == 2.0
|
||||
assert out['actual_cents'] == 3.0
|
||||
|
||||
|
||||
def test_regimes_split_predictions_by_period():
|
||||
rows = [prediction('2020-03-15'), prediction('2022-05-15'), prediction('2023-09-15'),
|
||||
prediction('2026-03-01'), prediction('2021-01-01')]
|
||||
regimes = backtest.regime_report(rows)
|
||||
assert regimes['covid_2020']['count'] == 1
|
||||
assert regimes['choc_2022']['count'] == 1
|
||||
assert regimes['calme_2023']['count'] == 1
|
||||
assert regimes['crise_2026']['count'] == 1
|
||||
assert '2021' not in str([regime['count'] for regime in regimes.values()])
|
||||
|
||||
|
||||
def test_confidence_must_be_earned_during_a_shock():
|
||||
"""Forte confiance pendant un choc + sens proche du hasard = refus."""
|
||||
rows = []
|
||||
for index in range(40):
|
||||
rows.append(prediction(f'2026-01-{index % 28 + 1:02d}', mu=5.0,
|
||||
actual=(-5.0 if index % 2 else 5.0), confidence=0.93))
|
||||
regimes = backtest.regime_report(rows)
|
||||
verdict = backtest.shock_verdict(regimes)
|
||||
assert verdict['passed'] is False
|
||||
assert any('confiance' in problem for problem in verdict['problems'])
|
||||
|
||||
|
||||
def test_a_prudent_model_during_a_shock_is_accepted():
|
||||
rows = [prediction(f'2026-02-{index % 28 + 1:02d}', mu=2.0,
|
||||
actual=(2.0 if index % 4 else -2.0), confidence=0.55)
|
||||
for index in range(40)]
|
||||
verdict = backtest.shock_verdict(backtest.regime_report(rows))
|
||||
assert verdict['passed'] is True
|
||||
|
||||
|
||||
def test_shock_verdict_ignores_a_thin_regime():
|
||||
rows = [prediction('2022-03-01', mu=6.0, actual=-6.0, confidence=0.95) for _ in range(5)]
|
||||
verdict = backtest.shock_verdict(backtest.regime_report(rows))
|
||||
assert verdict['passed'] is True, 'cinq prévisions ne permettent pas de conclure'
|
||||
|
||||
|
||||
def test_interval_coverage_and_probability_calibration():
|
||||
rows = [prediction('2026-01-01', mu=2.0, actual=2.5),
|
||||
prediction('2026-01-02', mu=2.0, actual=9.0)]
|
||||
assert backtest._interval_coverage(rows) == 0.5
|
||||
assert backtest._probability_calibration(rows) is None, 'échantillon trop mince'
|
||||
many = [prediction(f'2026-02-{index % 28 + 1:02d}', mu=2.0,
|
||||
actual=(2.0 if index < 35 else -2.0), confidence=0.7)
|
||||
for index in range(70)]
|
||||
calibration = backtest._probability_calibration(many)
|
||||
assert calibration['count'] == 70
|
||||
assert calibration['observed'] == 0.5
|
||||
|
||||
|
||||
def test_render_reports_every_required_item():
|
||||
entry = dict(fuel='Gazole', variant='local_long', label='Modèle local long historique',
|
||||
train=('2007-01-01', '2024-12-31'), test=('2025-01-01', '2026-09-12'),
|
||||
train_samples=5000, test_samples=600, main_model='ridge_market',
|
||||
horizons={'7': backtest.metrics_in_cents(
|
||||
validation.evaluate([prediction(f'2026-01-{index % 28 + 1:02d}')
|
||||
for index in range(40)], horizon=7))
|
||||
| dict(model='ridge_market', interval_coverage=0.8,
|
||||
amplitude=dict(predicted_cents=2.4, actual_cents=2.8))},
|
||||
regimes={'crise_2026': dict(label='crise actuelle', period='2026-01-01 → 2026-12-31',
|
||||
count=40, mae_cents=1.2, improvement_pct=12.0,
|
||||
direction=0.6, mean_confidence=0.62)},
|
||||
economics=dict(naive=dict(cost_eur=100.0, refuels=10), advisor=dict(
|
||||
cost_eur=95.0, refuels=11), value=dict(net_saving_eur=3.5),
|
||||
comfort=dict(comfortable=True), period=('2025-01-01', '2026-09-12')),
|
||||
verdict=dict(passed=True, failures=[], reasons=['coût simulé']))
|
||||
text = backtest.render_variant(entry)
|
||||
for needle in ('apprentissage', 'test', 'MAE', 'amélioration', 'sens', 'calib', 'amplitude',
|
||||
'régimes', 'économie simulée', 'verdict'):
|
||||
assert needle in text, needle
|
||||
|
||||
|
||||
def test_render_explains_a_refusal():
|
||||
text = backtest.render_variant(dict(label='Modèle marché', fuel='SP95', variant='market',
|
||||
reason='12 échantillons : trop peu pour conclure'))
|
||||
assert 'non exploitable' in text and 'trop peu' in text
|
||||
|
||||
|
||||
def test_run_variant_without_data_returns_a_reason(store):
|
||||
entry = backtest.run_variant('Gazole', 'local_long', 44.77, -0.55, 15, days=60)
|
||||
assert entry['reason']
|
||||
assert entry.get('verdict') is None
|
||||
|
||||
|
||||
def test_holdout_keeps_the_current_crisis_out_of_training(store, monkeypatch):
|
||||
"""La période actuelle peut rester totalement hors entraînement."""
|
||||
rows = []
|
||||
from datetime import date, timedelta
|
||||
base = date(2024, 1, 1)
|
||||
for index in range(900):
|
||||
day = (base + timedelta(days=index)).isoformat()
|
||||
for station in range(5):
|
||||
rows.append(dict(station_id=f's{station}', fuel='Gazole', day=day,
|
||||
price=round(2.0 + index * 0.0005 + station * 0.004, 4),
|
||||
declared_at=f'{day}T09:00:00', lat=44.7737872, lon=-0.5595029))
|
||||
store.save_archive_observations(rows, 'archive:test')
|
||||
entry = backtest.run_variant('Gazole', 'local_long', 44.7737872, -0.5595029, 15, days=900,
|
||||
holdout_start='2026-06-01')
|
||||
if entry.get('train'):
|
||||
assert entry['train'][1] < '2026-06-01'
|
||||
assert entry['test'][0] >= '2026-06-01'
|
||||
@@ -24,7 +24,7 @@ def test_collect_overlapping_favorites_once_daily(store, collector):
|
||||
assert out["status"] == "ok"
|
||||
assert out["count"] == 1
|
||||
assert len(calls) == 1
|
||||
assert collector.collect(load, 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,7 +36,7 @@ def test_failed_collection_logged_and_retryable(store, collector):
|
||||
def fail():
|
||||
raise OSError("source inaccessible")
|
||||
|
||||
assert collector.collect(fail, force=True)["status"] == "error"
|
||||
assert collector.collect(fail, force=True)['status'] == 'error'
|
||||
out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], force=False)
|
||||
assert out["status"] == "ok"
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Événements prix (changement uniquement), actualités structurées et opérations commerciales."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
@@ -11,51 +10,39 @@ 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 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()], 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"
|
||||
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")
|
||||
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))
|
||||
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
|
||||
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():
|
||||
@@ -64,131 +51,80 @@ def test_rss_articles_keep_publication_date_and_source():
|
||||
<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")
|
||||
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
|
||||
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], []))
|
||||
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"
|
||||
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)
|
||||
monkeypatch.setattr(llm, 'extract', fake_extract)
|
||||
first = news.collect()
|
||||
assert first["analysed"] == 1 and first["events"] == 1
|
||||
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 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"
|
||||
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"))
|
||||
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() == []
|
||||
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",
|
||||
),
|
||||
)
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
assert active[0]['state'] == 'en cours'
|
||||
announced = promotions.active(today=datetime(2026, 9, 12, tzinfo=timezone.utc).date())
|
||||
assert announced[0]["state"] == "annoncée"
|
||||
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}
|
||||
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")
|
||||
llm.parse_json('aucun json ici')
|
||||
|
||||
@@ -6,7 +6,6 @@ Deux exigences verrouillées ici :
|
||||
- un trafic effondré est un **signal**, pas une mesure impossible : la référence est pré-crise,
|
||||
le niveau et la dynamique sont séparés, la confiance dépend de la mesure ET de l'actualité.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import storage
|
||||
@@ -18,100 +17,66 @@ def days_ago(n):
|
||||
|
||||
|
||||
def seed(series, unit, rows):
|
||||
return storage.save_upstream(series, rows, unit, "test")
|
||||
return storage.save_upstream(series, rows, unit, 'test')
|
||||
|
||||
|
||||
def seed_reference(median=47.0, chokepoint="Strait of Hormuz", total_median=95.0):
|
||||
storage.save_chokepoint_reference(
|
||||
[
|
||||
dict(
|
||||
chokepoint=chokepoint,
|
||||
window_start="2022-09-12",
|
||||
window_end="2025-09-12",
|
||||
observations=1000,
|
||||
tankers_median=median,
|
||||
tankers_mean=median + 1,
|
||||
tankers_p10=median - 20,
|
||||
tankers_p90=median + 20,
|
||||
total_median=total_median,
|
||||
capacity_tanker_median=2_500_000,
|
||||
source="test",
|
||||
)
|
||||
]
|
||||
)
|
||||
def seed_reference(median=47.0, chokepoint='Strait of Hormuz', total_median=95.0):
|
||||
storage.save_chokepoint_reference([dict(
|
||||
chokepoint=chokepoint, window_start='2022-09-12', window_end='2025-09-12',
|
||||
observations=1000, tankers_median=median, tankers_mean=median + 1, tankers_p10=median - 20,
|
||||
tankers_p90=median + 20, total_median=total_median, capacity_tanker_median=2_500_000,
|
||||
source='test')])
|
||||
|
||||
|
||||
def seed_transits(values, chokepoint="Strait of Hormuz", step=1):
|
||||
def seed_transits(values, chokepoint='Strait of Hormuz', step=1):
|
||||
"""values : du plus ancien au plus récent, un point tous les ``step`` jours."""
|
||||
pairs = [((len(values) - 1 - index) * step, value) for index, value in enumerate(values)]
|
||||
seed_transits_at(pairs, chokepoint)
|
||||
|
||||
|
||||
def seed_transits_at(pairs, chokepoint="Strait of Hormuz"):
|
||||
def seed_transits_at(pairs, chokepoint='Strait of Hormuz'):
|
||||
"""pairs : (jours dans le passé, nombre de pétroliers). Permet de simuler un historique ancien."""
|
||||
rows = [
|
||||
(
|
||||
chokepoint,
|
||||
dict(
|
||||
day=days_ago(offset),
|
||||
transit_tankers=value,
|
||||
transit_total=value * 2,
|
||||
capacity_tankers=value * 1000,
|
||||
capacity_total=value * 2000,
|
||||
),
|
||||
)
|
||||
for offset, value in pairs
|
||||
]
|
||||
storage.save_chokepoints(rows, "IMF PortWatch")
|
||||
rows = [(chokepoint, dict(day=days_ago(offset), transit_tankers=value,
|
||||
transit_total=value * 2, capacity_tankers=value * 1000,
|
||||
capacity_total=value * 2000)) for offset, value in pairs]
|
||||
storage.save_chokepoints(rows, 'IMF PortWatch')
|
||||
|
||||
|
||||
def seed_event(zone, direction="hausse", confidence=0.7, days=3):
|
||||
storage.save_news_event(
|
||||
dict(
|
||||
url_hash=f"hash-{zone}",
|
||||
topic="geo",
|
||||
event_type="chokepoint",
|
||||
direction=direction,
|
||||
magnitude="",
|
||||
fuels=[],
|
||||
zone=zone,
|
||||
horizon_days=10,
|
||||
confidence=confidence,
|
||||
valid_from=days_ago(days),
|
||||
valid_until=days_ago(days - 20),
|
||||
observed_at=days_ago(days),
|
||||
published_at=days_ago(days),
|
||||
source_url=f"https://exemple.local/{zone}",
|
||||
extracted_by="gemma4:12b",
|
||||
)
|
||||
)
|
||||
def seed_event(zone, direction='hausse', confidence=0.7, days=3):
|
||||
storage.save_news_event(dict(url_hash=f'hash-{zone}', topic='geo', event_type='chokepoint',
|
||||
direction=direction, magnitude='', fuels=[], zone=zone,
|
||||
horizon_days=10, confidence=confidence,
|
||||
valid_from=days_ago(days), valid_until=days_ago(days - 20),
|
||||
observed_at=days_ago(days), published_at=days_ago(days),
|
||||
source_url=f'https://exemple.local/{zone}',
|
||||
extracted_by='gemma4:12b'))
|
||||
|
||||
|
||||
def test_collapse_is_kept_as_a_signal_when_corroborated(store):
|
||||
"""Un trafic de quelques navires par jour n'est pas « impossible » : c'est un signal."""
|
||||
seed_reference(median=47.0)
|
||||
seed_transits([45, 44, 3, 2, 2, 1, 2])
|
||||
seed_event("détroit d'Ormuz", "hausse", 0.9)
|
||||
seed_event("détroit d'Ormuz", 'hausse', 0.9)
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["direction"] == synthesis.UP, "effondrement du trafic = pression haussière"
|
||||
assert factor["level_label"] == "EXTRÊME"
|
||||
assert factor["level_pct"] <= -90
|
||||
assert factor["corroboration_count"] >= 1
|
||||
assert factor["data_confidence"] < 0.7, "mesure AIS imparfaite : confiance réduite"
|
||||
assert any("corroborée" in note for note in factor["notes"])
|
||||
assert "AIS" in factor["relation"]
|
||||
assert factor['direction'] == synthesis.UP, 'effondrement du trafic = pression haussière'
|
||||
assert factor['level_label'] == 'EXTRÊME'
|
||||
assert factor['level_pct'] <= -90
|
||||
assert factor['corroboration_count'] >= 1
|
||||
assert factor['data_confidence'] < 0.7, 'mesure AIS imparfaite : confiance réduite'
|
||||
assert any('corroborée' in note for note in factor['notes'])
|
||||
assert 'AIS' in factor['relation']
|
||||
|
||||
|
||||
def test_collapse_without_news_keeps_signal_with_lower_confidence(store):
|
||||
seed_reference(median=47.0)
|
||||
seed_transits([45, 44, 3, 2, 2, 1, 2])
|
||||
alone = synthesis.factor_logistique()
|
||||
assert alone["direction"] == synthesis.UP, "aucune règle absolue ne neutralise le signal"
|
||||
assert alone["corroboration_count"] == 0
|
||||
assert any("non corroboré" in note for note in alone["notes"])
|
||||
seed_event("détroit d'Ormuz", "hausse", 0.9)
|
||||
assert alone['direction'] == synthesis.UP, 'aucune règle absolue ne neutralise le signal'
|
||||
assert alone['corroboration_count'] == 0
|
||||
assert any('non corroboré' in note for note in alone['notes'])
|
||||
seed_event("détroit d'Ormuz", 'hausse', 0.9)
|
||||
corroborated = synthesis.factor_logistique()
|
||||
assert corroborated["data_confidence"] > alone["data_confidence"]
|
||||
assert corroborated['data_confidence'] > alone['data_confidence']
|
||||
|
||||
|
||||
def test_level_and_dynamics_are_separate_dimensions(store):
|
||||
@@ -120,13 +85,13 @@ def test_level_and_dynamics_are_separate_dimensions(store):
|
||||
# Niveau pré-crise il y a plusieurs mois, puis effondrement et reprise partielle récente.
|
||||
seed_transits_at([(600, 50), (500, 49), (4, 2), (3, 2), (2, 3), (1, 6), (0, 10)])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["level_label"] == "EXTRÊME"
|
||||
assert factor["level_pct"] <= -75
|
||||
assert factor["dynamics_pct"] > 50
|
||||
assert factor["dynamics_label"] == "nette amélioration"
|
||||
assert factor["direction"] == synthesis.UP, "la tension reste, la détente récente ne l’annule pas"
|
||||
assert "EXTRÊME" in factor["explanation"] and "amélioration" in factor["explanation"]
|
||||
assert "pré-crise" in factor["observation"]
|
||||
assert factor['level_label'] == 'EXTRÊME'
|
||||
assert factor['level_pct'] <= -75
|
||||
assert factor['dynamics_pct'] > 50
|
||||
assert factor['dynamics_label'] == 'nette amélioration'
|
||||
assert factor['direction'] == synthesis.UP, 'la tension reste, la détente récente ne l’annule pas'
|
||||
assert 'EXTRÊME' in factor['explanation'] and 'amélioration' in factor['explanation']
|
||||
assert 'pré-crise' in factor['observation']
|
||||
|
||||
|
||||
def test_tiny_moves_are_not_presented_as_dynamics(store):
|
||||
@@ -134,11 +99,11 @@ def test_tiny_moves_are_not_presented_as_dynamics(store):
|
||||
seed_reference(median=54.0)
|
||||
seed_transits([1, 0, 1, 2, 0, 1, 2])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["level_label"] == "EXTRÊME"
|
||||
assert factor["dynamics_pct"] is None
|
||||
assert factor["dynamics_label"] is None
|
||||
assert any("trop faibles pour" in note for note in factor["notes"])
|
||||
assert factor["direction"] == synthesis.UP, "la tension reste le message principal"
|
||||
assert factor['level_label'] == 'EXTRÊME'
|
||||
assert factor['dynamics_pct'] is None
|
||||
assert factor['dynamics_label'] is None
|
||||
assert any('trop faibles pour' in note for note in factor['notes'])
|
||||
assert factor['direction'] == synthesis.UP, 'la tension reste le message principal'
|
||||
|
||||
|
||||
def test_reference_and_current_use_the_same_metric(store):
|
||||
@@ -146,152 +111,133 @@ def test_reference_and_current_use_the_same_metric(store):
|
||||
seed_reference(median=47.0, total_median=95.0)
|
||||
seed_transits([45, 45, 2, 2, 2, 2, 2])
|
||||
factor = synthesis.factor_logistique()
|
||||
sample = factor["samples"]["Strait of Hormuz"]
|
||||
assert sample["reference_median"] == 47.0
|
||||
assert sample["level_pct"] == round((2 - 47) / 47 * 100, 1)
|
||||
assert "pré-crise 47" in factor["observation_change"]
|
||||
sample = factor['samples']['Strait of Hormuz']
|
||||
assert sample['reference_median'] == 47.0
|
||||
assert sample['level_pct'] == round((2 - 47) / 47 * 100, 1)
|
||||
assert 'pré-crise 47' in factor['observation_change']
|
||||
|
||||
|
||||
def test_missing_pre_crisis_reference_no_conclusion(store):
|
||||
"""Sans référence pré-crise, on ne conclut pas : l'historique local peut être né dans la crise."""
|
||||
seed_transits([2, 2, 1, 2])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["direction"] == synthesis.UNKNOWN
|
||||
assert factor["level_label"] is None
|
||||
assert "référence pré-crise indisponible" in factor["observation"] or any(
|
||||
"référence pré-crise indisponible" in note for note in factor["notes"]
|
||||
)
|
||||
assert "impossible de dire" in factor["explanation"]
|
||||
assert factor['direction'] == synthesis.UNKNOWN
|
||||
assert factor['level_label'] is None
|
||||
assert 'référence pré-crise indisponible' in factor['observation'] or any(
|
||||
'référence pré-crise indisponible' in note for note in factor['notes'])
|
||||
assert 'impossible de dire' in factor['explanation']
|
||||
|
||||
|
||||
def test_recent_recovery_from_a_normal_level_eases_pressure(store):
|
||||
seed_reference(median=50.0)
|
||||
seed_transits([100, 100, 120, 130, 130, 130, 140])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["level_label"] == "SUPÉRIEURE"
|
||||
assert factor["direction"] == synthesis.DOWN
|
||||
assert factor['level_label'] == 'SUPÉRIEURE'
|
||||
assert factor['direction'] == synthesis.DOWN
|
||||
|
||||
|
||||
def test_brut_never_uses_the_monthly_average_as_current_price(store):
|
||||
seed(
|
||||
"dgec_brent_usd",
|
||||
"USD/baril",
|
||||
[dict(day=days_ago(31), value=95.0), dict(day=days_ago(1), value=91.08)],
|
||||
)
|
||||
seed('dgec_brent_usd', 'USD/baril', [dict(day=days_ago(31), value=95.0),
|
||||
dict(day=days_ago(1), value=91.08)])
|
||||
factor = synthesis.factor_brut()
|
||||
assert factor["direction"] == synthesis.UNKNOWN, "pas de direction depuis une moyenne mensuelle"
|
||||
assert factor["daily_available"] is False
|
||||
assert "Cours quotidien du brut indisponible" in factor["observation"]
|
||||
assert factor["historical_context"]["value"] == 91.08
|
||||
assert "contexte historique" in factor["observation_change"].lower()
|
||||
assert "pas un cours du jour" in factor["observation_change"]
|
||||
assert factor['direction'] == synthesis.UNKNOWN, 'pas de direction depuis une moyenne mensuelle'
|
||||
assert factor['daily_available'] is False
|
||||
assert 'Cours quotidien du brut indisponible' in factor['observation']
|
||||
assert factor['historical_context']['value'] == 91.08
|
||||
assert 'contexte historique' in factor['observation_change'].lower()
|
||||
assert 'pas un cours du jour' in factor['observation_change']
|
||||
|
||||
|
||||
def test_brut_uses_a_fresh_daily_quote(store):
|
||||
rows = [dict(day=days_ago(offset), value=88.0 + (5 - offset) * 1.2) for offset in range(5, 0, -1)]
|
||||
seed("brent_usd_daily", "USD/baril", rows)
|
||||
seed(
|
||||
"dgec_brent_usd",
|
||||
"USD/baril",
|
||||
[dict(day=days_ago(31), value=95.0), dict(day=days_ago(1), value=91.08)],
|
||||
)
|
||||
seed('brent_usd_daily', 'USD/baril', rows)
|
||||
seed('dgec_brent_usd', 'USD/baril', [dict(day=days_ago(31), value=95.0),
|
||||
dict(day=days_ago(1), value=91.08)])
|
||||
factor = synthesis.factor_brut()
|
||||
assert factor["daily_available"] is True
|
||||
assert factor["direction"] == synthesis.UP
|
||||
assert factor["series"] == "brent_usd_daily"
|
||||
assert "USD/baril" in factor["observation"]
|
||||
assert factor["historical_context"]["value"] == 91.08, "le mensuel reste exposé comme contexte"
|
||||
assert factor['daily_available'] is True
|
||||
assert factor['direction'] == synthesis.UP
|
||||
assert factor['series'] == 'brent_usd_daily'
|
||||
assert 'USD/baril' in factor['observation']
|
||||
assert factor['historical_context']['value'] == 91.08, 'le mensuel reste exposé comme contexte'
|
||||
|
||||
|
||||
def test_stale_daily_quote_is_declared_unavailable(store):
|
||||
seed(
|
||||
"brent_usd_daily",
|
||||
"USD/baril",
|
||||
[
|
||||
dict(day=days_ago(14), value=88.0),
|
||||
dict(day=days_ago(12), value=89.0),
|
||||
dict(day=days_ago(10), value=90.0),
|
||||
],
|
||||
)
|
||||
seed('brent_usd_daily', 'USD/baril', [dict(day=days_ago(14), value=88.0),
|
||||
dict(day=days_ago(12), value=89.0),
|
||||
dict(day=days_ago(10), value=90.0)])
|
||||
factor = synthesis.factor_brut()
|
||||
assert factor["direction"] == synthesis.UNKNOWN
|
||||
assert "indisponible" in factor["observation"]
|
||||
assert "jours" in factor["observation"]
|
||||
assert factor['direction'] == synthesis.UNKNOWN
|
||||
assert 'indisponible' in factor['observation']
|
||||
assert 'jours' in factor['observation']
|
||||
|
||||
|
||||
def test_stronger_euro_pushes_prices_down(store):
|
||||
seed("usd_per_eur", "USD/EUR", [dict(day=days_ago(6), value=1.10), dict(day=days_ago(1), value=1.16)])
|
||||
seed('usd_per_eur', 'USD/EUR', [dict(day=days_ago(6), value=1.10),
|
||||
dict(day=days_ago(1), value=1.16)])
|
||||
factor = synthesis.factor_change()
|
||||
assert factor["change_pct"] > 0
|
||||
assert factor["direction"] == synthesis.DOWN, "euro plus fort = pression baissière en euros"
|
||||
assert factor["inverted"] is True
|
||||
assert "renforcé" in factor["explanation"]
|
||||
assert factor['change_pct'] > 0
|
||||
assert factor['direction'] == synthesis.DOWN, 'euro plus fort = pression baissière en euros'
|
||||
assert factor['inverted'] is True
|
||||
assert 'renforcé' in factor['explanation']
|
||||
|
||||
|
||||
def test_weaker_euro_pushes_prices_up(store):
|
||||
seed("usd_per_eur", "USD/EUR", [dict(day=days_ago(6), value=1.18), dict(day=days_ago(1), value=1.08)])
|
||||
seed('usd_per_eur', 'USD/EUR', [dict(day=days_ago(6), value=1.18),
|
||||
dict(day=days_ago(1), value=1.08)])
|
||||
factor = synthesis.factor_change()
|
||||
assert factor["direction"] == synthesis.UP
|
||||
assert "affaibli" in factor["explanation"]
|
||||
assert factor['direction'] == synthesis.UP
|
||||
assert 'affaibli' in factor['explanation']
|
||||
|
||||
|
||||
def test_brut_raffinage_and_products_keep_same_sign(store):
|
||||
rows = [dict(day=days_ago(offset), value=80.0 + (5 - offset) * 2) for offset in range(5, 0, -1)]
|
||||
seed("brent_usd_daily", "USD/baril", rows)
|
||||
seed(
|
||||
"dgec_margin_eur_per_tonne",
|
||||
"EUR/tonne",
|
||||
[dict(day=days_ago(40), value=200.0), dict(day=days_ago(2), value=260.0)],
|
||||
)
|
||||
seed("fr_htt_Gazole", "EUR/L", [dict(day=days_ago(21), value=1.20), dict(day=days_ago(1), value=1.28)])
|
||||
brut, raffinage, produits = (
|
||||
synthesis.factor_brut(),
|
||||
synthesis.factor_raffinage(),
|
||||
synthesis.factor_produits("Gazole"),
|
||||
)
|
||||
assert brut["direction"] == synthesis.UP and brut["inverted"] is False
|
||||
assert raffinage["direction"] == synthesis.UP and raffinage["inverted"] is False
|
||||
assert produits["direction"] == synthesis.UP and produits["inverted"] is False
|
||||
assert "€/tonne" in raffinage["observation"]
|
||||
assert "hors taxes" in produits["observation"]
|
||||
seed('brent_usd_daily', 'USD/baril', rows)
|
||||
seed('dgec_margin_eur_per_tonne', 'EUR/tonne', [dict(day=days_ago(40), value=200.0),
|
||||
dict(day=days_ago(2), value=260.0)])
|
||||
seed('fr_htt_Gazole', 'EUR/L', [dict(day=days_ago(21), value=1.20),
|
||||
dict(day=days_ago(1), value=1.28)])
|
||||
brut, raffinage, produits = synthesis.factor_brut(), synthesis.factor_raffinage(), \
|
||||
synthesis.factor_produits('Gazole')
|
||||
assert brut['direction'] == synthesis.UP and brut['inverted'] is False
|
||||
assert raffinage['direction'] == synthesis.UP and raffinage['inverted'] is False
|
||||
assert produits['direction'] == synthesis.UP and produits['inverted'] is False
|
||||
assert '€/tonne' in raffinage['observation']
|
||||
assert 'hors taxes' in produits['observation']
|
||||
|
||||
|
||||
def test_factors_carry_references_d1_d7_d30_and_mean(store):
|
||||
rows = [dict(day=days_ago(1), value=92.0)]
|
||||
rows += [dict(day=days_ago(off), value=90.0 - off * 0.1) for off in range(2, 41)]
|
||||
seed("brent_usd_daily", "USD/baril", rows)
|
||||
seed('brent_usd_daily', 'USD/baril', rows)
|
||||
factor = synthesis.factor_brut()
|
||||
changes = factor["changes"]
|
||||
assert {"d1", "d7", "d30", "prev", "mean30"} <= set(changes)
|
||||
assert changes["d1"]["reference_day"] == days_ago(2)
|
||||
assert "vs J-7" in factor["observation_change"]
|
||||
assert "moyenne 30 jours" in factor["observation_change"]
|
||||
changes = factor['changes']
|
||||
assert {'d1', 'd7', 'd30', 'prev', 'mean30'} <= set(changes)
|
||||
assert changes['d1']['reference_day'] == days_ago(2)
|
||||
assert 'vs J-7' in factor['observation_change']
|
||||
assert 'moyenne 30 jours' in factor['observation_change']
|
||||
|
||||
|
||||
def test_every_factor_explains_observation_and_effect(store):
|
||||
seed_reference()
|
||||
seed_transits([40, 40, 40, 40, 40, 40, 40])
|
||||
built = synthesis.build("Gazole")
|
||||
assert len(built["factors"]) == 6
|
||||
for factor in built["factors"]:
|
||||
assert factor["observation"], f"{factor['key']} sans observation"
|
||||
assert factor["effect"], f"{factor['key']} sans effet affiché"
|
||||
assert factor["relation"], f"{factor['key']} sans relation expliquée"
|
||||
assert factor["arrow"] in ("↑", "↓", "→", "?")
|
||||
if factor["direction"] == synthesis.UNKNOWN:
|
||||
assert factor["effect"] == "? effet non évalué"
|
||||
built = synthesis.build('Gazole')
|
||||
assert len(built['factors']) == 6
|
||||
for factor in built['factors']:
|
||||
assert factor['observation'], f"{factor['key']} sans observation"
|
||||
assert factor['effect'], f"{factor['key']} sans effet affiché"
|
||||
assert factor['relation'], f"{factor['key']} sans relation expliquée"
|
||||
assert factor['arrow'] in ('↑', '↓', '→', '?')
|
||||
if factor['direction'] == synthesis.UNKNOWN:
|
||||
assert factor['effect'] == '? effet non évalué'
|
||||
|
||||
|
||||
def test_pressure_uses_effect_not_observed_move(store):
|
||||
"""Le trafic s'effondre (donnée en baisse) : l'effet est haussier."""
|
||||
seed_reference(median=47.0)
|
||||
seed_transits([45, 45, 2, 2, 2, 2, 2])
|
||||
seed(
|
||||
"brent_usd_daily",
|
||||
"USD/baril",
|
||||
[dict(day=days_ago(offset), value=80.0 + (5 - offset) * 2) for offset in range(5, 0, -1)],
|
||||
)
|
||||
built = synthesis.build("Gazole")
|
||||
assert built["pressure"] == "HAUSSE"
|
||||
logistique = [f for f in built["factors"] if f["key"] == "logistique"][0]
|
||||
assert logistique["direction"] == "up" and logistique["level_pct"] < 0
|
||||
seed('brent_usd_daily', 'USD/baril',
|
||||
[dict(day=days_ago(offset), value=80.0 + (5 - offset) * 2) for offset in range(5, 0, -1)])
|
||||
built = synthesis.build('Gazole')
|
||||
assert built['pressure'] == 'HAUSSE'
|
||||
logistique = [f for f in built['factors'] if f['key'] == 'logistique'][0]
|
||||
assert logistique['direction'] == 'up' and logistique['level_pct'] < 0
|
||||
|
||||
@@ -136,35 +136,18 @@ def test_http_jobs_inventory_exposes_sources_and_schedules(server):
|
||||
|
||||
|
||||
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,
|
||||
)
|
||||
],
|
||||
)
|
||||
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"}
|
||||
)
|
||||
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"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import importlib
|
||||
from datetime import date, timedelta
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -12,7 +12,9 @@ def market(monkeypatch, tmp_path):
|
||||
return module
|
||||
|
||||
|
||||
TODAY = date.today()
|
||||
# Le module raisonne en UTC : le test doit utiliser la même horloge, sinon il casse au passage
|
||||
# de minuit en heure locale (décalage Paris/UTC).
|
||||
TODAY = datetime.now(timezone.utc).date()
|
||||
STOOQ_OK = f"Symbol,Date,Open,Close\nCL.F,{TODAY},80.0,82.4\n"
|
||||
TE_ROW = (
|
||||
'<tr data-symbol="CO1:COM"> <td><a href="/commodity/brent-crude-oil">Brent</a></td>'
|
||||
@@ -24,7 +26,7 @@ TE_ROW = (
|
||||
def test_stooq_parsing_accepts_fresh_quote(market):
|
||||
out = market.parse_stooq(STOOQ_OK)
|
||||
assert out["price_usd"] == pytest.approx(82.4)
|
||||
assert out["date"] == date.today()
|
||||
assert out["date"] == TODAY
|
||||
assert out["change_pct"] == pytest.approx(3.0)
|
||||
|
||||
|
||||
|
||||
171
tests/test_models.py
Normal file
171
tests/test_models.py
Normal file
@@ -0,0 +1,171 @@
|
||||
"""Modèles : algèbre vérifiable, rolls détectés, sélection sans fuite, sorties en c€/L."""
|
||||
import math
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
import market
|
||||
import models
|
||||
import storage
|
||||
|
||||
|
||||
def sample(day, delta_7=0.0, target_7=0.0, slope=0.0, vol=1.0, **extra):
|
||||
features = dict(local_delta_1=delta_7 / 7, local_delta_3=delta_7, local_delta_7=delta_7,
|
||||
local_delta_14=delta_7 * 2, local_slope_7=slope, local_vol_14=vol,
|
||||
local_percentile_90=50.0, local_matched_7=delta_7)
|
||||
features.update(extra)
|
||||
return dict(day=day, price=2.0, features=features, targets={1: target_7, 3: target_7,
|
||||
7: target_7, 14: target_7,
|
||||
21: target_7},
|
||||
target_meta={}, declared_today=3, active_stations=40)
|
||||
|
||||
|
||||
def history(count=200, relation=lambda index: (index % 3) - 1):
|
||||
out = []
|
||||
for index in range(count):
|
||||
day = (date(2024, 1, 1) + timedelta(days=index)).isoformat()
|
||||
delta = (index % 5) - 2.0
|
||||
out.append(sample(day, delta_7=delta, slope=delta / 7, target_7=2.0 * delta,
|
||||
local_delta_1=delta / 5, local_delta_14=delta * 2))
|
||||
return out
|
||||
|
||||
|
||||
def test_probability_up_is_monotonic_and_bounded():
|
||||
assert models.probability_up(5, 2) > 0.5
|
||||
assert models.probability_up(-5, 2) < 0.5
|
||||
assert models.probability_up(0, 2) == 0.5
|
||||
assert 0.9 < models.probability_up(50, 1) <= 1.0
|
||||
assert models.probability_up(3, 0) == 1.0
|
||||
|
||||
|
||||
def test_ridge_recovers_a_simple_linear_relation():
|
||||
train = [sample((date(2024, 1, 1) + timedelta(days=index)).isoformat(),
|
||||
delta_7=float(index), target_7=0.0) for index in range(40)]
|
||||
for row in train:
|
||||
row['targets'][7] = 2.0 * row['features']['local_delta_7']
|
||||
fitted = models.model_autoregressive(train, 7)
|
||||
assert fitted is not None
|
||||
predicted = fitted['predict'](sample('2024-02-01', delta_7=10.0))
|
||||
assert predicted == pytest.approx(20.0, abs=3.0)
|
||||
|
||||
|
||||
def test_naive_model_predicts_no_change():
|
||||
train = history(120)
|
||||
fitted = models.model_naive_unchanged(train, 7)
|
||||
assert fitted['predict'](train[0]) == 0.0
|
||||
out = models.predict(fitted, train[0])
|
||||
assert out['mu_cents'] == 0.0 and out['direction'] == 'flat'
|
||||
|
||||
|
||||
def test_predict_exposes_the_decision_making_output():
|
||||
fitted = models.model_local_trend(history(120), 7)
|
||||
out = models.predict(fitted, sample('2024-05-01', slope=0.5))
|
||||
assert out['mu_cents'] == pytest.approx(3.5, abs=0.01)
|
||||
assert out['interval'][0] < out['mu_cents'] <= out['interval'][1]
|
||||
assert 0 <= out['p_up'] <= 1 and 0.5 <= out['confidence'] <= 1
|
||||
assert out['direction'] == 'up'
|
||||
|
||||
|
||||
def test_selection_uses_a_chronological_tail_and_never_the_test_set():
|
||||
train = history(200)
|
||||
fitted, selection = models.select_model(train, 7, validation_share=0.2)
|
||||
assert fitted is not None
|
||||
assert selection['validation'].startswith('fin d’apprentissage')
|
||||
assert selection['validation_samples'] >= 10
|
||||
assert selection['winner'] in selection['candidate_scores']
|
||||
# Le meilleur score interne est bien celui retenu
|
||||
assert selection['candidate_scores'][selection['winner']] == min(
|
||||
selection['candidate_scores'].values())
|
||||
|
||||
|
||||
def test_selection_refuses_a_too_small_sample():
|
||||
fitted, selection = models.select_model(history(20), 7)
|
||||
assert fitted is None
|
||||
assert 'trop peu' in selection['reason']
|
||||
|
||||
|
||||
def test_roll_detection_flags_a_reverted_jump_only():
|
||||
"""Un saut annulé = changement de contrat ; une vraie tendance = mouvement de marché."""
|
||||
values = [dict(day=(date(2024, 1, 1) + timedelta(days=index)).isoformat(),
|
||||
value=80.0 + index * 0.01) for index in range(40)]
|
||||
clean = market.detect_rolls(values)
|
||||
assert clean['count'] == 0
|
||||
rolled = [dict(point) for point in values]
|
||||
rolled[20]['value'] = rolled[19]['value'] * 1.12 # saut de 12 %
|
||||
for index in range(21, 23): # annulé dans les 2 jours
|
||||
rolled[index]['value'] = rolled[19]['value'] * (1 + (index - 19) * 0.001)
|
||||
flagged = market.detect_rolls(rolled)
|
||||
assert flagged['count'] >= 1
|
||||
assert flagged['days'][0]['day'] == rolled[20]['day']
|
||||
assert 'roll' in flagged['basis']
|
||||
|
||||
|
||||
def test_log_return_respects_publication_dates():
|
||||
"""Une valeur publiée plus tard n'est pas utilisable avant sa publication."""
|
||||
points = [dict(available_from='2026-07-01', day='2026-07-01', value=80.0),
|
||||
dict(available_from='2026-08-15', day='2026-07-01', value=88.0)]
|
||||
assert models._log_return(points, '2026-08-02', 30) is None, 'pas encore publiée'
|
||||
assert models._log_return(points, '2026-08-20', 30) is not None
|
||||
|
||||
|
||||
def test_samples_carry_cent_targets_and_no_future_feature(store):
|
||||
"""La cible est en centimes ; la feature « matched » est connue au jour du calcul."""
|
||||
import series as series_module
|
||||
lat, lon = 44.7737872, -0.5595029
|
||||
base = storage.datetime.now(storage.PARIS).date() - timedelta(days=200)
|
||||
rows = []
|
||||
for index in range(150):
|
||||
day = (base + timedelta(days=index)).isoformat()
|
||||
for station in range(6):
|
||||
rows.append(dict(station_id=f's{station}', fuel='Gazole', day=day,
|
||||
price=round(2.0 + index * 0.001 + station * 0.005, 4),
|
||||
declared_at=f'{day}T09:00:00', lat=lat, lon=lon))
|
||||
store.save_archive_observations(rows, 'archive:test')
|
||||
built = models.build_samples(lat, lon, 15, 'Gazole', days=200, market=False)
|
||||
samples = built['samples']
|
||||
assert samples, built.get('reason')
|
||||
row = [item for item in samples if item['targets'][7] is not None][-1]
|
||||
assert isinstance(row['targets'][7], float)
|
||||
assert abs(row['targets'][7]) < 100, 'cible en centimes par litre'
|
||||
expected = None
|
||||
for item in series_module.matched_variation(built['reconstructed'], horizon=7):
|
||||
if item['day'] == row['day']:
|
||||
expected = item['delta_cents']
|
||||
assert row['features']['local_matched_7'] == expected, 'feature connue au jour J'
|
||||
assert row['targets'][7] == expected, 'cible au jour J+7'
|
||||
|
||||
|
||||
def test_samples_are_empty_without_enough_market_history(store):
|
||||
built = models.build_samples(44.77, -0.55, 15, 'Gazole', days=30, market=False)
|
||||
assert built['samples'] == []
|
||||
assert 'jours de marché reconstruits' in built['reason']
|
||||
|
||||
|
||||
def test_every_candidate_is_reentrainable_on_enough_data():
|
||||
train = history(160)
|
||||
for candidate in models.CANDIDATES:
|
||||
fitted = candidate(train, 7)
|
||||
assert fitted is not None, candidate.__name__
|
||||
out = models.predict(fitted, train[0])
|
||||
assert isinstance(out['mu_cents'], float)
|
||||
|
||||
|
||||
def test_fuel_coverage_reports_the_real_period(store):
|
||||
store.save_archive_observations(
|
||||
[dict(station_id='a', fuel='E10', day='2009-05-05', price=1.2,
|
||||
declared_at='2009-05-05T09:00:00', lat=44.77, lon=-0.55),
|
||||
dict(station_id='b', fuel='E10', day='2026-01-01', price=1.9,
|
||||
declared_at='2026-01-01T09:00:00', lat=44.77, lon=-0.55)], 'archive:test')
|
||||
coverage = models.fuel_coverage('E10')
|
||||
assert coverage['first'] == '2009-05-05'
|
||||
assert coverage['points'] == 2
|
||||
assert coverage['archived'] == 2
|
||||
assert models.fuel_coverage('GPLc')['points'] == 0
|
||||
|
||||
|
||||
def test_standardisation_survives_missing_values():
|
||||
rows = [dict(a=1.0, b=None), dict(a=3.0, b=5.0), dict(a=None, b=7.0)]
|
||||
stats = models._standardise(rows, ['a', 'b'])
|
||||
design = models._design(rows, ['a', 'b'], stats)
|
||||
assert len(design[0]) == 3 and design[0][0] == 1.0
|
||||
assert all(math.isfinite(value) for line in design for value in line)
|
||||
@@ -1,96 +1,84 @@
|
||||
"""Deux indicateurs distincts : position dans l'espace (aujourd'hui) et dans le temps (historique)."""
|
||||
from datetime import timedelta
|
||||
|
||||
from datetime import date, timedelta
|
||||
import storage
|
||||
|
||||
|
||||
def days_ago(n):
|
||||
return (date.today() - timedelta(days=n)).isoformat()
|
||||
return (storage.datetime.now(storage.PARIS).date() - timedelta(days=n)).isoformat()
|
||||
|
||||
|
||||
def seed_observation(store, station_id, fuel, day, price, lat=44.7737872, lon=-0.5595029):
|
||||
store.save_archive_observations(
|
||||
[
|
||||
dict(
|
||||
station_id=station_id,
|
||||
fuel=fuel,
|
||||
day=day,
|
||||
price=price,
|
||||
declared_at=f"{day}T10:00:00",
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
)
|
||||
],
|
||||
"archive:test",
|
||||
)
|
||||
[dict(station_id=station_id, fuel=fuel, day=day, price=price,
|
||||
declared_at=f'{day}T10:00:00', lat=lat, lon=lon)], 'archive:test')
|
||||
|
||||
|
||||
def test_local_position_ranks_stations_today(store):
|
||||
for index, price in enumerate((2.30, 2.10, 1.99, 2.20)):
|
||||
seed_observation(store, f"station{index}", "E10", days_ago(0), price)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert local["kind"] == "local"
|
||||
assert local["stations"] == 4
|
||||
assert local["percentile"] == 0.25, "le meilleur prix est le 1ᵉʳ des 4"
|
||||
assert local["best"] == 1.99
|
||||
assert "dans l’espace" in local["summary"] and "pas dans le temps" in local["summary"]
|
||||
seed_observation(store, f'station{index}', 'E10', days_ago(0), price)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, 'E10')
|
||||
assert local['kind'] == 'local'
|
||||
assert local['stations'] == 4
|
||||
assert local['percentile'] == 0.25, 'le meilleur prix est le 1ᵉʳ des 4'
|
||||
assert local['best'] == 1.99
|
||||
assert 'dans l’espace' in local['summary'] and 'pas dans le temps' in local['summary']
|
||||
|
||||
|
||||
def test_historical_position_uses_daily_medians_over_windows(store):
|
||||
"""Un jour = un point (médiane du panel), pour que les jours chargés ne pèsent pas plus."""
|
||||
for offset in range(40, 0, -1):
|
||||
day = days_ago(offset)
|
||||
seed_observation(store, "a", "E10", day, 2.20 + (offset - 40) * 0.01)
|
||||
seed_observation(store, "b", "E10", day, 2.30 + (offset - 40) * 0.01)
|
||||
seed_observation(store, "a", "E10", days_ago(39), 2.19)
|
||||
seed_observation(store, "b", "E10", days_ago(39), 2.29)
|
||||
seed_observation(store, "c", "E10", days_ago(39), 2.39)
|
||||
seed_observation(store, 'a', 'E10', day, 2.20 + (offset - 40) * 0.01)
|
||||
seed_observation(store, 'b', 'E10', day, 2.30 + (offset - 40) * 0.01)
|
||||
seed_observation(store, 'a', 'E10', days_ago(39), 2.19)
|
||||
seed_observation(store, 'b', 'E10', days_ago(39), 2.29)
|
||||
seed_observation(store, 'c', 'E10', days_ago(39), 2.39)
|
||||
for index, price in enumerate((1.95, 2.05, 2.15)):
|
||||
seed_observation(store, f"today{index}", "E10", days_ago(0), price)
|
||||
position = store.historical_position(44.7737872, -0.5595029, 15, "E10", windows=(30, 90, 365))
|
||||
assert position["kind"] == "historique"
|
||||
seed_observation(store, f'today{index}', 'E10', days_ago(0), price)
|
||||
position = store.historical_position(44.7737872, -0.5595029, 15, 'E10',
|
||||
windows=(30, 90, 365))
|
||||
assert position['kind'] == 'historique'
|
||||
# Reconstruction : les stations qui n'ont pas déclaré aujourd'hui comptent encore, avec leur
|
||||
# dernière valeur connue. La médiane n'est donc pas celle des seules déclarations du jour.
|
||||
assert position["daily_series"][1]["stations"] == 3, "les 3 stations déclarées la veille"
|
||||
assert position["current"] == 1.95, "a et b comptent encore (≈1,81 et ≈1,91), d’où 1,95"
|
||||
assert "aucune interpolation" in position["basis"]
|
||||
assert position["windows"]["30"]["percentile"] is not None
|
||||
assert position["windows"]["30"]["days"] <= 31
|
||||
assert position["windows"]["365"]["percentile"] is None, (
|
||||
"40 jours d’historique ne suffisent pas pour un percentile à 365 jours"
|
||||
)
|
||||
assert (
|
||||
"Historique" in position["windows"]["365"]["summary"]
|
||||
or "insuffisant" in position["windows"]["365"]["summary"]
|
||||
)
|
||||
assert position['daily_series'][1]['stations'] == 3, 'les 3 stations déclarées la veille'
|
||||
assert position['current'] == 1.95, 'a et b comptent encore (≈1,81 et ≈1,91), d’où 1,95'
|
||||
assert 'aucune interpolation' in position['basis']
|
||||
assert position['windows']['30']['percentile'] is not None
|
||||
assert position['windows']['30']['days'] <= 31
|
||||
assert position['windows']['365']['percentile'] is None, \
|
||||
'40 jours d’historique ne suffisent pas pour un percentile à 365 jours'
|
||||
assert 'Historique' in position['windows']['365']['summary'] or \
|
||||
'insuffisant' in position['windows']['365']['summary']
|
||||
|
||||
|
||||
def test_historical_position_is_insufficient_without_history(store):
|
||||
for index, price in enumerate((2.0, 2.1, 2.2)):
|
||||
seed_observation(store, f"today{index}", "E10", days_ago(0), price)
|
||||
position = store.historical_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert position["percentile"] is None
|
||||
assert position["windows"]["30"]["percentile"] is None
|
||||
assert "insuffisant" in position["windows"]["30"]["summary"]
|
||||
seed_observation(store, f'today{index}', 'E10', days_ago(0), price)
|
||||
position = store.historical_position(44.7737872, -0.5595029, 15, 'E10')
|
||||
assert position['percentile'] is None
|
||||
assert position['windows']['30']['percentile'] is None
|
||||
assert 'insuffisant' in position['windows']['30']['summary']
|
||||
|
||||
|
||||
def test_positions_are_two_different_distributions(store):
|
||||
"""Le même jour peut être excellent localement et cher dans le temps."""
|
||||
for offset in range(25, 0, -1):
|
||||
for index, base in enumerate((1.70, 1.75, 1.80)):
|
||||
seed_observation(store, f"old{index}", "E10", days_ago(offset), base)
|
||||
seed_observation(store, f'old{index}', 'E10', days_ago(offset), base)
|
||||
for index, price in enumerate((2.40, 2.45, 2.50)):
|
||||
seed_observation(store, f"today{index}", "E10", days_ago(0), price)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, "E10")
|
||||
historical = store.historical_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert local["percentile"] == round(1 / 3, 3), "meilleur prix du jour"
|
||||
assert historical["percentile"] >= 0.9, "mais cher par rapport à son propre passé"
|
||||
assert local["percentile"] < 0.5 < historical["percentile"]
|
||||
seed_observation(store, f'today{index}', 'E10', days_ago(0), price)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, 'E10')
|
||||
historical = store.historical_position(44.7737872, -0.5595029, 15, 'E10')
|
||||
assert local['percentile'] == round(1 / 3, 3), 'meilleur prix du jour'
|
||||
assert historical['percentile'] >= 0.9, 'mais cher par rapport à son propre passé'
|
||||
assert local['percentile'] < 0.5 < historical['percentile']
|
||||
|
||||
|
||||
def test_stations_outside_the_radius_are_excluded(store):
|
||||
seed_observation(store, "loin", "E10", days_ago(0), 1.50, lat=48.8566, lon=2.3522)
|
||||
seed_observation(store, "proche", "E10", days_ago(1), 2.00)
|
||||
seed_observation(store, "proche", "E10", days_ago(0), 2.05)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert local["stations"] == 1, "la station parisienne est hors rayon"
|
||||
assert local["best"] == 2.05
|
||||
seed_observation(store, 'loin', 'E10', days_ago(0), 1.50, lat=48.8566, lon=2.3522)
|
||||
seed_observation(store, 'proche', 'E10', days_ago(1), 2.00)
|
||||
seed_observation(store, 'proche', 'E10', days_ago(0), 2.05)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, 'E10')
|
||||
assert local['stations'] == 1, 'la station parisienne est hors rayon'
|
||||
assert local['best'] == 2.05
|
||||
|
||||
@@ -4,88 +4,39 @@ Scénarios repris de l'usage réel : appoint minimal pour atteindre une baisse a
|
||||
anticipé justifié par un prix favorable **et** une hausse fiable, véhicule occasionnel basé sur le
|
||||
prochain trajet, et refus d'un passage supplémentaire pour quelques centimes.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
import quantity
|
||||
import storage
|
||||
|
||||
REGULAR = dict(
|
||||
name="Prius",
|
||||
fuel="Gazole",
|
||||
usage="regular",
|
||||
consumption=5.0,
|
||||
min_range_km=80.0,
|
||||
monthly_km=1100.0,
|
||||
tank_liters=43.0,
|
||||
min_topup_liters=10.0,
|
||||
min_gain_eur=1.5,
|
||||
)
|
||||
VAN = dict(
|
||||
name="Van",
|
||||
fuel="Gazole",
|
||||
usage="occasional",
|
||||
consumption=8.0,
|
||||
min_range_km=80.0,
|
||||
monthly_km=0.0,
|
||||
tank_liters=70.0,
|
||||
min_topup_liters=10.0,
|
||||
min_gain_eur=1.5,
|
||||
)
|
||||
REGULAR = dict(name='Prius', fuel='Gazole', usage='regular', consumption=5.0, min_range_km=80.0,
|
||||
monthly_km=1100.0, tank_liters=43.0, min_topup_liters=10.0, min_gain_eur=1.5)
|
||||
VAN = dict(name='Van', fuel='Gazole', usage='occasional', consumption=8.0, min_range_km=80.0,
|
||||
monthly_km=0.0, tank_liters=70.0, min_topup_liters=10.0, min_gain_eur=1.5)
|
||||
|
||||
|
||||
def outlook_down(confidence=0.72, days_min=3, days_max=5, low=0.04, high=0.07):
|
||||
return dict(
|
||||
status="ok",
|
||||
direction="down",
|
||||
change_low=low,
|
||||
change_high=high,
|
||||
days_min=days_min,
|
||||
days_max=days_max,
|
||||
confidence=confidence,
|
||||
model="test-v1",
|
||||
)
|
||||
return dict(status='ok', direction='down', change_low=low, change_high=high,
|
||||
days_min=days_min, days_max=days_max, confidence=confidence, model='test-v1')
|
||||
|
||||
|
||||
def outlook_up(confidence=0.81, days_max=7, low=0.05, high=0.08):
|
||||
return dict(
|
||||
status="ok",
|
||||
direction="up",
|
||||
change_low=low,
|
||||
change_high=high,
|
||||
days_min=2,
|
||||
days_max=days_max,
|
||||
confidence=confidence,
|
||||
model="test-v1",
|
||||
)
|
||||
return dict(status='ok', direction='up', change_low=low, change_high=high,
|
||||
days_min=2, days_max=days_max, confidence=confidence, model='test-v1')
|
||||
|
||||
|
||||
def historical_position(percentile, current=1.62, days=120):
|
||||
"""Position **historique** (fenêtres 30/90/365 jours). Seule utilisée pour anticiper."""
|
||||
return dict(
|
||||
kind="historique",
|
||||
percentile=percentile,
|
||||
current=current,
|
||||
days=days,
|
||||
windows={
|
||||
str(window): dict(percentile=percentile, days=days, current=current, median=1.60, summary="test")
|
||||
for window in (30, 90, 365)
|
||||
},
|
||||
summary="1.620 €/L se situe au test.",
|
||||
)
|
||||
return dict(kind='historique', percentile=percentile, current=current, days=days,
|
||||
windows={str(window): dict(percentile=percentile, days=days, current=current,
|
||||
median=1.60, summary='test') for window in (30, 90, 365)},
|
||||
summary='1.620 €/L se situe au test.')
|
||||
|
||||
|
||||
def local_position(percentile, stations=36):
|
||||
"""Position **locale** du jour : classement dans l'espace, jamais dans le temps."""
|
||||
return dict(
|
||||
kind="local",
|
||||
percentile=percentile,
|
||||
stations=stations,
|
||||
day="2026-09-12",
|
||||
best=1.99,
|
||||
median=2.11,
|
||||
summary="test local",
|
||||
)
|
||||
return dict(kind='local', percentile=percentile, stations=stations, day='2026-09-12',
|
||||
best=1.99, median=2.11, summary='test local')
|
||||
|
||||
|
||||
def test_bands_refuse_false_precision():
|
||||
@@ -101,218 +52,151 @@ def test_daily_km_never_assumes_an_average_for_occasional_use():
|
||||
|
||||
def test_wait_plan_buys_the_minimum_and_respects_comfort_floor():
|
||||
"""Baisse annoncée : appoint minimal, jamais 4 L qui obligeraient à revenir demain."""
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=150,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["usable_km"] == 70.0
|
||||
assert out["daily_km"] == pytest.approx(36.1, abs=0.1)
|
||||
assert out["litres_low"] >= 10.0, "plancher de confort appliqué"
|
||||
assert out["horizon"]["direction"] == "down"
|
||||
assert out["horizon"]["days_min"] == 3
|
||||
assert out["economy"]["reference"].startswith("litres dont")
|
||||
assert any("baisse de 4.0–7.0 c€/L" in reason for reason in out["reasons"])
|
||||
assert any("confiance 72%" in reason for reason in out["reasons"])
|
||||
assert out["forecast_note"] is None
|
||||
out = quantity.plan(REGULAR, remaining_km=150, price_now=1.62, historical_position=historical_position(0.5),
|
||||
outlook=outlook_down())
|
||||
assert out['action'] == 'topup'
|
||||
assert out['usable_km'] == 70.0
|
||||
assert out['daily_km'] == pytest.approx(36.1, abs=0.1)
|
||||
assert out['litres_low'] >= 10.0, 'plancher de confort appliqué'
|
||||
assert out['horizon']['direction'] == 'down'
|
||||
assert out['horizon']['days_min'] == 3
|
||||
assert out['economy']['reference'].startswith('litres dont')
|
||||
assert any('baisse de 4.0–7.0 c€/L' in reason for reason in out['reasons'])
|
||||
assert any('confiance 72%' in reason for reason in out['reasons'])
|
||||
assert out['forecast_note'] is None
|
||||
|
||||
|
||||
def test_wait_plan_buys_nothing_when_the_autonomy_already_covers_the_window():
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(),
|
||||
)
|
||||
assert out["action"] == "wait"
|
||||
assert out["litres_low"] is None
|
||||
assert any("couvre déjà" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(REGULAR, remaining_km=195, price_now=1.62, historical_position=historical_position(0.5),
|
||||
outlook=outlook_down())
|
||||
assert out['action'] == 'wait'
|
||||
assert out['litres_low'] is None
|
||||
assert any('couvre déjà' in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_wait_plan_warns_when_the_tank_cannot_reach_the_window():
|
||||
"""Réservoir trop petit pour tenir jusqu'à la baisse : le dire au lieu de promettre."""
|
||||
small_tank = dict(REGULAR, tank_liters=20.0)
|
||||
out = quantity.plan(
|
||||
small_tank,
|
||||
remaining_km=95,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(days_min=14, days_max=17),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["litres_target"] == pytest.approx(15.3, abs=0.4), "plafonné au réservoir"
|
||||
assert any("second ravitaillement" in caveat for caveat in out["caveats"])
|
||||
assert any("plafonnée" in caveat for caveat in out["caveats"])
|
||||
out = quantity.plan(small_tank, remaining_km=95, price_now=1.62, historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(days_min=14, days_max=17))
|
||||
assert out['action'] == 'topup'
|
||||
assert out['litres_target'] == pytest.approx(15.3, abs=0.4), 'plafonné au réservoir'
|
||||
assert any('second ravitaillement' in caveat for caveat in out['caveats'])
|
||||
assert any('plafonnée' in caveat for caveat in out['caveats'])
|
||||
|
||||
|
||||
def test_full_tank_requires_both_favourable_price_and_upward_forecast():
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "refill"
|
||||
assert out["litres_low"] == 30.0 and out["litres_high"] == 35.0
|
||||
assert out["economy"]["gain_low"] > 0 and out["economy"]["worth_it"] is True
|
||||
joined = " ".join(out["reasons"])
|
||||
assert "centile des prix journaliers" in joined
|
||||
assert "plancher garanti" in joined, "un bon prix n’est jamais présenté comme un plancher certain"
|
||||
out = quantity.plan(REGULAR, remaining_km=195, price_now=1.55, historical_position=historical_position(0.10),
|
||||
outlook=outlook_up())
|
||||
assert out['action'] == 'refill'
|
||||
assert out['litres_low'] == 30.0 and out['litres_high'] == 35.0
|
||||
assert out['economy']['gain_low'] > 0 and out['economy']['worth_it'] is True
|
||||
joined = ' '.join(out['reasons'])
|
||||
assert 'centile des prix journaliers' in joined
|
||||
assert 'plancher garanti' in joined, 'un bon prix n’est jamais présenté comme un plancher certain'
|
||||
|
||||
|
||||
def test_upward_forecast_with_ordinary_price_does_not_justify_a_full_tank():
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.72,
|
||||
historical_position=historical_position(0.70),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["action"] != "refill"
|
||||
assert any("n'est pas historiquement favorable" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(REGULAR, remaining_km=195, price_now=1.72, historical_position=historical_position(0.70),
|
||||
outlook=outlook_up())
|
||||
assert out['action'] == 'topup'
|
||||
assert out['action'] != 'refill'
|
||||
assert any("n'est pas historiquement favorable" in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_small_gain_is_rejected_to_avoid_a_pointless_stop():
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(low=0.004, high=0.006),
|
||||
)
|
||||
assert out["economy"]["worth_it"] is False
|
||||
assert any(
|
||||
"ne multipliez pas les passages" in caveat
|
||||
or "Gain net faible" in caveat
|
||||
or "inutile de multiplier" in caveat
|
||||
for caveat in out["caveats"]
|
||||
)
|
||||
out = quantity.plan(REGULAR, remaining_km=195, price_now=1.55, historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(low=0.004, high=0.006))
|
||||
assert out['economy']['worth_it'] is False
|
||||
assert any('ne multipliez pas les passages' in caveat
|
||||
or 'Gain net faible' in caveat or 'inutile de multiplier' in caveat
|
||||
for caveat in out['caveats'])
|
||||
|
||||
|
||||
def test_no_validated_forecast_means_no_anticipation(store):
|
||||
"""Autonomie confortable : sans prévision validée, on n'anticipe pas du tout."""
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=420,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
local_position=local_position(0.16),
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["action"] == "wait"
|
||||
assert out["litres_low"] is None
|
||||
assert out["forecast_note"] == "modèle non entraîné"
|
||||
assert any("Position historique" in reason for reason in out["reasons"])
|
||||
assert any("Position locale" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(REGULAR, remaining_km=420, price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
local_position=local_position(0.16),
|
||||
outlook=dict(status='insufficient', reason='modèle non entraîné'))
|
||||
assert out['action'] == 'wait'
|
||||
assert out['litres_low'] is None
|
||||
assert out['forecast_note'] == 'modèle non entraîné'
|
||||
assert any('Position historique' in reason for reason in out['reasons'])
|
||||
assert any('Position locale' in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_without_forecast_a_short_runway_still_buys_the_need_only(store):
|
||||
"""Sans prévision, le besoin réel reste couvert — sans argument de prix."""
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=150,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["horizon"] is None
|
||||
assert out["forecast_note"] == "modèle non entraîné"
|
||||
assert out["economy"].get("gain_high") is None
|
||||
out = quantity.plan(REGULAR, remaining_km=150, price_now=1.55, historical_position=historical_position(0.10),
|
||||
outlook=dict(status='insufficient', reason='modèle non entraîné'))
|
||||
assert out['action'] == 'topup'
|
||||
assert out['horizon'] is None
|
||||
assert out['forecast_note'] == 'modèle non entraîné'
|
||||
assert out['economy'].get('gain_high') is None
|
||||
|
||||
|
||||
def test_low_confidence_forecast_does_not_drive_the_quantity():
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=150,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_down(confidence=0.40),
|
||||
)
|
||||
assert out["horizon"] is None, "la prévision ne pilote pas la quantité sous le seuil"
|
||||
assert out["action"] == "topup", "le besoin réel reste couvert"
|
||||
assert "confiance 40%" in out["forecast_note"]
|
||||
assert "seuil" in out["forecast_note"]
|
||||
out = quantity.plan(REGULAR, remaining_km=150, price_now=1.55, historical_position=historical_position(0.10),
|
||||
outlook=outlook_down(confidence=0.40))
|
||||
assert out['horizon'] is None, 'la prévision ne pilote pas la quantité sous le seuil'
|
||||
assert out['action'] == 'topup', 'le besoin réel reste couvert'
|
||||
assert 'confiance 40%' in out['forecast_note']
|
||||
assert 'seuil' in out['forecast_note']
|
||||
|
||||
|
||||
def test_no_forecast_but_immediate_need_still_buys_what_is_needed():
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=110,
|
||||
price_now=1.62,
|
||||
historical_position=None,
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["litres_low"] >= 10.0
|
||||
assert any("Besoin de déplacement estimé" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(REGULAR, remaining_km=110, price_now=1.62, historical_position=None,
|
||||
outlook=dict(status='insufficient', reason='modèle non entraîné'))
|
||||
assert out['action'] == 'topup'
|
||||
assert out['litres_low'] >= 10.0
|
||||
assert any('Besoin de déplacement estimé' in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_margin_reached_recommends_refuelling_without_waiting():
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=80, price_now=1.62, historical_position=None, outlook=outlook_down()
|
||||
)
|
||||
assert out["action"] == "refuel"
|
||||
assert any("marge minimale est atteinte" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(REGULAR, remaining_km=80, price_now=1.62, historical_position=None,
|
||||
outlook=outlook_down())
|
||||
assert out['action'] == 'refuel'
|
||||
assert any('marge minimale est atteinte' in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_occasional_vehicle_uses_the_next_trip_only(store):
|
||||
out = quantity.plan(
|
||||
VAN,
|
||||
remaining_km=280,
|
||||
trip=dict(km=600, date="2026-10-01"),
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["daily_km"] is None, "aucune moyenne mensuelle supposée"
|
||||
assert out["action"] == "topup"
|
||||
assert out["litres_low"] == 30.0 and out["litres_high"] == 35.0
|
||||
assert any("jamais sur une moyenne mensuelle" in caveat for caveat in out["caveats"])
|
||||
assert out["trip_km"] == 600
|
||||
out = quantity.plan(VAN, remaining_km=280, trip=dict(km=600, date='2026-10-01'),
|
||||
outlook=dict(status='insufficient', reason='modèle non entraîné'))
|
||||
assert out['daily_km'] is None, 'aucune moyenne mensuelle supposée'
|
||||
assert out['action'] == 'topup'
|
||||
assert out['litres_low'] == 30.0 and out['litres_high'] == 35.0
|
||||
assert any('jamais sur une moyenne mensuelle' in caveat for caveat in out['caveats'])
|
||||
assert out['trip_km'] == 600
|
||||
|
||||
|
||||
def test_occasional_vehicle_without_trip_asks_for_one(store):
|
||||
out = quantity.plan(
|
||||
VAN, remaining_km=280, trip=None, outlook=dict(status="insufficient", reason="modèle non entraîné")
|
||||
)
|
||||
assert out["action"] == "none"
|
||||
assert out["litres_low"] is None
|
||||
assert any("prochain trajet" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(VAN, remaining_km=280, trip=None,
|
||||
outlook=dict(status='insufficient', reason='modèle non entraîné'))
|
||||
assert out['action'] == 'none'
|
||||
assert out['litres_low'] is None
|
||||
assert any('prochain trajet' in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_occasional_vehicle_anticipates_before_a_rise_during_the_trip(store):
|
||||
out = quantity.plan(VAN, remaining_km=280, trip=dict(km=600, date="2026-10-01"), outlook=outlook_up())
|
||||
assert any("anticiper le plein avant le départ" in caveat for caveat in out["caveats"])
|
||||
out = quantity.plan(VAN, remaining_km=280, trip=dict(km=600, date='2026-10-01'),
|
||||
outlook=outlook_up())
|
||||
assert any('anticiper le plein avant le départ' in caveat for caveat in out['caveats'])
|
||||
|
||||
|
||||
def test_declared_tank_caps_the_quantity(store):
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=780,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "refill"
|
||||
assert out["litres_target"] == pytest.approx(4.0, abs=0.5), "réservoir presque plein"
|
||||
out = quantity.plan(REGULAR, remaining_km=780, price_now=1.55, historical_position=historical_position(0.10),
|
||||
outlook=outlook_up())
|
||||
assert out['action'] == 'refill'
|
||||
assert out['litres_target'] == pytest.approx(4.0, abs=0.5), 'réservoir presque plein'
|
||||
|
||||
|
||||
def test_missing_tank_is_declared_not_invented(store):
|
||||
vehicle = dict(REGULAR, tank_liters=None)
|
||||
out = quantity.plan(
|
||||
vehicle,
|
||||
remaining_km=150,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(),
|
||||
)
|
||||
assert out["litres_target"] is not None
|
||||
assert any("Capacité du réservoir non déclarée" in caveat for caveat in out["caveats"])
|
||||
out = quantity.plan(vehicle, remaining_km=150, price_now=1.62, historical_position=historical_position(0.5),
|
||||
outlook=outlook_down())
|
||||
assert out['litres_target'] is not None
|
||||
assert any('Capacité du réservoir non déclarée' in caveat for caveat in out['caveats'])
|
||||
|
||||
|
||||
def test_quantity_module_never_calls_a_language_model():
|
||||
@@ -320,135 +204,89 @@ def test_quantity_module_never_calls_a_language_model():
|
||||
|
||||
Le module ne peut pas atteindre un modèle sans importer le client : c'est ce qu'on verrouille.
|
||||
"""
|
||||
source = storage.__file__.rsplit("/", 1)[0] + "/quantity.py"
|
||||
text = open(source, encoding="utf-8").read()
|
||||
assert "import llm" not in text
|
||||
assert "llm.extract" not in text and "llm.run" not in text
|
||||
source = (storage.__file__.rsplit('/', 1)[0] + '/quantity.py')
|
||||
text = open(source, encoding='utf-8').read()
|
||||
assert 'import llm' not in text
|
||||
assert 'llm.extract' not in text and 'llm.run' not in text
|
||||
|
||||
|
||||
def test_forecast_is_ignored_until_it_beats_the_naive_rule(store):
|
||||
import forecast
|
||||
|
||||
storage.save_forecast(
|
||||
dict(
|
||||
fuel="Gazole",
|
||||
direction="down",
|
||||
change_low=-0.05,
|
||||
change_high=-0.08,
|
||||
days_min=3,
|
||||
days_max=5,
|
||||
confidence=0.8,
|
||||
model="test-v1",
|
||||
skill_vs_naive=0.001,
|
||||
)
|
||||
)
|
||||
out = forecast.outlook("Gazole")
|
||||
assert out["status"] == "insufficient"
|
||||
assert "règle naïve" in out["reason"]
|
||||
storage.save_forecast(
|
||||
dict(
|
||||
fuel="Gazole",
|
||||
direction="down",
|
||||
change_low=-0.05,
|
||||
change_high=-0.08,
|
||||
days_min=3,
|
||||
days_max=5,
|
||||
confidence=0.8,
|
||||
model="test-v2",
|
||||
skill_vs_naive=0.15,
|
||||
)
|
||||
)
|
||||
out = forecast.outlook("Gazole")
|
||||
assert out["status"] == "ok" and out["direction"] == "down" and out["model"] == "test-v2"
|
||||
storage.save_forecast(dict(fuel='Gazole', direction='down', change_low=-0.05,
|
||||
change_high=-0.08, days_min=3, days_max=5, confidence=0.8,
|
||||
model='test-v1', skill_vs_naive=0.001))
|
||||
out = forecast.outlook('Gazole')
|
||||
assert out['status'] == 'insufficient'
|
||||
assert 'règle naïve' in out['reason']
|
||||
storage.save_forecast(dict(fuel='Gazole', direction='down', change_low=-0.05,
|
||||
change_high=-0.08, days_min=3, days_max=5, confidence=0.8,
|
||||
model='test-v2', skill_vs_naive=0.15))
|
||||
out = forecast.outlook('Gazole')
|
||||
assert out['status'] == 'ok' and out['direction'] == 'down' and out['model'] == 'test-v2'
|
||||
|
||||
|
||||
def test_absent_model_is_declared_absent(store):
|
||||
import forecast
|
||||
|
||||
out = forecast.outlook("Gazole")
|
||||
assert out["status"] == "insufficient"
|
||||
assert "pas encore entraîné" in out["reason"]
|
||||
out = forecast.outlook('Gazole')
|
||||
assert out['status'] == 'insufficient'
|
||||
assert 'pas encore entraîné' in out['reason']
|
||||
|
||||
|
||||
def test_local_rank_never_triggers_a_full_tank(store):
|
||||
"""Excellent localement mais cher dans le temps : aucune anticipation autorisée."""
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
historical_position=historical_position(0.72),
|
||||
local_position=local_position(0.01),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["action"] != "refill"
|
||||
assert any("n'est pas historiquement favorable" in reason for reason in out["reasons"])
|
||||
assert any("36 stations" in reason for reason in out["reasons"])
|
||||
out = quantity.plan(REGULAR, remaining_km=200,
|
||||
historical_position=historical_position(0.72),
|
||||
local_position=local_position(0.01), outlook=outlook_up())
|
||||
assert out['action'] == 'topup'
|
||||
assert out['action'] != 'refill'
|
||||
assert any("n'est pas historiquement favorable" in reason for reason in out['reasons'])
|
||||
assert any('36 stations' in reason for reason in out['reasons'])
|
||||
|
||||
|
||||
def test_historical_rank_is_the_only_anticipation_trigger(store):
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.90),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "refill"
|
||||
assert any("Position historique favorable" in reason for reason in out["reasons"])
|
||||
assert any("ne participe pas à cette décision" in caveat for caveat in out["caveats"])
|
||||
out = quantity.plan(REGULAR, remaining_km=200,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.90), outlook=outlook_up())
|
||||
assert out['action'] == 'refill'
|
||||
assert any('Position historique favorable' in reason for reason in out['reasons'])
|
||||
assert any('ne participe pas à cette décision' in caveat for caveat in out['caveats'])
|
||||
|
||||
|
||||
def test_detour_fuel_is_deducted_from_the_net_gain(store):
|
||||
"""Un détour peut annuler une économie : le gain net doit le montrer."""
|
||||
from quantity import detour_cost
|
||||
|
||||
detour = dict(extra_km=40.0, nearest_km=3.0, chosen_km=43.0)
|
||||
detour["cost_eur"] = detour_cost(detour, REGULAR, 1.55)
|
||||
assert detour["cost_eur"] == round(40 * 5 / 100 * 1.55, 2), "km × consommation × prix"
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.9),
|
||||
outlook=outlook_up(),
|
||||
detour=detour,
|
||||
)
|
||||
assert out["economy"]["detour_eur"] == detour["cost_eur"]
|
||||
assert out["economy"]["net_high"] == round(out["economy"]["gain_high"] - detour["cost_eur"], 2)
|
||||
assert out["economy"]["worth_it"] is False, "gain net sous le seuil : pas un passage de plus"
|
||||
assert any("Gain net faible" in caveat for caveat in out["caveats"])
|
||||
detour['cost_eur'] = detour_cost(detour, REGULAR, 1.55)
|
||||
assert detour['cost_eur'] == round(40 * 5 / 100 * 1.55, 2), 'km × consommation × prix'
|
||||
out = quantity.plan(REGULAR, remaining_km=200, price_now=1.55,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.9), outlook=outlook_up(), detour=detour)
|
||||
assert out['economy']['detour_eur'] == detour['cost_eur']
|
||||
assert out['economy']['net_high'] == round(out['economy']['gain_high'] - detour['cost_eur'], 2)
|
||||
assert out['economy']['worth_it'] is False, 'gain net sous le seuil : pas un passage de plus'
|
||||
assert any('Gain net faible' in caveat for caveat in out['caveats'])
|
||||
|
||||
|
||||
def test_a_small_detour_can_be_absorbed_by_the_expected_gain(store):
|
||||
from quantity import detour_cost
|
||||
|
||||
detour = dict(extra_km=2.0, nearest_km=3.0, chosen_km=5.0)
|
||||
detour["cost_eur"] = detour_cost(detour, REGULAR, 1.55)
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.9),
|
||||
outlook=outlook_up(),
|
||||
detour=detour,
|
||||
)
|
||||
assert out["economy"]["worth_it"] is True
|
||||
assert out["economy"]["net_high"] > out["economy"]["gain_high"] - 1.0
|
||||
detour['cost_eur'] = detour_cost(detour, REGULAR, 1.55)
|
||||
out = quantity.plan(REGULAR, remaining_km=200, price_now=1.55,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.9), outlook=outlook_up(), detour=detour)
|
||||
assert out['economy']['worth_it'] is True
|
||||
assert out['economy']['net_high'] > out['economy']['gain_high'] - 1.0
|
||||
|
||||
|
||||
def test_detour_cost_is_computed_by_the_engine(store):
|
||||
from quantity import detour_cost
|
||||
|
||||
assert detour_cost(None, REGULAR, 2.0) is None
|
||||
assert detour_cost(dict(extra_km=0.0), REGULAR, 2.0) == 0.0
|
||||
assert detour_cost(dict(extra_km=10.0), REGULAR, 2.0) == 1.0, "10 km × 5 L/100 × 2 €/L"
|
||||
assert detour_cost(dict(extra_km=10.0), REGULAR, 2.0) == 1.0, '10 km × 5 L/100 × 2 €/L'
|
||||
|
||||
|
||||
def test_tank_content_is_always_an_estimate(store):
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=150, historical_position=historical_position(0.5), outlook=outlook_down()
|
||||
)
|
||||
assert out["estimated_in_tank_liters"] == 7.5, "estimation issue de l’autonomie affichée"
|
||||
assert any("estimé" in caveat or "estimation" in caveat for caveat in out["caveats"])
|
||||
out = quantity.plan(REGULAR, remaining_km=150, historical_position=historical_position(0.5),
|
||||
outlook=outlook_down())
|
||||
assert out['estimated_in_tank_liters'] == 7.5, 'estimation issue de l’autonomie affichée'
|
||||
assert any('estimé' in caveat or 'estimation' in caveat for caveat in out['caveats'])
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Cache de routes : origine normalisée, rattachement au favori, séparation statique / trafic."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
@@ -15,11 +14,11 @@ def meters_between(origin, other):
|
||||
def test_gps_jitter_of_a_few_dozens_of_meters_shares_one_cache_key(store):
|
||||
target = (44.795280, -0.604509)
|
||||
first = (44.78060, -0.57060)
|
||||
second = (44.78063, -0.57064) # ~5 m plus loin : bruit normal d'une mesure téléphone
|
||||
third = (44.78110, -0.57110) # ~70 m plus loin
|
||||
second = (44.78063, -0.57064) # ~5 m plus loin : bruit normal d'une mesure téléphone
|
||||
third = (44.78110, -0.57110) # ~70 m plus loin
|
||||
assert meters_between(first, second) < 10
|
||||
keys = {storage.route_key(point, target) for point in (first, second, third)}
|
||||
assert len(keys) == 1, f"positions quasi identiques, clés distinctes : {keys}"
|
||||
assert len(keys) == 1, f'positions quasi identiques, clés distinctes : {keys}'
|
||||
|
||||
|
||||
def test_two_positions_hundreds_of_meters_apart_use_distinct_keys(store):
|
||||
@@ -38,89 +37,77 @@ def test_distinct_stations_never_share_a_key(store):
|
||||
|
||||
def test_favourite_tag_replaces_raw_coordinates(store):
|
||||
target = (44.795280, -0.604509)
|
||||
key = storage.route_key((44.78055, -0.57051), target, origin_tag="fav:3")
|
||||
assert key.startswith("fav:3|")
|
||||
assert storage.route_key((44.79999, -0.57051), target, origin_tag="fav:3") == key
|
||||
key = storage.route_key((44.78055, -0.57051), target, origin_tag='fav:3')
|
||||
assert key.startswith('fav:3|')
|
||||
assert storage.route_key((44.79999, -0.57051), target, origin_tag='fav:3') == key
|
||||
|
||||
|
||||
def test_match_favorite_absorbs_gps_jitter(store):
|
||||
storage.save_entity("favorites", dict(name="Villenave", lat=44.78060, lon=-0.57060, radius_km=10))
|
||||
storage.save_entity('favorites', dict(name='Villenave', lat=44.78060, lon=-0.57060, radius_km=10))
|
||||
favorite = storage.match_favorite(44.78068, -0.57070)
|
||||
assert favorite and favorite["name"] == "Villenave"
|
||||
assert favorite["distance_km"] <= 0.15
|
||||
assert favorite and favorite['name'] == 'Villenave'
|
||||
assert favorite['distance_km'] <= 0.15
|
||||
assert storage.match_favorite(44.90000, -0.57070) is None
|
||||
|
||||
|
||||
def test_osrm_duration_is_static_and_never_an_eta(store, monkeypatch):
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"osrm",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=5000.0, duration_s=600.0, duration_kind=routing.STATIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "osrm")
|
||||
routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)])
|
||||
assert routes["A"]["duration_kind"] == routing.STATIC
|
||||
assert routes["A"]["duration_label"] == "hors trafic"
|
||||
assert routes["A"]["eta_min"] is None
|
||||
assert info["eta_count"] == 0
|
||||
assert "hors trafic" in info["eta_note"]
|
||||
monkeypatch.setitem(routing.PROVIDERS, 'osrm',
|
||||
lambda origin, targets: {t[0]: dict(distance_m=5000.0, duration_s=600.0,
|
||||
duration_kind=routing.STATIC)
|
||||
for t in targets})
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'osrm')
|
||||
routes, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)])
|
||||
assert routes['A']['duration_kind'] == routing.STATIC
|
||||
assert routes['A']['duration_label'] == 'hors trafic'
|
||||
assert routes['A']['eta_min'] is None
|
||||
assert info['eta_count'] == 0
|
||||
assert 'hors trafic' in info['eta_note']
|
||||
assert store.eta_lookup([storage.route_key((44.78, -0.57), (44.79, -0.60))]) == {}
|
||||
|
||||
|
||||
def test_google_traffic_duration_goes_to_short_cache_only(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"google",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=8000.0, duration_s=900.0, duration_kind=routing.TRAFFIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)])
|
||||
assert routes["A"]["distance_km"] == pytest.approx(8.0)
|
||||
assert routes["A"]["duration_min"] is None, "une durée de trafic n’est pas une durée statique"
|
||||
assert routes["A"]["eta_min"] == pytest.approx(15.0)
|
||||
assert routes["A"]["eta_age_seconds"] is not None
|
||||
assert info["eta_count"] == 1 and info["eta_provider"] == "google"
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test')
|
||||
monkeypatch.setitem(routing.PROVIDERS, 'google',
|
||||
lambda origin, targets: {t[0]: dict(distance_m=8000.0, duration_s=900.0,
|
||||
duration_kind=routing.TRAFFIC)
|
||||
for t in targets})
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google')
|
||||
routes, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)])
|
||||
assert routes['A']['distance_km'] == pytest.approx(8.0)
|
||||
assert routes['A']['duration_min'] is None, 'une durée de trafic n’est pas une durée statique'
|
||||
assert routes['A']['eta_min'] == pytest.approx(15.0)
|
||||
assert routes['A']['eta_age_seconds'] is not None
|
||||
assert info['eta_count'] == 1 and info['eta_provider'] == 'google'
|
||||
cached = store.route_lookup([storage.route_key((44.78, -0.57), (44.79, -0.60))])
|
||||
assert list(cached.values())[0]["duration_s"] is None, "pas de durée trafic dans le cache long"
|
||||
assert list(cached.values())[0]['duration_s'] is None, 'pas de durée trafic dans le cache long'
|
||||
|
||||
|
||||
def test_stale_eta_is_ignored_and_static_duration_is_used(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"google",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=8000.0, duration_s=900.0, duration_kind=routing.TRAFFIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
routing.routes((44.78, -0.57), [("A", 44.79, -0.60)])
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test')
|
||||
monkeypatch.setitem(routing.PROVIDERS, 'google',
|
||||
lambda origin, targets: {t[0]: dict(distance_m=8000.0, duration_s=900.0,
|
||||
duration_kind=routing.TRAFFIC)
|
||||
for t in targets})
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google')
|
||||
routing.routes((44.78, -0.57), [('A', 44.79, -0.60)])
|
||||
key = storage.route_key((44.78, -0.57), (44.79, -0.60))
|
||||
stale = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
|
||||
store.eta_save([dict(key=key, duration_s=1800.0, provider="google")])
|
||||
store.eta_save([dict(key=key, duration_s=1800.0, provider='google')])
|
||||
with store.connect() as db:
|
||||
db.execute("UPDATE route_eta SET computed_at=? WHERE key=?", (stale, key))
|
||||
routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)], eta_ttl=900)
|
||||
assert routes["A"]["eta_min"] is None, "une ETA de 3 heures n’est pas une ETA actuelle"
|
||||
assert info["eta_count"] == 0
|
||||
assert "Aucune ETA de trafic" in info["eta_note"]
|
||||
db.execute('UPDATE route_eta SET computed_at=? WHERE key=?', (stale, key))
|
||||
routes, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)], eta_ttl=900)
|
||||
assert routes['A']['eta_min'] is None, 'une ETA de 3 heures n’est pas une ETA actuelle'
|
||||
assert info['eta_count'] == 0
|
||||
assert 'Aucune ETA de trafic' in info['eta_note']
|
||||
|
||||
|
||||
def test_eta_key_is_separate_for_tagged_origin(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"google",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=4000.0, duration_s=600.0, duration_kind=routing.TRAFFIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
_, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)], origin_tag="fav:7")
|
||||
assert info["eta_count"] == 1
|
||||
assert store.eta_lookup(["fav:7|44.7900|-0.6000"]) != {}
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test')
|
||||
monkeypatch.setitem(routing.PROVIDERS, 'google',
|
||||
lambda origin, targets: {t[0]: dict(distance_m=4000.0, duration_s=600.0,
|
||||
duration_kind=routing.TRAFFIC)
|
||||
for t in targets})
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google')
|
||||
_, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)], origin_tag='fav:7')
|
||||
assert info['eta_count'] == 1
|
||||
assert store.eta_lookup(['fav:7|44.7900|-0.6000']) != {}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Distances routières : fournisseurs, cache, application du rayon, liens de navigation."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
@@ -9,69 +8,55 @@ import routing
|
||||
import storage
|
||||
|
||||
|
||||
def station_row(station_id, lat, lon, price=1.9, fuel="Gazole"):
|
||||
return dict(
|
||||
id=station_id,
|
||||
name=f"Station {station_id}",
|
||||
address="Rue",
|
||||
city="Nantes",
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
prices={fuel: price},
|
||||
updates={fuel: "2026-09-12 08:00:00"},
|
||||
road="",
|
||||
)
|
||||
def station_row(station_id, lat, lon, price=1.9, fuel='Gazole'):
|
||||
return dict(id=station_id, name=f'Station {station_id}', address='Rue', city='Nantes',
|
||||
lat=lat, lon=lon, prices={fuel: price}, updates={fuel: '2026-09-12 08:00:00'},
|
||||
road='')
|
||||
|
||||
|
||||
def test_provider_order_skips_google_without_key(monkeypatch):
|
||||
monkeypatch.delenv("FUEL_GOOGLE_MAPS_API_KEY", raising=False)
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "")
|
||||
assert routing.provider_order() == ["osrm"]
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google,osrm")
|
||||
assert routing.provider_order() == ["osrm"], "Google sans clé ne doit jamais être tenté"
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
assert routing.provider_order() == ["google", "osrm"]
|
||||
monkeypatch.delenv('FUEL_GOOGLE_MAPS_API_KEY', raising=False)
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', '')
|
||||
assert routing.provider_order() == ['osrm']
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google,osrm')
|
||||
assert routing.provider_order() == ['osrm'], 'Google sans clé ne doit jamais être tenté'
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test')
|
||||
assert routing.provider_order() == ['google', 'osrm']
|
||||
|
||||
|
||||
def test_provider_osrm_parses_table_and_drops_unreachable(monkeypatch):
|
||||
payload = json.dumps(
|
||||
{"code": "Ok", "distances": [[0, 3699.3, None]], "durations": [[0, 580.3, None]]}
|
||||
).encode()
|
||||
monkeypatch.setattr(routing, "_get", lambda *args, **kwargs: payload)
|
||||
found = routing.provider_osrm((48.85, 2.35), [("A", 48.86, 2.30), ("B", 48.90, 2.25)])
|
||||
assert found["A"]["distance_m"] == pytest.approx(3699.3)
|
||||
assert found["A"]["duration_s"] == pytest.approx(580.3)
|
||||
assert "B" not in found, "aucune route : la station n’est pas estimée"
|
||||
payload = json.dumps({'code': 'Ok', 'distances': [[0, 3699.3, None]],
|
||||
'durations': [[0, 580.3, None]]}).encode()
|
||||
monkeypatch.setattr(routing, '_get', lambda *args, **kwargs: payload)
|
||||
found = routing.provider_osrm((48.85, 2.35), [('A', 48.86, 2.30), ('B', 48.90, 2.25)])
|
||||
assert found['A']['distance_m'] == pytest.approx(3699.3)
|
||||
assert found['A']['duration_s'] == pytest.approx(580.3)
|
||||
assert 'B' not in found, 'aucune route : la station n’est pas estimée'
|
||||
|
||||
|
||||
def test_provider_google_requires_key_and_parses_matrix(monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "")
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', '')
|
||||
with pytest.raises(ValueError):
|
||||
routing.provider_google((48.85, 2.35), [("A", 48.86, 2.30)])
|
||||
routing.provider_google((48.85, 2.35), [('A', 48.86, 2.30)])
|
||||
captured = {}
|
||||
|
||||
def fake_get(url, timeout=None, data=None, headers=None):
|
||||
captured["url"], captured["body"] = url, json.loads(data or b"{}")
|
||||
return json.dumps(
|
||||
[
|
||||
{
|
||||
"destinationIndex": 0,
|
||||
"condition": "ROUTE_EXISTS",
|
||||
"distanceMeters": 4200,
|
||||
"duration": "720s",
|
||||
},
|
||||
{"destinationIndex": 1, "condition": "ROUTE_NOT_FOUND"},
|
||||
]
|
||||
).encode()
|
||||
captured['url'], captured['body'] = url, json.loads(data or b'{}')
|
||||
return json.dumps([
|
||||
{'destinationIndex': 0, 'condition': 'ROUTE_EXISTS', 'distanceMeters': 4200,
|
||||
'duration': '720s'},
|
||||
{'destinationIndex': 1, 'condition': 'ROUTE_NOT_FOUND'},
|
||||
]).encode()
|
||||
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setattr(routing, "_get", fake_get)
|
||||
found = routing.provider_google((48.85, 2.35), [("A", 48.86, 2.30), ("B", 48.90, 2.25)])
|
||||
assert "computeRouteMatrix" in captured["url"]
|
||||
assert captured["url"] == "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix"
|
||||
assert len(captured["body"]["destinations"]) == 2
|
||||
assert captured["body"]["travelMode"] == "DRIVE"
|
||||
assert found == {"A": dict(distance_m=4200.0, duration_s=720.0, duration_kind=routing.TRAFFIC)}
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test')
|
||||
monkeypatch.setattr(routing, '_get', fake_get)
|
||||
found = routing.provider_google((48.85, 2.35), [('A', 48.86, 2.30), ('B', 48.90, 2.25)])
|
||||
assert 'computeRouteMatrix' in captured['url']
|
||||
assert captured['url'] == 'https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix'
|
||||
assert len(captured['body']['destinations']) == 2
|
||||
assert captured['body']['travelMode'] == 'DRIVE'
|
||||
assert found == {'A': dict(distance_m=4200.0, duration_s=720.0,
|
||||
duration_kind=routing.TRAFFIC)}
|
||||
|
||||
|
||||
def test_routes_uses_cache_then_provider(store, monkeypatch):
|
||||
@@ -81,105 +66,83 @@ def test_routes_uses_cache_then_provider(store, monkeypatch):
|
||||
calls.append(targets)
|
||||
return {station_id: dict(distance_m=5000.0, duration_s=600.0) for station_id, _a, _b in targets}
|
||||
|
||||
monkeypatch.setitem(routing.PROVIDERS, "osrm", fake_provider)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "osrm")
|
||||
monkeypatch.setitem(routing.PROVIDERS, 'osrm', fake_provider)
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'osrm')
|
||||
origin = (48.85, 2.35)
|
||||
targets = [("A", 48.86, 2.30)]
|
||||
targets = [('A', 48.86, 2.30)]
|
||||
first, info = routing.routes(origin, targets)
|
||||
assert first["A"]["distance_km"] == pytest.approx(5.0)
|
||||
assert first["A"]["duration_min"] == pytest.approx(10.0)
|
||||
assert info["provider"] == "osrm" and info["computed"] == 1 and info["from_cache"] == 0
|
||||
assert first['A']['distance_km'] == pytest.approx(5.0)
|
||||
assert first['A']['duration_min'] == pytest.approx(10.0)
|
||||
assert info['provider'] == 'osrm' and info['computed'] == 1 and info['from_cache'] == 0
|
||||
second, info2 = routing.routes(origin, targets)
|
||||
assert info2["from_cache"] == 1 and info2["computed"] == 0
|
||||
assert len(calls) == 1, "la seconde demande ne doit pas rappeler le fournisseur"
|
||||
assert info2['from_cache'] == 1 and info2['computed'] == 0
|
||||
assert len(calls) == 1, 'la seconde demande ne doit pas rappeler le fournisseur'
|
||||
assert store.route_lookup([storage.route_key(origin, (48.86, 2.30))], max_age_days=1)
|
||||
|
||||
|
||||
def test_routes_without_provider_says_so_and_invents_nothing(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "PROVIDERS", {})
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "")
|
||||
routes, info = routing.routes((48.85, 2.35), [("A", 48.86, 2.30)])
|
||||
monkeypatch.setattr(routing, 'PROVIDERS', {})
|
||||
monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google')
|
||||
monkeypatch.setattr(routing, 'GOOGLE_KEY', '')
|
||||
routes, info = routing.routes((48.85, 2.35), [('A', 48.86, 2.30)])
|
||||
assert routes == {}
|
||||
assert info["provider"] == "none"
|
||||
assert "à vol d’oiseau" in info["note"]
|
||||
assert info['provider'] == 'none'
|
||||
assert 'à vol d’oiseau' in info['note']
|
||||
|
||||
|
||||
def test_nearest_stations_applies_radius_on_road_distance(store, monkeypatch):
|
||||
rows = [
|
||||
station_row("proche", 48.8610, 2.3010, price=1.95),
|
||||
station_row("loin", 48.9000, 2.2500, price=1.80),
|
||||
station_row("hors", 49.2000, 2.6000, price=1.70),
|
||||
]
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows)
|
||||
rows = [station_row('proche', 48.8610, 2.3010, price=1.95),
|
||||
station_row('loin', 48.9000, 2.2500, price=1.80),
|
||||
station_row('hors', 49.2000, 2.6000, price=1.70)]
|
||||
monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: rows)
|
||||
|
||||
def fake_routes(origin, targets, origin_tag=None, **kwargs):
|
||||
distances = {"proche": 1200.0, "loin": 18500.0, "hors": 40000.0}
|
||||
return (
|
||||
{
|
||||
station_id: dict(
|
||||
distance_km=distances[station_id] / 1000,
|
||||
duration_min=5.0,
|
||||
duration_label="hors trafic",
|
||||
provider="osrm",
|
||||
cached=False,
|
||||
)
|
||||
for station_id, _lat, _lon in targets
|
||||
},
|
||||
dict(provider="osrm", computed=len(targets), from_cache=0, failures=[], note=""),
|
||||
)
|
||||
distances = {'proche': 1200.0, 'loin': 18500.0, 'hors': 40000.0}
|
||||
return ({station_id: dict(distance_km=distances[station_id] / 1000, duration_min=5.0,
|
||||
duration_label='hors trafic', provider='osrm', cached=False)
|
||||
for station_id, _lat, _lon in targets},
|
||||
dict(provider='osrm', computed=len(targets), from_cache=0, failures=[], note=''))
|
||||
|
||||
monkeypatch.setattr(routing, "routes", fake_routes)
|
||||
stations, info = app.nearest_stations(48.86, 2.30, "Gazole", 15)
|
||||
assert [s.id for s in stations] == ["proche"], "rayon de 15 km appliqué à la distance routière"
|
||||
monkeypatch.setattr(routing, 'routes', fake_routes)
|
||||
stations, info = app.nearest_stations(48.86, 2.30, 'Gazole', 15)
|
||||
assert [s.id for s in stations] == ['proche'], 'rayon de 15 km appliqué à la distance routière'
|
||||
assert stations[0].route_distance_km == pytest.approx(1.2)
|
||||
assert stations[0].route_duration_min == pytest.approx(5.0)
|
||||
assert stations[0].distance_km < 1, "le vol d’oiseau reste disponible en interne"
|
||||
assert info["provider"] == "osrm"
|
||||
assert stations[0].distance_km < 1, 'le vol d’oiseau reste disponible en interne'
|
||||
assert info['provider'] == 'osrm'
|
||||
|
||||
|
||||
def test_nearest_stations_without_routing_falls_back_and_says_it(store, monkeypatch):
|
||||
rows = [station_row("proche", 48.8610, 2.3010), station_row("hors", 49.1000, 2.5000)]
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows)
|
||||
monkeypatch.setattr(
|
||||
routing,
|
||||
"routes",
|
||||
lambda *args, **kwargs: (
|
||||
{},
|
||||
dict(provider="none", computed=0, from_cache=0, failures=["TimeoutError"], note="indispo"),
|
||||
),
|
||||
)
|
||||
stations, info = app.nearest_stations(48.86, 2.30, "Gazole", 5)
|
||||
assert [s.id for s in stations] == ["proche"]
|
||||
rows = [station_row('proche', 48.8610, 2.3010), station_row('hors', 49.1000, 2.5000)]
|
||||
monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: rows)
|
||||
monkeypatch.setattr(routing, 'routes', lambda *args, **kwargs: (
|
||||
{}, dict(provider='none', computed=0, from_cache=0, failures=['TimeoutError'], note='indispo')))
|
||||
stations, info = app.nearest_stations(48.86, 2.30, 'Gazole', 5)
|
||||
assert [s.id for s in stations] == ['proche']
|
||||
assert stations[0].route_distance_km is None
|
||||
assert info["provider"] == "none"
|
||||
assert info['provider'] == 'none'
|
||||
|
||||
|
||||
def test_navigation_links_use_exact_coordinates():
|
||||
links = app.navigation_links(48.861012, 2.301045)
|
||||
assert links["coordinates"] == "48.861012,2.301045"
|
||||
assert links["google_maps"].startswith("https://www.google.com/maps/dir/?api=1&destination=")
|
||||
assert "48.861012,2.301045" in links["google_maps"] and "travelmode=driving" in links["google_maps"]
|
||||
assert links["waze"].startswith("https://waze.com/ul?ll=48.861012,2.301045")
|
||||
assert links['coordinates'] == '48.861012,2.301045'
|
||||
assert links['google_maps'].startswith('https://www.google.com/maps/dir/?api=1&destination=')
|
||||
assert '48.861012,2.301045' in links['google_maps'] and 'travelmode=driving' in links['google_maps']
|
||||
assert links['waze'].startswith('https://waze.com/ul?ll=48.861012,2.301045')
|
||||
|
||||
|
||||
def test_station_payload_carries_detour_ready_fields(store, monkeypatch):
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [station_row("A", 48.861, 2.301)])
|
||||
monkeypatch.setattr(
|
||||
routing,
|
||||
"routes",
|
||||
lambda *args, **kwargs: (
|
||||
{"A": dict(distance_km=3.4, duration_min=8.0, provider="osrm", cached=False)},
|
||||
dict(provider="osrm", computed=1, from_cache=0, failures=[], note=""),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(app.collector, "ensure_fresh_local", lambda **kwargs: dict(refreshed=False))
|
||||
monkeypatch.setattr(app.promotions, "active", lambda: [])
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [station_row("A", 48.861, 2.301)])
|
||||
out = app.advice(48.86, 2.30, "Gazole", 15)
|
||||
station = out["stations"][0]
|
||||
assert station["route_distance_km"] == pytest.approx(3.4)
|
||||
assert station["route_duration_min"] == pytest.approx(8.0)
|
||||
assert station["navigation"]["waze"]
|
||||
assert out["detour_prep"]["available"] is True
|
||||
assert out["routing"]["provider"] == "osrm"
|
||||
monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: [station_row('A', 48.861, 2.301)])
|
||||
monkeypatch.setattr(routing, 'routes', lambda *args, **kwargs: (
|
||||
{'A': dict(distance_km=3.4, duration_min=8.0, provider='osrm', cached=False)},
|
||||
dict(provider='osrm', computed=1, from_cache=0, failures=[], note='')))
|
||||
monkeypatch.setattr(app.collector, 'ensure_fresh_local', lambda **kwargs: dict(refreshed=False))
|
||||
monkeypatch.setattr(app.promotions, 'active', lambda: [])
|
||||
monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: [station_row('A', 48.861, 2.301)])
|
||||
out = app.advice(48.86, 2.30, 'Gazole', 15)
|
||||
station = out['stations'][0]
|
||||
assert station['route_distance_km'] == pytest.approx(3.4)
|
||||
assert station['route_duration_min'] == pytest.approx(8.0)
|
||||
assert station['navigation']['waze']
|
||||
assert out['detour_prep']['available'] is True
|
||||
assert out['routing']['provider'] == 'osrm'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Ordonnanceur : cadences propres à chaque source, fenêtres, supervision, résilience."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import collector
|
||||
@@ -8,91 +7,80 @@ 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",
|
||||
}
|
||||
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"
|
||||
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"])))
|
||||
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
|
||||
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"
|
||||
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"
|
||||
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")
|
||||
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")
|
||||
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"]
|
||||
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"]
|
||||
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,6 +1,5 @@
|
||||
"""Reconstruction du marché : la médiane ne doit pas basculer quand seules 3 stations déclarent."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
from datetime import timedelta
|
||||
|
||||
import series
|
||||
import storage
|
||||
@@ -9,80 +8,70 @@ LAT, LON = 44.7737872, -0.5595029
|
||||
|
||||
|
||||
def days_ago(n):
|
||||
return (date.today() - timedelta(days=n)).isoformat()
|
||||
"""Même horloge que ``series`` (Paris) : un test ne doit pas dépendre du fuseau de la VM."""
|
||||
return (storage.datetime.now(storage.PARIS).date() - timedelta(days=n)).isoformat()
|
||||
|
||||
|
||||
def declare(store, station_id, fuel, day, price, lat=LAT, lon=LON):
|
||||
store.save_archive_observations(
|
||||
[
|
||||
dict(
|
||||
station_id=station_id,
|
||||
fuel=fuel,
|
||||
day=day,
|
||||
price=price,
|
||||
declared_at=f"{day}T09:00:00",
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
)
|
||||
],
|
||||
"archive:test",
|
||||
)
|
||||
[dict(station_id=station_id, fuel=fuel, day=day, price=price,
|
||||
declared_at=f'{day}T09:00:00', lat=lat, lon=lon)], 'archive:test')
|
||||
|
||||
|
||||
def test_median_uses_the_last_declared_price_not_only_today_s_changes(store):
|
||||
"""30 stations à 1,90 € et 3 changements à 1,95 € : la médiane reste 1,90 €."""
|
||||
for index in range(30):
|
||||
declare(store, f"stable{index}", "Gazole", days_ago(10), 1.90)
|
||||
declare(store, f'stable{index}', 'Gazole', days_ago(10), 1.90)
|
||||
for index in range(3):
|
||||
declare(store, f"stable{index}", "Gazole", days_ago(0), 1.95)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15)
|
||||
today = reconstructed["days"][-1]
|
||||
assert len(today["active"]) == 30, "une seule entrée active par station"
|
||||
assert today["declared_today"] == 3, "seules 3 stations ont déclaré aujourd’hui"
|
||||
assert today["median"] == 1.90, "la médiane du marché ne doit pas devenir 1,95 €"
|
||||
journal = store.price_journal("Gazole", days_ago(1), days_ago(0))
|
||||
naive = sorted(row["price"] for row in journal)
|
||||
assert naive[len(naive) // 2] == 1.95, "calcul naïf (lignes du jour) : 1,95 € — c’est le piège"
|
||||
declare(store, f'stable{index}', 'Gazole', days_ago(0), 1.95)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15)
|
||||
today = reconstructed['days'][-1]
|
||||
assert len(today['active']) == 30, 'une seule entrée active par station'
|
||||
assert today['declared_today'] == 3, 'seules 3 stations ont déclaré aujourd’hui'
|
||||
assert today['median'] == 1.90, 'la médiane du marché ne doit pas devenir 1,95 €'
|
||||
journal = store.price_journal('Gazole', days_ago(1), days_ago(0))
|
||||
naive = sorted(row['price'] for row in journal)
|
||||
assert naive[len(naive) // 2] == 1.95, 'calcul naïf (lignes du jour) : 1,95 € — c’est le piège'
|
||||
|
||||
|
||||
def test_a_price_stays_active_until_the_next_declaration(store):
|
||||
declare(store, "a", "Gazole", days_ago(5), 2.00)
|
||||
declare(store, "b", "Gazole", days_ago(5), 2.10)
|
||||
declare(store, "c", "Gazole", days_ago(5), 2.20)
|
||||
declare(store, "a", "Gazole", days_ago(1), 2.50)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15)
|
||||
by_day = {item["day"]: item for item in reconstructed["days"]}
|
||||
assert by_day[days_ago(3)]["median"] == 2.10, "a est encore à 2,00 € avant sa nouvelle déclaration"
|
||||
assert by_day[days_ago(0)]["median"] == 2.20, "après la déclaration de a à 2,50 €"
|
||||
declare(store, 'a', 'Gazole', days_ago(5), 2.00)
|
||||
declare(store, 'b', 'Gazole', days_ago(5), 2.10)
|
||||
declare(store, 'c', 'Gazole', days_ago(5), 2.20)
|
||||
declare(store, 'a', 'Gazole', days_ago(1), 2.50)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15)
|
||||
by_day = {item['day']: item for item in reconstructed['days']}
|
||||
assert by_day[days_ago(3)]['median'] == 2.10, 'a est encore à 2,00 € avant sa nouvelle déclaration'
|
||||
assert by_day[days_ago(0)]['median'] == 2.20, 'après la déclaration de a à 2,50 €'
|
||||
|
||||
|
||||
def test_stations_that_stopped_declaring_are_dropped(store):
|
||||
declare(store, "muette", "Gazole", days_ago(45), 1.50)
|
||||
declare(store, "actives1", "Gazole", days_ago(1), 2.00)
|
||||
declare(store, "actives2", "Gazole", days_ago(1), 2.20)
|
||||
declare(store, "actives3", "Gazole", days_ago(1), 2.10)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15, max_stale_days=30)
|
||||
today = reconstructed["days"][-1]
|
||||
assert {item["station_id"] for item in today["active"]} == {"actives1", "actives2", "actives3"}
|
||||
assert today["median"] == 2.10
|
||||
assert reconstructed["stale_dropped"] > 0
|
||||
permissive = series.active_series(LAT, LON, 15, "Gazole", days=15, max_stale_days=90)
|
||||
assert permissive["days"][-1]["stations"] == 4, "un seuil plus large la conserve"
|
||||
declare(store, 'muette', 'Gazole', days_ago(45), 1.50)
|
||||
declare(store, 'actives1', 'Gazole', days_ago(1), 2.00)
|
||||
declare(store, 'actives2', 'Gazole', days_ago(1), 2.20)
|
||||
declare(store, 'actives3', 'Gazole', days_ago(1), 2.10)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15, max_stale_days=30)
|
||||
today = reconstructed['days'][-1]
|
||||
assert {item['station_id'] for item in today['active']} == {'actives1', 'actives2', 'actives3'}
|
||||
assert today['median'] == 2.10
|
||||
assert reconstructed['stale_dropped'] > 0
|
||||
permissive = series.active_series(LAT, LON, 15, 'Gazole', days=15, max_stale_days=90)
|
||||
assert permissive['days'][-1]['stations'] == 4, 'un seuil plus large la conserve'
|
||||
|
||||
|
||||
def test_matched_panel_ignores_opening_stations(store):
|
||||
"""Six stations qui ouvrent à 1,00 € font chuter le niveau, pas l'indice comparable."""
|
||||
for name in ("a", "b", "c"):
|
||||
declare(store, name, "Gazole", days_ago(7), 2.00)
|
||||
declare(store, name, "Gazole", days_ago(0), 2.00)
|
||||
for name in ('a', 'b', 'c'):
|
||||
declare(store, name, 'Gazole', days_ago(7), 2.00)
|
||||
declare(store, name, 'Gazole', days_ago(0), 2.00)
|
||||
for index in range(6):
|
||||
declare(store, f"nouvelle{index}", "Gazole", days_ago(0), 1.00)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15)
|
||||
declare(store, f'nouvelle{index}', 'Gazole', days_ago(0), 1.00)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15)
|
||||
matched = series.matched_variation(reconstructed, horizon=7, min_pairs=3)
|
||||
entry = [item for item in matched if item["day"] == days_ago(7)][0]
|
||||
assert entry["matched_stations"] == 3, "seules les stations présentes aux deux dates"
|
||||
assert entry["change_pct"] == 0.0, "aucune variation réelle : l’ouverture ne compte pas"
|
||||
levels = {item["day"]: item["median"] for item in series.median_series(reconstructed)}
|
||||
entry = [item for item in matched if item['day'] == days_ago(7)][0]
|
||||
assert entry['matched_stations'] == 3, 'seules les stations présentes aux deux dates'
|
||||
assert entry['change_pct'] == 0.0, 'aucune variation réelle : l’ouverture ne compte pas'
|
||||
levels = {item['day']: item['median'] for item in series.median_series(reconstructed)}
|
||||
# Le niveau du marché, lui, bouge : six stations pas chères ont ouvert. C'est pourquoi les
|
||||
# variations utilisées par le modèle reposent sur le panel comparable, pas sur ce niveau.
|
||||
assert levels[days_ago(0)] == 1.00
|
||||
@@ -90,58 +79,55 @@ def test_matched_panel_ignores_opening_stations(store):
|
||||
|
||||
def test_matched_panel_detects_a_real_move(store):
|
||||
for index, (before, after) in enumerate(((2.00, 2.20), (2.00, 2.20), (2.00, 1.80))):
|
||||
declare(store, f"station{index}", "Gazole", days_ago(7), before)
|
||||
declare(store, f"station{index}", "Gazole", days_ago(0), after)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15)
|
||||
entry = [
|
||||
item
|
||||
for item in series.matched_variation(reconstructed, horizon=7, min_pairs=3)
|
||||
if item["day"] == days_ago(7)
|
||||
][0]
|
||||
assert entry["comparable"] is True
|
||||
assert entry["change_pct"] == 10.0, "médiane des rapports : +10 %"
|
||||
declare(store, f'station{index}', 'Gazole', days_ago(7), before)
|
||||
declare(store, f'station{index}', 'Gazole', days_ago(0), after)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15)
|
||||
entry = [item for item in series.matched_variation(reconstructed, horizon=7, min_pairs=3)
|
||||
if item['day'] == days_ago(7)][0]
|
||||
assert entry['comparable'] is True
|
||||
assert entry['change_pct'] == 10.0, 'médiane des rapports : +10 %'
|
||||
|
||||
|
||||
def test_matched_panel_refuses_a_thin_sample(store):
|
||||
declare(store, "only", "Gazole", days_ago(7), 2.00)
|
||||
declare(store, "only", "Gazole", days_ago(0), 2.20)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15)
|
||||
declare(store, 'only', 'Gazole', days_ago(7), 2.00)
|
||||
declare(store, 'only', 'Gazole', days_ago(0), 2.20)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15)
|
||||
entry = series.matched_variation(reconstructed, horizon=7, min_pairs=3)[0]
|
||||
assert entry["comparable"] is False
|
||||
assert entry["change_pct"] is None
|
||||
assert entry['comparable'] is False
|
||||
assert entry['change_pct'] is None
|
||||
|
||||
|
||||
def test_reconstructed_series_is_what_the_percentiles_use(store):
|
||||
"""Le percentile doit porter sur la série reconstruite, pas sur les seules lignes du jour."""
|
||||
for index in range(10):
|
||||
declare(store, f"stable{index}", "Gazole", days_ago(20), 1.90)
|
||||
declare(store, f'stable{index}', 'Gazole', days_ago(20), 1.90)
|
||||
for offset in range(19, 0, -1):
|
||||
declare(store, f"stable{offset % 10}", "Gazole", days_ago(offset), 1.95)
|
||||
declare(store, f'stable{offset % 10}', 'Gazole', days_ago(offset), 1.95)
|
||||
for index in range(2):
|
||||
declare(store, f"stable{index}", "Gazole", days_ago(0), 2.20)
|
||||
position = storage.historical_position(LAT, LON, 15, "Gazole", windows=(30,))
|
||||
assert position["current"] == 1.95, "médiane reconstruite, pas les 2,20 € du jour"
|
||||
assert position["windows"]["30"]["percentile"] is not None
|
||||
assert "aucune interpolation" in position["basis"]
|
||||
assert position["reconstruction"]["max_stale_days"] == series.MAX_STALE_DAYS
|
||||
declare(store, f'stable{index}', 'Gazole', days_ago(0), 2.20)
|
||||
position = storage.historical_position(LAT, LON, 15, 'Gazole', windows=(30,))
|
||||
assert position['current'] == 1.95, 'médiane reconstruite, pas les 2,20 € du jour'
|
||||
assert position['windows']['30']['percentile'] is not None
|
||||
assert 'aucune interpolation' in position['basis']
|
||||
assert position['reconstruction']['max_stale_days'] == series.MAX_STALE_DAYS
|
||||
|
||||
|
||||
def test_targets_are_built_on_the_matched_panel(store):
|
||||
for index in range(4):
|
||||
declare(store, f"station{index}", "Gazole", days_ago(20), 2.00)
|
||||
declare(store, f"station{index}", "Gazole", days_ago(13), 2.10)
|
||||
declare(store, "nouvelle", "Gazole", days_ago(13), 1.00)
|
||||
out = series.targets(LAT, LON, 15, "Gazole", horizons=(7,), days=30)
|
||||
entries = {item["day"]: item for item in out[7]}
|
||||
assert entries[days_ago(20)]["change_pct"] == 5.0
|
||||
assert entries[days_ago(20)]["matched_stations"] == 4
|
||||
declare(store, f'station{index}', 'Gazole', days_ago(20), 2.00)
|
||||
declare(store, f'station{index}', 'Gazole', days_ago(13), 2.10)
|
||||
declare(store, 'nouvelle', 'Gazole', days_ago(13), 1.00)
|
||||
out = series.targets(LAT, LON, 15, 'Gazole', horizons=(7,), days=30)
|
||||
entries = {item['day']: item for item in out[7]}
|
||||
assert entries[days_ago(20)]['change_pct'] == 5.0
|
||||
assert entries[days_ago(20)]['matched_stations'] == 4
|
||||
|
||||
|
||||
def test_freshness_report_summarises_the_reconstruction(store):
|
||||
for index in range(5):
|
||||
declare(store, f"station{index}", "Gazole", days_ago(1), 2.00)
|
||||
reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15)
|
||||
declare(store, f'station{index}', 'Gazole', days_ago(1), 2.00)
|
||||
reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15)
|
||||
report = series.freshness_report(reconstructed)
|
||||
assert report["days"] == 16
|
||||
assert report["median_stations"] == 5
|
||||
assert report["share_declaring"] is not None
|
||||
assert report['days'] == 16
|
||||
assert report['median_stations'] == 5
|
||||
assert report['share_declaring'] is not None
|
||||
|
||||
@@ -2,72 +2,28 @@
|
||||
|
||||
|
||||
def test_sync_fills_missing_station_names(store):
|
||||
assert hasattr(store, "sync_station_names"), "Backfill des noms absent"
|
||||
assert hasattr(store, 'sync_station_names'), 'Backfill des noms absent'
|
||||
from datetime import datetime, timezone
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
store.record_observations(
|
||||
[
|
||||
{
|
||||
"id": "X1",
|
||||
"lat": 44.77,
|
||||
"lon": -0.55,
|
||||
"prices": {"Gazole": 1.9},
|
||||
"updates": {"Gazole": now.isoformat()},
|
||||
}
|
||||
],
|
||||
now,
|
||||
)
|
||||
assert store.history(44.77, -0.55, 5, "Gazole", now)["stations_series"][0]["name"] == "Station X1"
|
||||
filled = store.sync_station_names(
|
||||
[
|
||||
{
|
||||
"id": "X1",
|
||||
"name": "12 RUE DES VIGNES",
|
||||
"city": "Villenave",
|
||||
"road": "",
|
||||
"lat": 44.77,
|
||||
"lon": -0.55,
|
||||
},
|
||||
{
|
||||
"id": "X2",
|
||||
"name": "AUTRE STATION",
|
||||
"city": "Ailleurs",
|
||||
"road": "autoroute",
|
||||
"lat": 44.80,
|
||||
"lon": -0.60,
|
||||
},
|
||||
],
|
||||
now,
|
||||
)
|
||||
assert filled == 1, "seules les stations observées doivent être complétées"
|
||||
entry = store.history(44.77, -0.55, 5, "Gazole", now)["stations_series"][0]
|
||||
assert entry["name"] == "12 RUE DES VIGNES"
|
||||
assert entry["city"] == "Villenave"
|
||||
store.record_observations([{'id': 'X1', 'lat': 44.77, 'lon': -0.55,
|
||||
'prices': {'Gazole': 1.9}, 'updates': {'Gazole': now.isoformat()}}], now)
|
||||
assert store.history(44.77, -0.55, 5, 'Gazole', now)['stations_series'][0]['name'] == 'Station X1'
|
||||
filled = store.sync_station_names([
|
||||
{'id': 'X1', 'name': '12 RUE DES VIGNES', 'city': 'Villenave', 'road': '', 'lat': 44.77, 'lon': -0.55},
|
||||
{'id': 'X2', 'name': 'AUTRE STATION', 'city': 'Ailleurs', 'road': 'autoroute', 'lat': 44.80, 'lon': -0.60},
|
||||
], now)
|
||||
assert filled == 1, 'seules les stations observées doivent être complétées'
|
||||
entry = store.history(44.77, -0.55, 5, 'Gazole', now)['stations_series'][0]
|
||||
assert entry['name'] == '12 RUE DES VIGNES'
|
||||
assert entry['city'] == 'Villenave'
|
||||
# Un second passage ne reécrit rien.
|
||||
assert (
|
||||
store.sync_station_names(
|
||||
[{"id": "X1", "name": "AUTRE NOM", "city": "Villenave", "road": "", "lat": 44.77, "lon": -0.55}],
|
||||
now,
|
||||
)
|
||||
== 0
|
||||
)
|
||||
assert store.sync_station_names([{'id': 'X1', 'name': 'AUTRE NOM', 'city': 'Villenave', 'road': '',
|
||||
'lat': 44.77, 'lon': -0.55}], now) == 0
|
||||
|
||||
|
||||
def test_sync_ignores_unknown_and_malformed_rows(store):
|
||||
from datetime import datetime, timezone
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
store.record_observations(
|
||||
[
|
||||
{
|
||||
"id": "Y1",
|
||||
"lat": 44.7,
|
||||
"lon": -0.5,
|
||||
"prices": {"Gazole": 1.9},
|
||||
"updates": {"Gazole": now.isoformat()},
|
||||
}
|
||||
],
|
||||
now,
|
||||
)
|
||||
assert store.sync_station_names([{"name": "SANS ID"}, {"id": "Y1", "name": ""}], now) == 0
|
||||
store.record_observations([{'id': 'Y1', 'lat': 44.7, 'lon': -0.5,
|
||||
'prices': {'Gazole': 1.9}, 'updates': {'Gazole': now.isoformat()}}], now)
|
||||
assert store.sync_station_names([{'name': 'SANS ID'}, {'id': 'Y1', 'name': ''}], now) == 0
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Synthèse amont : pression, facteurs en langage courant, « En clair » et prudence."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
@@ -11,7 +10,7 @@ import synthesis
|
||||
|
||||
|
||||
def seed(series, unit, rows):
|
||||
return storage.save_upstream(series, rows, unit, "test")
|
||||
return storage.save_upstream(series, rows, unit, 'test')
|
||||
|
||||
|
||||
def days_ago(n):
|
||||
@@ -19,159 +18,88 @@ def days_ago(n):
|
||||
|
||||
|
||||
def test_factors_report_unknown_without_data(store):
|
||||
built = synthesis.build("Gazole")
|
||||
assert len(built["factors"]) == 6
|
||||
assert built["pressure"] == "INCERTAINE"
|
||||
assert built["confidence"] is None
|
||||
assert all(factor["arrow"] == "?" for factor in built["factors"])
|
||||
assert "pas assez de données" in built["plain"]
|
||||
assert "pas encore" in built["plain"] and "prévision" in built["disclaimer"]
|
||||
built = synthesis.build('Gazole')
|
||||
assert len(built['factors']) == 6
|
||||
assert built['pressure'] == 'INCERTAINE'
|
||||
assert built['confidence'] is None
|
||||
assert all(factor['arrow'] == '?' for factor in built['factors'])
|
||||
assert 'pas assez de données' in built['plain']
|
||||
assert 'pas encore' in built['plain'] and 'prévision' in built['disclaimer']
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_evenements_factor_weighs_confidence_and_expiry(store):
|
||||
base = dict(
|
||||
topic="ormuz",
|
||||
event_type="chokepoint",
|
||||
magnitude="forte",
|
||||
fuels=["gazole"],
|
||||
zone="Ormuz",
|
||||
horizon_days=10,
|
||||
observed_at=days_ago(1),
|
||||
published_at=days_ago(1),
|
||||
source_url="https://exemple.fr/a",
|
||||
extracted_by="test",
|
||||
)
|
||||
storage.save_news_event(
|
||||
dict(
|
||||
base,
|
||||
url_hash="h1",
|
||||
direction="hausse",
|
||||
confidence=0.9,
|
||||
valid_from=days_ago(1),
|
||||
valid_until=days_ago(-5),
|
||||
)
|
||||
)
|
||||
storage.save_news_event(
|
||||
dict(
|
||||
base,
|
||||
url_hash="h2",
|
||||
direction="baisse",
|
||||
confidence=0.2,
|
||||
valid_from=days_ago(1),
|
||||
valid_until=days_ago(-5),
|
||||
)
|
||||
)
|
||||
base = dict(topic='ormuz', event_type='chokepoint', magnitude='forte', fuels=['gazole'],
|
||||
zone='Ormuz', horizon_days=10, observed_at=days_ago(1), published_at=days_ago(1),
|
||||
source_url='https://exemple.fr/a', extracted_by='test')
|
||||
storage.save_news_event(dict(base, url_hash='h1', direction='hausse', confidence=0.9,
|
||||
valid_from=days_ago(1), valid_until=days_ago(-5)))
|
||||
storage.save_news_event(dict(base, url_hash='h2', direction='baisse', confidence=0.2,
|
||||
valid_from=days_ago(1), valid_until=days_ago(-5)))
|
||||
factor = synthesis.factor_evenements()
|
||||
assert factor["direction"] == synthesis.UP
|
||||
assert factor["count"] == 2 and factor["confidence_used"] == pytest.approx(1.1)
|
||||
assert factor['direction'] == synthesis.UP
|
||||
assert factor['count'] == 2 and factor['confidence_used'] == pytest.approx(1.1)
|
||||
# Un événement expiré ne doit plus peser.
|
||||
storage.save_news_event(
|
||||
dict(
|
||||
base,
|
||||
url_hash="h3",
|
||||
direction="baisse",
|
||||
confidence=1.0,
|
||||
valid_from=days_ago(20),
|
||||
valid_until=days_ago(5),
|
||||
)
|
||||
)
|
||||
assert synthesis.factor_evenements()["direction"] == synthesis.UP
|
||||
storage.save_news_event(dict(base, url_hash='h3', direction='baisse', confidence=1.0,
|
||||
valid_from=days_ago(20), valid_until=days_ago(5)))
|
||||
assert synthesis.factor_evenements()['direction'] == synthesis.UP
|
||||
|
||||
|
||||
def test_pressure_aggregates_weights_and_confidence(store):
|
||||
# Cotation quotidienne fraîche : le brut n'accepte plus une série mensuelle comme cours du jour.
|
||||
seed(
|
||||
"brent_eur_daily",
|
||||
"EUR/baril",
|
||||
[dict(day=days_ago(off), value=80.0 + (5 - off) * 2.4) for off in range(5, 0, -1)],
|
||||
)
|
||||
seed(
|
||||
"dgec_margin_eur_per_tonne",
|
||||
"EUR/tonne",
|
||||
[dict(day=days_ago(40), value=200.0), dict(day=days_ago(2), value=260.0)],
|
||||
)
|
||||
built = synthesis.build("Gazole")
|
||||
assert built["pressure"] == "HAUSSE"
|
||||
assert built["confidence"] is not None and 0 < built["confidence"] <= 0.8
|
||||
assert built["known_factors"] >= 2
|
||||
up = [factor["label"] for factor in built["factors"] if factor["direction"] == "up"]
|
||||
assert "Pétrole brut" in up
|
||||
assert "montent" in built["plain"] and "pèse le plus" in built["plain"]
|
||||
assert "jamais comme une prévision validée" in built["plain"]
|
||||
assert "délai de transmission" in built["plain"]
|
||||
seed('brent_eur_daily', 'EUR/baril',
|
||||
[dict(day=days_ago(off), value=80.0 + (5 - off) * 2.4) for off in range(5, 0, -1)])
|
||||
seed('dgec_margin_eur_per_tonne', 'EUR/tonne', [dict(day=days_ago(40), value=200.0),
|
||||
dict(day=days_ago(2), value=260.0)])
|
||||
built = synthesis.build('Gazole')
|
||||
assert built['pressure'] == 'HAUSSE'
|
||||
assert built['confidence'] is not None and 0 < built['confidence'] <= 0.8
|
||||
assert built['known_factors'] >= 2
|
||||
up = [factor['label'] for factor in built['factors'] if factor['direction'] == 'up']
|
||||
assert 'Pétrole brut' in up
|
||||
assert 'montent' in built['plain'] and 'pèse le plus' in built['plain']
|
||||
assert 'jamais comme une prévision validée' in built['plain']
|
||||
assert 'délai de transmission' in built['plain']
|
||||
|
||||
|
||||
def test_prefilter_rejects_non_fuel_articles_and_duplicates():
|
||||
keep, dropped = news.prefilter(
|
||||
[
|
||||
dict(
|
||||
hash="a",
|
||||
title="Le détroit d’Ormuz perturbe les livraisons de pétrole brut",
|
||||
summary="Les pétroliers ralentissent.",
|
||||
),
|
||||
dict(hash="b", title="Recette de gâteau au chocolat", summary="Sucre et farine."),
|
||||
dict(
|
||||
hash="c",
|
||||
title="Le détroit d’Ormuz perturbe les livraisons de pétrole brut",
|
||||
summary="Doublon du même flux.",
|
||||
),
|
||||
dict(hash="d", title="Nouvelle taxe carburant", summary="Le gazole et l’essence concernés."),
|
||||
]
|
||||
)
|
||||
assert [article["hash"] for article in keep] == ["a", "d"]
|
||||
reasons = {article["hash"]: reason for article, reason in dropped}
|
||||
assert "carburant" in reasons["b"]
|
||||
assert "déjà vu" in reasons["c"]
|
||||
keep, dropped = news.prefilter([
|
||||
dict(hash='a', title='Le détroit d’Ormuz perturbe les livraisons de pétrole brut',
|
||||
summary='Les pétroliers ralentissent.'),
|
||||
dict(hash='b', title='Recette de gâteau au chocolat', summary='Sucre et farine.'),
|
||||
dict(hash='c', title='Le détroit d’Ormuz perturbe les livraisons de pétrole brut',
|
||||
summary='Doublon du même flux.'),
|
||||
dict(hash='d', title='Nouvelle taxe carburant', summary='Le gazole et l’essence concernés.'),
|
||||
])
|
||||
assert [article['hash'] for article in keep] == ['a', 'd']
|
||||
reasons = {article['hash']: reason for article, reason in dropped}
|
||||
assert 'carburant' in reasons['b']
|
||||
assert 'déjà vu' in reasons['c']
|
||||
|
||||
|
||||
def test_prefilter_promotions_needs_brand_and_fuel_words():
|
||||
keep, dropped = promotions.prefilter(
|
||||
[
|
||||
dict(
|
||||
hash="p1",
|
||||
title="Carburant à prix coûtant chez E.Leclerc ce week-end",
|
||||
summary="Le gazole au prix coûtant samedi.",
|
||||
),
|
||||
dict(hash="p2", title="E.Leclerc ouvre un nouveau magasin", summary="Ouverture lundi."),
|
||||
]
|
||||
)
|
||||
assert [article["hash"] for article in keep] == ["p1"]
|
||||
assert dropped[0][1], "une raison d’écartement est toujours fournie"
|
||||
keep, dropped = promotions.prefilter([
|
||||
dict(hash='p1', title='Carburant à prix coûtant chez E.Leclerc ce week-end',
|
||||
summary='Le gazole au prix coûtant samedi.'),
|
||||
dict(hash='p2', title='E.Leclerc ouvre un nouveau magasin', summary='Ouverture lundi.'),
|
||||
])
|
||||
assert [article['hash'] for article in keep] == ['p1']
|
||||
assert dropped[0][1], 'une raison d’écartement est toujours fournie'
|
||||
|
||||
|
||||
def test_queue_metrics_expose_backlog_age_and_durations(store):
|
||||
storage.save_articles(
|
||||
[
|
||||
dict(
|
||||
hash="a",
|
||||
url="https://exemple.fr/a",
|
||||
title="Ormuz",
|
||||
source="Test",
|
||||
published_at=days_ago(3),
|
||||
observed_at=days_ago(3),
|
||||
)
|
||||
],
|
||||
"geo",
|
||||
)
|
||||
storage.save_articles(
|
||||
[
|
||||
dict(
|
||||
hash="b",
|
||||
url="https://exemple.fr/b",
|
||||
title="Suez",
|
||||
source="Test",
|
||||
published_at=days_ago(1),
|
||||
observed_at=days_ago(1),
|
||||
)
|
||||
],
|
||||
"geo",
|
||||
)
|
||||
storage.mark_skipped(["b"], "préfiltrage automatique")
|
||||
storage.record_llm_run("x", "ormuz", "gemma4:12b", 40.0, ok=True)
|
||||
storage.record_llm_run("y", "ormuz", "gemma4:12b", 60.0, ok=False, detail="TimeoutError")
|
||||
storage.save_articles([dict(hash='a', url='https://exemple.fr/a', title='Ormuz',
|
||||
source='Test', published_at=days_ago(3), observed_at=days_ago(3))], 'geo')
|
||||
storage.save_articles([dict(hash='b', url='https://exemple.fr/b', title='Suez',
|
||||
source='Test', published_at=days_ago(1), observed_at=days_ago(1))], 'geo')
|
||||
storage.mark_skipped(['b'], 'préfiltrage automatique')
|
||||
storage.record_llm_run('x', 'ormuz', 'gemma4:12b', 40.0, ok=True)
|
||||
storage.record_llm_run('y', 'ormuz', 'gemma4:12b', 60.0, ok=False, detail='TimeoutError')
|
||||
queue = storage.llm_queue()
|
||||
assert queue["pending"] == 1 and queue["skipped"] == 1 and queue["total"] == 2
|
||||
assert queue["oldest_pending_at"] and queue["oldest_pending_age_hours"] is not None
|
||||
assert queue["analysed_24h_avg_seconds"] == pytest.approx(50.0)
|
||||
assert queue["analysed_24h_failures"] == 1
|
||||
assert queue["by_model"][0]["model"] == "gemma4:12b"
|
||||
assert queue['pending'] == 1 and queue['skipped'] == 1 and queue['total'] == 2
|
||||
assert queue['oldest_pending_at'] and queue['oldest_pending_age_hours'] is not None
|
||||
assert queue['analysed_24h_avg_seconds'] == pytest.approx(50.0)
|
||||
assert queue['analysed_24h_failures'] == 1
|
||||
assert queue['by_model'][0]['model'] == 'gemma4:12b'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
@@ -23,139 +22,89 @@ 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():
|
||||
@@ -164,11 +113,7 @@ 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}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Historisation des séries amont et orchestration de la collecte amont."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import collector
|
||||
@@ -7,91 +6,72 @@ 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]
|
||||
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") == []
|
||||
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")
|
||||
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
|
||||
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")
|
||||
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
|
||||
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)])
|
||||
]
|
||||
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")
|
||||
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
|
||||
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
|
||||
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")
|
||||
raise OSError('hors ligne')
|
||||
|
||||
out = collector.collect_upstream(force=True, sources={"broken": broken})
|
||||
assert out["status"] == "error"
|
||||
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):
|
||||
out = collector.collect(lambda: [], force=True)
|
||||
assert out["status"] == "no_favorites"
|
||||
assert "upstream" in out
|
||||
assert out['status'] == 'no_favorites'
|
||||
assert 'upstream' in out
|
||||
|
||||
@@ -1,302 +1,235 @@
|
||||
"""Banc de validation : aucune fuite, métriques exigées, et verdict économique."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
import validation
|
||||
|
||||
VEHICLE = dict(
|
||||
name="Fictif", fuel="E10", consumption=6.0, tank_liters=45.0, min_range_km=80.0, monthly_km=1000.0
|
||||
)
|
||||
VEHICLE = dict(name='Fictif', fuel='E10', consumption=6.0, tank_liters=45.0,
|
||||
min_range_km=80.0, monthly_km=1000.0)
|
||||
|
||||
|
||||
def series(prices, step_days=1, start_day=1):
|
||||
origin = date(2026, 1, start_day)
|
||||
return [
|
||||
dict(day=(origin + timedelta(days=index * step_days)).isoformat(), price=price)
|
||||
for index, price in enumerate(prices)
|
||||
]
|
||||
return [dict(day=(origin + timedelta(days=index * step_days)).isoformat(), price=price)
|
||||
for index, price in enumerate(prices)]
|
||||
|
||||
|
||||
def prediction(
|
||||
day, horizon=7, predicted=None, actual=None, reference=None, confidence=0.8, trained_until=None
|
||||
):
|
||||
return dict(
|
||||
day=day,
|
||||
horizon=horizon,
|
||||
predicted_change=predicted,
|
||||
actual_change=actual,
|
||||
predicted_price=(reference or 0) + (predicted or 0),
|
||||
actual_price=(reference or 0) + (actual or 0),
|
||||
last_known_price=reference,
|
||||
confidence=confidence,
|
||||
trained_until=trained_until or day,
|
||||
)
|
||||
def prediction(day, horizon=7, predicted=None, actual=None, reference=None, confidence=0.8,
|
||||
trained_until=None):
|
||||
return dict(day=day, horizon=horizon, predicted_change=predicted, actual_change=actual,
|
||||
predicted_price=(reference or 0) + (predicted or 0), actual_price=(reference or 0) + (actual or 0),
|
||||
last_known_price=reference, confidence=confidence,
|
||||
trained_until=trained_until or day)
|
||||
|
||||
|
||||
def test_chronological_split_never_trains_on_the_future():
|
||||
samples = [dict(day=f"2026-01-{day:02d}") for day in range(1, 11)]
|
||||
samples = [dict(day=f'2026-01-{day:02d}') for day in range(1, 11)]
|
||||
train, test = validation.split_chronologically(samples, ratio=0.6)
|
||||
assert len(train) == 6 and len(test) == 4
|
||||
assert max(item["day"] for item in train) < min(item["day"] for item in test)
|
||||
assert max(item['day'] for item in train) < min(item['day'] for item in test)
|
||||
|
||||
|
||||
def test_leakage_is_refused_outright():
|
||||
leaky = [prediction("2026-03-01", trained_until="2026-03-05")]
|
||||
leaky = [prediction('2026-03-01', trained_until='2026-03-05')]
|
||||
with pytest.raises(ValueError) as error:
|
||||
validation.assert_no_leakage(leaky)
|
||||
assert "fuite de données" in str(error.value)
|
||||
validation.assert_no_leakage([prediction("2026-03-05", trained_until="2026-03-01")])
|
||||
assert 'fuite de données' in str(error.value)
|
||||
validation.assert_no_leakage([prediction('2026-03-05', trained_until='2026-03-01')])
|
||||
|
||||
|
||||
def test_perfect_model_beats_the_naive_rule():
|
||||
predictions = [
|
||||
prediction(f"2026-0{month}-15", predicted=delta, actual=delta, reference=2.0)
|
||||
for month in (1, 2)
|
||||
for delta in (0.05, -0.03, 0.02)
|
||||
]
|
||||
predictions = [prediction(f'2026-0{month}-15', predicted=delta, actual=delta, reference=2.0)
|
||||
for month in (1, 2) for delta in (0.05, -0.03, 0.02)]
|
||||
metrics = validation.evaluate(predictions, horizon=7)
|
||||
assert metrics["count"] == 6
|
||||
assert metrics["mae"] == 0
|
||||
assert metrics["skill_vs_naive"] == 1.0
|
||||
assert metrics["direction"]["accuracy"] == 1.0
|
||||
assert metrics['count'] == 6
|
||||
assert metrics['mae'] == 0
|
||||
assert metrics['skill_vs_naive'] == 1.0
|
||||
assert metrics['direction']['accuracy'] == 1.0
|
||||
|
||||
|
||||
def test_a_useless_model_scores_no_better_than_the_naive_rule():
|
||||
predictions = [
|
||||
prediction(f"2026-01-{day:02d}", predicted=0.01, actual=-0.02, reference=2.0, confidence=0.9)
|
||||
for day in range(1, 11)
|
||||
]
|
||||
predictions = [prediction(f'2026-01-{day:02d}', predicted=0.01, actual=-0.02, reference=2.0,
|
||||
confidence=0.9) for day in range(1, 11)]
|
||||
metrics = validation.evaluate(predictions, horizon=7)
|
||||
assert metrics["skill_vs_naive"] <= 0.1, "aucun progrès sur la règle « prix identique »"
|
||||
assert metrics["direction"]["accuracy"] == 0.0
|
||||
assert metrics['skill_vs_naive'] <= 0.1, 'aucun progrès sur la règle « prix identique »'
|
||||
assert metrics['direction']['accuracy'] == 0.0
|
||||
|
||||
|
||||
def test_direction_accuracy_counts_only_real_moves():
|
||||
predictions = [
|
||||
prediction("2026-01-01", predicted=0.05, actual=0.04, reference=2.0),
|
||||
prediction("2026-01-02", predicted=-0.05, actual=0.04, reference=2.0),
|
||||
prediction("2026-01-03", predicted=0.0, actual=0.04, reference=2.0),
|
||||
prediction('2026-01-01', predicted=0.05, actual=0.04, reference=2.0),
|
||||
prediction('2026-01-02', predicted=-0.05, actual=0.04, reference=2.0),
|
||||
prediction('2026-01-03', predicted=0.0, actual=0.04, reference=2.0),
|
||||
]
|
||||
scored = validation.direction_accuracy(predictions)
|
||||
assert scored["count"] == 2, "un « stable » annoncé n’est pas compté comme un sens juste"
|
||||
assert scored["accuracy"] == 0.5
|
||||
assert scored["flat_predicted"] == 1
|
||||
assert scored['count'] == 2, 'un « stable » annoncé n’est pas compté comme un sens juste'
|
||||
assert scored['accuracy'] == 0.5
|
||||
assert scored['flat_predicted'] == 1
|
||||
|
||||
|
||||
def test_confidence_calibration_penalises_overconfidence():
|
||||
"""Confiance annoncée contre réussite réelle : une surconfiance doit coûter cher."""
|
||||
honest, confident = [], []
|
||||
for day in range(1, 11):
|
||||
sign = 1 if day % 2 else -1 # une fois sur deux le sens est faux
|
||||
sign = 1 if day % 2 else -1 # une fois sur deux le sens est faux
|
||||
hit = dict(predicted=0.02, actual=0.02 * sign, reference=2.0)
|
||||
honest.append(prediction(f"2026-01-{day:02d}", confidence=0.55, **hit))
|
||||
confident.append(prediction(f"2026-01-{day:02d}", confidence=0.95, **hit))
|
||||
assert (
|
||||
validation.confidence_calibration(honest)["calibration_quality"]
|
||||
> validation.confidence_calibration(confident)["calibration_quality"]
|
||||
)
|
||||
assert validation.confidence_calibration([])["expected_calibration_error"] is None
|
||||
honest.append(prediction(f'2026-01-{day:02d}', confidence=0.55, **hit))
|
||||
confident.append(prediction(f'2026-01-{day:02d}', confidence=0.95, **hit))
|
||||
assert (validation.confidence_calibration(honest)['calibration_quality'] >
|
||||
validation.confidence_calibration(confident)['calibration_quality'])
|
||||
assert validation.confidence_calibration([])['expected_calibration_error'] is None
|
||||
|
||||
|
||||
def test_every_horizon_is_measured_separately():
|
||||
predictions = []
|
||||
for horizon in validation.HORIZONS:
|
||||
for day in range(1, 6):
|
||||
predictions.append(
|
||||
prediction(
|
||||
f"2026-01-{day:02d}",
|
||||
horizon=horizon,
|
||||
predicted=0.03 * horizon / 10,
|
||||
actual=0.02,
|
||||
reference=2.0,
|
||||
)
|
||||
)
|
||||
predictions.append(prediction(f'2026-01-{day:02d}', horizon=horizon,
|
||||
predicted=0.03 * horizon / 10, actual=0.02, reference=2.0))
|
||||
metrics = validation.evaluate_all_horizons(predictions)
|
||||
assert set(metrics) == {str(horizon) for horizon in validation.HORIZONS}
|
||||
assert metrics["21"]["count"] == 5
|
||||
assert metrics['21']['count'] == 5
|
||||
|
||||
|
||||
def test_naive_strategy_refuels_only_when_needed():
|
||||
prices = series([2.00] * 40)
|
||||
result = validation.simulate(prices, VEHICLE, strategy="naive")
|
||||
assert result["refuels"] >= 1
|
||||
assert result["cost_eur"] > 0
|
||||
assert result["cost_per_liter"] == pytest.approx(2.0, abs=0.01)
|
||||
result = validation.simulate(prices, VEHICLE, strategy='naive')
|
||||
assert result['refuels'] >= 1
|
||||
assert result['cost_eur'] > 0
|
||||
assert result['cost_per_liter'] == pytest.approx(2.0, abs=0.01)
|
||||
|
||||
|
||||
def test_advisor_strategy_can_wait_for_a_falling_price():
|
||||
"""Prix qui baisse : attendre coûte moins cher que remplir au début."""
|
||||
prices = series([2.00] * 5 + [1.80] * 20 + [2.00] * 15)
|
||||
forecasts = {point["day"]: dict(direction="down") for point in prices[:6]}
|
||||
forecasts = {point['day']: dict(direction='down') for point in prices[:6]}
|
||||
comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts)
|
||||
assert comparison["advisor"]["cost_eur"] <= comparison["naive"]["cost_eur"]
|
||||
assert comparison['advisor']['cost_eur'] <= comparison['naive']['cost_eur']
|
||||
|
||||
|
||||
def test_strategy_comparison_reports_cost_refuels_and_detour():
|
||||
prices = series([1.95] * 30)
|
||||
forecasts = {point["day"]: dict(direction="up") for point in prices}
|
||||
comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts, detour_km_per_stop=4.0)
|
||||
assert {"naive", "advisor", "value", "comfort"} <= set(comparison)
|
||||
for side in (comparison["naive"], comparison["advisor"]):
|
||||
assert {"cost_eur", "refuels", "detour_km", "litres"} <= set(side)
|
||||
assert comparison["advisor"]["detour_km"] == 4.0 * comparison["advisor"]["refuels"]
|
||||
forecasts = {point['day']: dict(direction='up') for point in prices}
|
||||
comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts,
|
||||
detour_km_per_stop=4.0)
|
||||
assert {'naive', 'advisor', 'value', 'comfort'} <= set(comparison)
|
||||
for side in (comparison['naive'], comparison['advisor']):
|
||||
assert {'cost_eur', 'refuels', 'detour_km', 'litres'} <= set(side)
|
||||
assert comparison['advisor']['detour_km'] == 4.0 * comparison['advisor']['refuels']
|
||||
|
||||
|
||||
def _metrics(count=500, accuracy=0.62, calibration=0.9, skill=0.05):
|
||||
return {
|
||||
str(validation.DEFAULT_HORIZON): dict(
|
||||
count=count,
|
||||
direction=dict(accuracy=accuracy),
|
||||
calibration=dict(calibration_quality=calibration),
|
||||
skill_vs_naive=skill,
|
||||
)
|
||||
}
|
||||
return {str(validation.DEFAULT_HORIZON): dict(
|
||||
count=count, direction=dict(accuracy=accuracy),
|
||||
calibration=dict(calibration_quality=calibration), skill_vs_naive=skill)}
|
||||
|
||||
|
||||
def _economics(
|
||||
naive_cost=100.0, advisor_cost=100.0, naive_refuels=10, advisor_refuels=10, penalty=1.5, refuel_days=None
|
||||
):
|
||||
days = refuel_days or [
|
||||
(date(2026, 1, 1) + timedelta(days=index * 3)).isoformat() for index in range(advisor_refuels)
|
||||
]
|
||||
naive = dict(
|
||||
cost_eur=naive_cost,
|
||||
refuels=naive_refuels,
|
||||
detour_km=0.0,
|
||||
median_interval_days=9.0,
|
||||
min_interval_days=3.0,
|
||||
refuels_per_month=naive_refuels / 3,
|
||||
)
|
||||
advisor = dict(
|
||||
cost_eur=advisor_cost,
|
||||
refuels=advisor_refuels,
|
||||
detour_km=8.0,
|
||||
refuel_days=days,
|
||||
median_interval_days=9.0 if advisor_refuels < 2 else 3.0,
|
||||
min_interval_days=3.0 if advisor_refuels < 2 else 3.0,
|
||||
refuels_per_month=advisor_refuels / 3,
|
||||
)
|
||||
def _economics(naive_cost=100.0, advisor_cost=100.0, naive_refuels=10, advisor_refuels=10,
|
||||
penalty=1.5, refuel_days=None):
|
||||
days = refuel_days or [(date(2026, 1, 1) + timedelta(days=index * 3)).isoformat()
|
||||
for index in range(advisor_refuels)]
|
||||
naive = dict(cost_eur=naive_cost, refuels=naive_refuels, detour_km=0.0,
|
||||
median_interval_days=9.0, min_interval_days=3.0,
|
||||
refuels_per_month=naive_refuels / 3)
|
||||
advisor = dict(cost_eur=advisor_cost, refuels=advisor_refuels, detour_km=8.0,
|
||||
refuel_days=days,
|
||||
median_interval_days=9.0 if advisor_refuels < 2 else 3.0,
|
||||
min_interval_days=3.0 if advisor_refuels < 2 else 3.0,
|
||||
refuels_per_month=advisor_refuels / 3)
|
||||
value = validation.net_value(naive, advisor, penalty)
|
||||
advisor.update(
|
||||
saving_eur=value["fuel_saving_eur"],
|
||||
net_saving_eur=value["net_saving_eur"],
|
||||
penalty_eur=value["penalty_eur"],
|
||||
cost_ratio=advisor_cost / naive_cost if naive_cost else None,
|
||||
)
|
||||
return dict(
|
||||
naive=naive,
|
||||
advisor=advisor,
|
||||
value=value,
|
||||
comfort=validation.comfort_check(advisor),
|
||||
penalty_per_extra_refuel=penalty,
|
||||
)
|
||||
advisor.update(saving_eur=value['fuel_saving_eur'], net_saving_eur=value['net_saving_eur'],
|
||||
penalty_eur=value['penalty_eur'],
|
||||
cost_ratio=advisor_cost / naive_cost if naive_cost else None)
|
||||
return dict(naive=naive, advisor=advisor, value=value,
|
||||
comfort=validation.comfort_check(advisor), penalty_per_extra_refuel=penalty)
|
||||
|
||||
|
||||
def test_verdict_refuses_a_model_that_saves_nothing():
|
||||
verdict = validation.verdict(_metrics(), _economics(100.0, 100.0))
|
||||
assert verdict["passed"] is False
|
||||
assert any("gain net simulé" in failure for failure in verdict["failures"])
|
||||
assert verdict['passed'] is False
|
||||
assert any('gain net simulé' in failure for failure in verdict['failures'])
|
||||
|
||||
|
||||
def test_one_extra_refuel_is_fine_if_it_pays_for_itself():
|
||||
"""Un passage supplémentaire sur trois mois est acceptable s'il économise réellement."""
|
||||
verdict = validation.verdict(
|
||||
_metrics(),
|
||||
_economics(naive_cost=120.0, advisor_cost=99.0, naive_refuels=10, advisor_refuels=11, penalty=1.5),
|
||||
)
|
||||
assert verdict["passed"] is True, verdict["failures"]
|
||||
assert verdict["net_saving_eur"] == pytest.approx(19.5, abs=0.1)
|
||||
verdict = validation.verdict(_metrics(),
|
||||
_economics(naive_cost=120.0, advisor_cost=99.0,
|
||||
naive_refuels=10, advisor_refuels=11, penalty=1.5))
|
||||
assert verdict['passed'] is True, verdict['failures']
|
||||
assert verdict['net_saving_eur'] == pytest.approx(19.5, abs=0.1)
|
||||
|
||||
|
||||
def test_extra_refuels_that_do_not_pay_are_refused():
|
||||
verdict = validation.verdict(
|
||||
_metrics(),
|
||||
_economics(naive_cost=100.0, advisor_cost=96.0, naive_refuels=10, advisor_refuels=13, penalty=2.5),
|
||||
)
|
||||
assert verdict["passed"] is False
|
||||
assert any("passage(s) supplémentaire(s)" in failure for failure in verdict["failures"])
|
||||
verdict = validation.verdict(_metrics(),
|
||||
_economics(naive_cost=100.0, advisor_cost=96.0,
|
||||
naive_refuels=10, advisor_refuels=13, penalty=2.5))
|
||||
assert verdict['passed'] is False
|
||||
assert any('passage(s) supplémentaire(s)' in failure for failure in verdict['failures'])
|
||||
|
||||
|
||||
def test_comfort_blocks_daily_refuelling_patterns():
|
||||
"""Gagner de l'argent en ravitaillant tous les jours n'est pas un conseil acceptable."""
|
||||
economics = _economics(
|
||||
naive_cost=120.0,
|
||||
advisor_cost=90.0,
|
||||
naive_refuels=6,
|
||||
advisor_refuels=8,
|
||||
penalty=1.0,
|
||||
refuel_days=[
|
||||
"2026-01-01",
|
||||
"2026-01-02",
|
||||
"2026-01-03",
|
||||
"2026-01-04",
|
||||
"2026-01-20",
|
||||
"2026-01-21",
|
||||
"2026-02-01",
|
||||
"2026-02-02",
|
||||
],
|
||||
)
|
||||
economics = _economics(naive_cost=120.0, advisor_cost=90.0, naive_refuels=6,
|
||||
advisor_refuels=8, penalty=1.0,
|
||||
refuel_days=['2026-01-01', '2026-01-02', '2026-01-03', '2026-01-04',
|
||||
'2026-01-20', '2026-01-21', '2026-02-01', '2026-02-02'])
|
||||
verdict = validation.verdict(_metrics(), economics)
|
||||
assert verdict["passed"] is False
|
||||
assert any("confort" in failure for failure in verdict["failures"])
|
||||
assert verdict['passed'] is False
|
||||
assert any('confort' in failure for failure in verdict['failures'])
|
||||
|
||||
|
||||
def test_verdict_refuses_a_small_sample_or_a_leaky_score():
|
||||
verdict = validation.verdict(_metrics(count=12, accuracy=0.9, skill=0.2), _economics(100.0, 90.0, 10, 9))
|
||||
assert verdict["passed"] is False
|
||||
assert any("pour conclure" in failure for failure in verdict["failures"])
|
||||
verdict = validation.verdict(_metrics(count=12, accuracy=0.9, skill=0.2),
|
||||
_economics(100.0, 90.0, 10, 9))
|
||||
assert verdict['passed'] is False
|
||||
assert any('pour conclure' in failure for failure in verdict['failures'])
|
||||
|
||||
|
||||
def test_verdict_accepts_a_genuinely_useful_model():
|
||||
verdict = validation.verdict(
|
||||
_metrics(count=800, accuracy=0.64, calibration=0.88, skill=0.12), _economics(100.0, 92.5, 10, 9)
|
||||
)
|
||||
assert verdict["passed"] is True, verdict["failures"]
|
||||
assert verdict["failures"] == []
|
||||
verdict = validation.verdict(_metrics(count=800, accuracy=0.64, calibration=0.88, skill=0.12),
|
||||
_economics(100.0, 92.5, 10, 9))
|
||||
assert verdict['passed'] is True, verdict['failures']
|
||||
assert verdict['failures'] == []
|
||||
|
||||
|
||||
def test_comfort_check_flags_abnormally_short_intervals():
|
||||
simulation = dict(
|
||||
refuels=3,
|
||||
refuel_days=["2026-01-01", "2026-01-02", "2026-01-10"],
|
||||
min_interval_days=1,
|
||||
refuels_per_month=30.0,
|
||||
)
|
||||
simulation = dict(refuels=3, refuel_days=['2026-01-01', '2026-01-02', '2026-01-10'],
|
||||
min_interval_days=1, refuels_per_month=30.0)
|
||||
check = validation.comfort_check(simulation)
|
||||
assert check["comfortable"] is False
|
||||
assert any("1 jour" in problem for problem in check["problems"])
|
||||
ok = validation.comfort_check(dict(refuels=3, refuel_days=[], min_interval_days=9, refuels_per_month=1.0))
|
||||
assert ok["comfortable"] is True
|
||||
assert check['comfortable'] is False
|
||||
assert any('1 jour' in problem for problem in check['problems'])
|
||||
ok = validation.comfort_check(dict(refuels=3, refuel_days=[], min_interval_days=9,
|
||||
refuels_per_month=1.0))
|
||||
assert ok['comfortable'] is True
|
||||
|
||||
|
||||
def test_van_profile_uses_discrete_trips():
|
||||
"""Le van ne consomme pas tous les jours : la simulation suit des trajets."""
|
||||
prices = series([2.00] * 60)
|
||||
van = validation.VEHICLE_PROFILES["van_occasionnel"]
|
||||
result = validation.simulate(prices, van, strategy="naive")
|
||||
assert result["km_per_day"] < 30, "des trajets discrets, pas une moyenne quotidienne"
|
||||
assert result["refuels"] >= 1
|
||||
assert result["refuels"] <= 6, "quatre trajets par mois ne demandent pas un plein par jour"
|
||||
van = validation.VEHICLE_PROFILES['van_occasionnel']
|
||||
result = validation.simulate(prices, van, strategy='naive')
|
||||
assert result['km_per_day'] < 30, 'des trajets discrets, pas une moyenne quotidienne'
|
||||
assert result['refuels'] >= 1
|
||||
assert result['refuels'] <= 6, 'quatre trajets par mois ne demandent pas un plein par jour'
|
||||
|
||||
|
||||
def test_every_requested_profile_is_simulated():
|
||||
prices = series([2.00] * 10, step_days=3, start_day=1)
|
||||
forecasts = {point["day"]: dict(direction="down") for point in prices}
|
||||
forecasts = {point['day']: dict(direction='down') for point in prices}
|
||||
out = validation.validate_profiles(prices, forecasts)
|
||||
assert set(out) == {"petit_rouleur_essence", "gros_rouleur_diesel", "petit_reservoir", "van_occasionnel"}
|
||||
assert set(out) == {'petit_rouleur_essence', 'gros_rouleur_diesel', 'petit_reservoir',
|
||||
'van_occasionnel'}
|
||||
for entry in out.values():
|
||||
assert "value" in entry and "comfort" in entry
|
||||
assert entry["naive"]["cost_eur"] is not None
|
||||
assert 'value' in entry and 'comfort' in entry
|
||||
assert entry['naive']['cost_eur'] is not None
|
||||
|
||||
|
||||
def test_model_quality_is_vehicle_independent():
|
||||
"""Les métriques statistiques ne dépendent pas du véhicule : elles se valident à part."""
|
||||
predictions = [
|
||||
prediction(f"2026-01-{day:02d}", predicted=0.02, actual=0.02, reference=2.0) for day in range(1, 11)
|
||||
]
|
||||
predictions = [prediction(f'2026-01-{day:02d}', predicted=0.02, actual=0.02, reference=2.0)
|
||||
for day in range(1, 11)]
|
||||
first = validation.evaluate(predictions, horizon=7)
|
||||
second = validation.evaluate(predictions, horizon=7)
|
||||
assert first == second
|
||||
assert "vehicle" not in first
|
||||
assert 'vehicle' not in first
|
||||
|
||||
Reference in New Issue
Block a user