Files
Fuel-Advisor/tests/test_quantity.py
root 01dccaaeb2 Combien acheter : quantite conseillee par tranches, confort et seuil economique
Le conseil donne desormais une quantite, calculee de facon deterministe a partir du besoin de deplacement (usage quotidien, autonomie utilisable, marge) et de la sortie validee du modele predictif. Garde-fous : appoint minimum configurable par vehicule pour eviter un passage a la pompe pour 4 L, seuil de gain minimum pour ne pas faire un detour inutile, plafonnement par la capacite du reservoir, et affichage par tranches (25-30 L) plutot qu une fausse precision. Le plein anticipe exige le cumul d un prix historiquement favorable et d une hausse prevue avec confiance suffisante, sans jamais presenter un bon prix comme un plancher certain. Vehicule occasionnel : quantite basee sur le prochain trajet, jamais sur une moyenne mensuelle. Une prevision n est utilisee que si elle bat la regle naive prix identique.
2026-09-12 23:33:15 +02:00

314 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 position(percentile, current=1.62):
return dict(percentile=percentile, current=current, observations=500, days=90)
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, position=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, position=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,
position=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("Quantité limité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, position=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 "15% les plus bas" 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, position=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,
position=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 "faible" 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,
position=position(0.10),
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("bon prix dans l’historique" 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,
position=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,
position=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,
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, 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, position=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, position=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"]