Les archives annuelles officielles de prix-carburants.gouv.fr sont importees retrospectivement depuis 2007 (20 annees, 354597 lignes sur 117 stations) avec la date declaree par la station, un marqueur d origine, sans ecrasement ni continuite inventee. Le percentile spatial et le percentile historique sont desormais deux indicateurs distincts : seul le second peut declencher un achat anticipe, et son affichage exige une fenetre reellement couverte. Le cout du detour est calcule automatiquement (distance routiere supplementaire x consommation x prix) et deduit du gain, tandis que le seuil de gain net pour un ravitaillement supplementaire reste configurable par vehicule. La quantite de carburant du reservoir est clairement presentee comme une estimation. Le banc de validation impose un backtest chronologique sans fuite, des metriques par horizon avec calibration de la confiance, et une simulation economique naive contre Fuel Advisor ; aucune prevision ne sera branchee avant que les criteres ne soient atteints.
455 lines
15 KiB
Python
455 lines
15 KiB
Python
"""Quantité à acheter : stock optimisé, mais sans absurdité ni fausse précision.
|
||
|
||
Scénarios repris de l'usage réel : appoint minimal pour atteindre une baisse annoncée, plein
|
||
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,
|
||
)
|
||
|
||
|
||
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",
|
||
)
|
||
|
||
|
||
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",
|
||
)
|
||
|
||
|
||
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.",
|
||
)
|
||
|
||
|
||
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",
|
||
)
|
||
|
||
|
||
def test_bands_refuse_false_precision():
|
||
assert quantity.quantity_band(27.43) == (25.0, 30.0)
|
||
assert quantity.quantity_band(12.4) == (12.0, 14.0)
|
||
assert quantity.quantity_band(8.0, minimum=10.0) == (10.0, 12.0)
|
||
|
||
|
||
def test_daily_km_never_assumes_an_average_for_occasional_use():
|
||
assert quantity.daily_km(REGULAR) == pytest.approx(36.1, abs=0.1)
|
||
assert quantity.daily_km(VAN) is None
|
||
|
||
|
||
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
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"]
|
||
)
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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
|
||
|
||
|
||
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"]
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"
|
||
|
||
|
||
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"])
|
||
|
||
|
||
def test_quantity_module_never_calls_a_language_model():
|
||
"""La quantité est calculée, jamais demandée à un modèle de langage.
|
||
|
||
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
|
||
|
||
|
||
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"
|
||
|
||
|
||
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"]
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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"])
|
||
|
||
|
||
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
|
||
|
||
|
||
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"
|
||
|
||
|
||
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"])
|