Refonte conseil carburant : favoris, historique quotidien et autonomie
Sépare le choix de la station du moment de ravitailler. Ajoute favoris et véhicules persistants, collecte quotidienne avec relance en cas déchec, historique par panel constant, marge de sécurité par véhicule et saisie systématique de lautonomie restante. Retire le score arbitraire, les appels Ollama et les RSS. Stooq indisponible => tendance inconnue.
This commit is contained in:
9
tests/conftest.py
Normal file
9
tests/conftest.py
Normal file
@@ -0,0 +1,9 @@
|
||||
import pytest
|
||||
|
||||
import storage
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(storage, "DB_PATH", tmp_path / "test.sqlite3")
|
||||
return storage
|
||||
@@ -14,16 +14,50 @@ def test_haversine_paris_close():
|
||||
assert d == 0
|
||||
|
||||
|
||||
def test_advice_uses_best_price(monkeypatch):
|
||||
def test_advice_uses_best_price(monkeypatch, tmp_path):
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import storage
|
||||
|
||||
monkeypatch.setattr(storage, "DB_PATH", tmp_path / "test.sqlite3")
|
||||
rows = [
|
||||
{"id": "1", "name": "A", "address": "rue A", "city": "Paris", "lat": 48.8566, "lon": 2.3522, "prices": {"Gazole": 1.70}, "updates": {"Gazole": "2026-01-01"}},
|
||||
{"id": "2", "name": "B", "address": "rue B", "city": "Paris", "lat": 48.8570, "lon": 2.3530, "prices": {"Gazole": 1.82}, "updates": {"Gazole": "2026-01-01"}},
|
||||
{"id": "3", "name": "C", "address": "rue C", "city": "Paris", "lat": 48.8580, "lon": 2.3540, "prices": {"Gazole": 1.80}, "updates": {"Gazole": "2026-01-01"}},
|
||||
{
|
||||
"id": "1",
|
||||
"name": "A",
|
||||
"address": "rue A",
|
||||
"city": "Paris",
|
||||
"lat": 48.8566,
|
||||
"lon": 2.3522,
|
||||
"prices": {"Gazole": 1.70},
|
||||
"updates": {"Gazole": "2026-01-01"},
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"name": "B",
|
||||
"address": "rue B",
|
||||
"city": "Paris",
|
||||
"lat": 48.8570,
|
||||
"lon": 2.3530,
|
||||
"prices": {"Gazole": 1.82},
|
||||
"updates": {"Gazole": "2026-01-01"},
|
||||
},
|
||||
{
|
||||
"id": "3",
|
||||
"name": "C",
|
||||
"address": "rue C",
|
||||
"city": "Paris",
|
||||
"lat": 48.8580,
|
||||
"lon": 2.3540,
|
||||
"prices": {"Gazole": 1.80},
|
||||
"updates": {"Gazole": "2026-01-01"},
|
||||
},
|
||||
]
|
||||
for row in rows:
|
||||
row["updates"]["Gazole"] = datetime.now(timezone.utc).isoformat()
|
||||
monkeypatch.setattr(fuel_app, "load_fuel_data", lambda: rows)
|
||||
monkeypatch.setattr(fuel_app, "market_signal", lambda: {"summary": "pétrole flat", "trend": "flat", "delta_pct": 0})
|
||||
monkeypatch.setattr(fuel_app, "news_signal", lambda: [])
|
||||
monkeypatch.setattr(fuel_app, "ollama_summary", lambda context: (None, False))
|
||||
monkeypatch.setattr(
|
||||
fuel_app, "market_signal", lambda: {"summary": "pétrole flat", "trend": "flat", "delta_pct": 0}
|
||||
)
|
||||
out = fuel_app.advice(48.8566, 2.3522, "Gazole", 5)
|
||||
assert out["stations"][0]["name"] == "A"
|
||||
assert out["action"] == "buy"
|
||||
assert out["action"] == "compare"
|
||||
|
||||
48
tests/test_collector.py
Normal file
48
tests/test_collector.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import importlib
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from test_history import sample
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def collector(store):
|
||||
assert importlib.util.find_spec("collector"), "Collecteur absent"
|
||||
return importlib.import_module("collector")
|
||||
|
||||
|
||||
def test_collect_overlapping_favorites_once_daily(store, collector):
|
||||
for name in ("Maison", "Travail"):
|
||||
store.save_entity("favorites", dict(name=name, lat=48.8, lon=2.3, radius_km=15))
|
||||
calls = []
|
||||
|
||||
def load():
|
||||
calls.append(1)
|
||||
return [sample(datetime.now(timezone.utc))]
|
||||
|
||||
out = collector.collect(load, lambda: {"trend": "unknown"}, force=True)
|
||||
assert out["status"] == "ok"
|
||||
assert out["count"] == 1
|
||||
assert len(calls) == 1
|
||||
assert collector.collect(load, lambda: {}, force=False)["status"] == "skipped"
|
||||
assert len(calls) == 1
|
||||
with store.connect() as db:
|
||||
assert db.execute("select count(*) from observations").fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_failed_collection_logged_and_retryable(store, collector):
|
||||
store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=15))
|
||||
|
||||
def fail():
|
||||
raise OSError("source inaccessible")
|
||||
|
||||
assert collector.collect(fail, lambda: {}, force=True)["status"] == "error"
|
||||
out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], lambda: {}, force=False)
|
||||
assert out["status"] == "ok"
|
||||
|
||||
|
||||
def test_empty_favorites_does_not_download(store, collector):
|
||||
def forbidden():
|
||||
raise AssertionError("Aucun téléchargement sans favori")
|
||||
|
||||
assert collector.collect(forbidden, forbidden)["status"] == "no_favorites"
|
||||
76
tests/test_decision.py
Normal file
76
tests/test_decision.py
Normal file
@@ -0,0 +1,76 @@
|
||||
import importlib
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def decide():
|
||||
assert importlib.util.find_spec("decision"), "Moteur de conseil absent"
|
||||
return importlib.import_module("decision").recommend
|
||||
|
||||
|
||||
VEHICLE = dict(
|
||||
name="Auto",
|
||||
consumption=6,
|
||||
min_range_km=80,
|
||||
monthly_km=1200,
|
||||
usage="regular",
|
||||
tank_liters=50,
|
||||
fuel="Gazole",
|
||||
)
|
||||
|
||||
|
||||
def test_reserve_overrides_downward_trend(decide):
|
||||
out = decide(VEHICLE, 80, {"trend": "down"})
|
||||
assert out["action"] == "refuel"
|
||||
assert out["usable_km"] == 0
|
||||
assert out["days_left"] == 0
|
||||
|
||||
|
||||
def test_missing_range_is_rejected_and_not_defaulted(decide):
|
||||
with pytest.raises(ValueError):
|
||||
decide(VEHICLE, None, {})
|
||||
with pytest.raises(ValueError):
|
||||
decide(VEHICLE, float("nan"), {})
|
||||
|
||||
|
||||
def test_sufficient_range_is_not_buy_on_unknown_market(decide):
|
||||
out = decide(VEHICLE, 480, {"trend": "unknown"})
|
||||
assert out["action"] == "wait"
|
||||
assert out["days_left"] == 10
|
||||
assert out["usable_km"] == 400
|
||||
assert out["topup_liters"] is None
|
||||
|
||||
|
||||
def test_near_need_proposes_measured_topup(decide):
|
||||
out = decide(VEHICLE, 120, {"trend": "down"})
|
||||
assert out["action"] == "topup"
|
||||
assert out["topup_liters"] == pytest.approx(14.4)
|
||||
|
||||
|
||||
def test_van_no_trip_no_monthly_assumption(decide):
|
||||
out = decide({**VEHICLE, "usage": "occasional"}, 300, {})
|
||||
assert out["action"] == "none"
|
||||
assert out["days_left"] is None
|
||||
assert out["usable_km"] == 220
|
||||
|
||||
|
||||
def test_van_imminent_trip_needs_fuel(decide):
|
||||
trip = dict(date=(date.today() + timedelta(days=1)).isoformat(), km=400)
|
||||
out = decide({**VEHICLE, "usage": "occasional"}, 300, {}, trip)
|
||||
assert out["action"] == "topup"
|
||||
assert out["topup_liters"] == pytest.approx(10.8)
|
||||
assert out["days_left"] is None
|
||||
|
||||
|
||||
def test_trip_over_tank_requires_stops(decide):
|
||||
out = decide({**VEHICLE, "usage": "occasional"}, 100, {}, dict(date=date.today().isoformat(), km=2000))
|
||||
assert out["action"] == "refuel"
|
||||
assert out["topup_liters"] is None
|
||||
assert any("ravitaillement" in x for x in out["reasons"])
|
||||
|
||||
|
||||
def test_no_vehicle_no_timing_claim(decide):
|
||||
out = decide(None, None, {"trend": "up"})
|
||||
assert out["action"] == "compare"
|
||||
47
tests/test_history.py
Normal file
47
tests/test_history.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def sample(day, price=1.8, station="A", age=0):
|
||||
stamp = (day - timedelta(days=age)).isoformat()
|
||||
return {"id": station, "lat": 48.8, "lon": 2.3, "prices": {"Gazole": price}, "updates": {"Gazole": stamp}}
|
||||
|
||||
|
||||
def test_observations_daily_dedup_and_freshness(store):
|
||||
assert hasattr(store, "record_observations"), "Historique absent"
|
||||
day = datetime.now(timezone.utc)
|
||||
row = sample(day)
|
||||
store.record_observations([row, row], day)
|
||||
store.record_observations([row], day)
|
||||
with store.connect() as db:
|
||||
assert db.execute("select count(*) from observations").fetchone()[0] == 1
|
||||
assert store.fresh_price(row["updates"]["Gazole"], day)
|
||||
assert not store.fresh_price(sample(day, age=20)["updates"]["Gazole"], day)
|
||||
|
||||
|
||||
def test_trend_requires_days_and_same_stations(store):
|
||||
assert hasattr(store, "history"), "Tendance absente"
|
||||
today = datetime.now(timezone.utc)
|
||||
store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=10))
|
||||
for age in range(8):
|
||||
day = today - timedelta(days=age)
|
||||
store.record_observations([sample(day, 1.8 + age * 0.01)], day)
|
||||
# Une nouvelle station moins chère ne doit pas simuler une baisse générale.
|
||||
store.record_observations([sample(today, 1.0, "B")], today)
|
||||
h = store.history(48.8, 2.3, 10, "Gazole", today)
|
||||
assert h["trend"] == "down"
|
||||
assert h["delta_per_liter"] == pytest.approx(-0.07)
|
||||
assert h["matched_stations"] == 1
|
||||
assert len(h["series"]) == 8
|
||||
assert h["confidence"] == "limited"
|
||||
assert store.history(0, 0, 10, "Gazole", today)["trend"] == "unknown"
|
||||
|
||||
|
||||
def test_old_reports_do_not_become_new_evidence(store):
|
||||
assert hasattr(store, "history"), "Tendance absente"
|
||||
today = datetime.now(timezone.utc)
|
||||
for age in range(8):
|
||||
day = today - timedelta(days=age)
|
||||
store.record_observations([sample(day, age=30)], day)
|
||||
assert store.history(48.8, 2.3, 10, "Gazole", today)["trend"] == "unknown"
|
||||
104
tests/test_http.py
Normal file
104
tests/test_http.py
Normal file
@@ -0,0 +1,104 @@
|
||||
import http.client
|
||||
import json
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
from test_app import fuel_app as app
|
||||
from test_history import sample
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(store, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(app, "CACHE_DB", tmp_path / "cache.sqlite3")
|
||||
monkeypatch.setattr(app, "DATA_DIR", tmp_path)
|
||||
httpd = app.ThreadingHTTPServer(("127.0.0.1", 0), app.Handler)
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield httpd.server_port
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
thread.join()
|
||||
|
||||
|
||||
def request(port, method, path, body=None, headers=None):
|
||||
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
||||
data = json.dumps(body) if body is not None else None
|
||||
hdrs = {"Content-Type": "application/json", "X-Fuel-Request": "1"}
|
||||
if headers:
|
||||
hdrs.update(headers)
|
||||
conn.request(method, path, body=data, headers=hdrs)
|
||||
res = conn.getresponse()
|
||||
status, raw = res.status, res.read()
|
||||
conn.close()
|
||||
return status, json.loads(raw) if raw.startswith(b"{") else raw.decode()
|
||||
|
||||
|
||||
def test_http_vehicle_crud_and_csrf(server):
|
||||
data = dict(name="Van", fuel="Gazole", consumption=9, min_range_km=80, usage="occasional", monthly_km=0)
|
||||
status, v = request(server, "POST", "/api/vehicles", data)
|
||||
assert status == 201
|
||||
assert request(server, "GET", "/api/vehicles")[1]["items"][0]["id"] == v["id"]
|
||||
assert request(server, "PUT", f"/api/vehicles/{v['id']}", {**data, "name": "Mon van"})[0] == 200
|
||||
assert request(server, "POST", "/api/vehicles", data, {"Origin": "https://evil.example"})[0] == 403
|
||||
assert request(server, "DELETE", f"/api/vehicles/{v['id']}", headers={"Content-Type": ""})[0] == 200
|
||||
assert request(server, "GET", "/api/vehicles")[1]["items"] == []
|
||||
|
||||
|
||||
def test_http_advice_requires_fresh_range(server, store, monkeypatch):
|
||||
vehicle = store.save_entity(
|
||||
"vehicles",
|
||||
dict(name="Auto", fuel="Gazole", consumption=6, min_range_km=80, monthly_km=1200, usage="regular"),
|
||||
)
|
||||
row = sample(datetime.now(timezone.utc))
|
||||
row.update(name="A", city="Paris", address="Rue")
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [row])
|
||||
monkeypatch.setattr(app, "market_signal", lambda: {"trend": "unknown", "summary": "indisponible"})
|
||||
data = dict(lat=48.8, lon=2.3, radius_km=15, vehicle_id=vehicle["id"])
|
||||
assert request(server, "POST", "/api/advice", data)[0] == 400
|
||||
code, out = request(server, "POST", "/api/advice", {**data, "remaining_km": 80})
|
||||
assert code == 200
|
||||
assert out["action"] == "refuel"
|
||||
assert out["ai_used"] is False
|
||||
assert out["stations"][0]["name"] == "A"
|
||||
# L'autonomie n'est jamais stockée dans le profil.
|
||||
assert "remaining_km" not in store.get_entity("vehicles", vehicle["id"])
|
||||
|
||||
|
||||
def test_market_failure_is_unknown(store, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(app, "CACHE_DB", tmp_path / "cache.sqlite3")
|
||||
monkeypatch.setattr(app, "DATA_DIR", tmp_path)
|
||||
|
||||
def fail(*args):
|
||||
raise OSError("maintenance")
|
||||
|
||||
monkeypatch.setattr(app, "fetch_bytes", fail)
|
||||
assert app.market_signal()["trend"] == "unknown"
|
||||
|
||||
|
||||
def test_market_rejects_nd_nan_and_old_quotes(store, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(app, "CACHE_DB", tmp_path / "cache.sqlite3")
|
||||
monkeypatch.setattr(app, "DATA_DIR", tmp_path)
|
||||
for text in (
|
||||
"Symbol,Date,Open,Close\nCL.F,N/D,N/D,N/D",
|
||||
"Symbol,Date,Open,Close\nCL.F,2020-01-01,80,85",
|
||||
f"Symbol,Date,Open,Close\nCL.F,{datetime.now().date()},nan,85",
|
||||
):
|
||||
app.cache_set("market_v2", None)
|
||||
monkeypatch.setattr(app, "fetch_bytes", lambda *args, text=text: text.encode())
|
||||
assert app.market_signal()["trend"] == "unknown"
|
||||
|
||||
|
||||
def test_http_ui_and_validation(server):
|
||||
status, html = request(server, "GET", "/")
|
||||
assert status == 200
|
||||
assert "Autonomie restante" in html
|
||||
assert "Mes favoris" in html
|
||||
assert (
|
||||
request(
|
||||
server, "POST", "/api/favorites", {"name": "X", "lat": float("nan"), "lon": 2, "radius_km": 10}
|
||||
)[0]
|
||||
== 400
|
||||
)
|
||||
assert request(server, "GET", "/api/advice?lat=nan&lon=2")[0] == 400
|
||||
assert request(server, "GET", "/api/status")[0] == 200
|
||||
34
tests/test_store.py
Normal file
34
tests/test_store.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_vehicle_crud_persists_and_validates(store):
|
||||
data = dict(
|
||||
name="Van",
|
||||
fuel="Gazole",
|
||||
consumption=9,
|
||||
min_range_km=80,
|
||||
monthly_km=0,
|
||||
usage="occasional",
|
||||
tank_liters=None,
|
||||
)
|
||||
v = store.save_entity("vehicles", data)
|
||||
assert store.list_entities("vehicles") == [v]
|
||||
assert v["min_range_km"] == 80
|
||||
assert store.save_entity("vehicles", {**data, "name": "Van aménagé"}, v["id"])["name"] == "Van aménagé"
|
||||
with pytest.raises(ValueError):
|
||||
store.save_entity("vehicles", {**data, "consumption": float("nan")})
|
||||
with pytest.raises(ValueError):
|
||||
store.save_entity("vehicles", {**data, "min_range_km": -1})
|
||||
store.delete_entity("vehicles", v["id"])
|
||||
assert store.list_entities("vehicles") == []
|
||||
|
||||
|
||||
def test_favorite_crud_limits_and_overlap(store):
|
||||
f = store.save_entity("favorites", dict(name="Maison", lat=48.8, lon=2.3, radius_km=15))
|
||||
assert store.list_entities("favorites")[0] == f
|
||||
with pytest.raises(ValueError):
|
||||
store.save_entity("favorites", dict(name="X", lat=91, lon=2, radius_km=10))
|
||||
with sqlite3.connect(store.DB_PATH) as db:
|
||||
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
Reference in New Issue
Block a user