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:
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
|
||||
Reference in New Issue
Block a user