Distances routieres reelles, navigation, synthese amont lisible et file Ollama supervisee

Le rayon porte desormais sur la distance routiere (prefiltre a vol d oiseau, puis itineraire reel via OSRM par defaut et Google Routes API si une cle est fournie). Chaque station affiche distance en voiture, duree, prix, enseigne et deux liens de navigation Google Maps et Waze sur ses coordonnees exactes ; distance et duree sont mises en cache pour le futur cout de detour. La section amont devient une synthese comprehensible (pression, confiance, facteurs en langage courant, paragraphe En clair) avec les donnees techniques repliees. La file Ollama est prefiltree de facon deterministe, mesuree et exposee dans la supervision (articles en attente, age du plus ancien, analyses sur 24 h, duree moyenne, echecs par modele).
This commit is contained in:
root
2026-09-12 23:00:07 +02:00
parent 41ddb98749
commit c0e930df76
13 changed files with 1742 additions and 77 deletions

View File

@@ -9,6 +9,7 @@ import llm
import market
import news
import promotions
import routing
import storage
@@ -19,6 +20,9 @@ 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.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(

180
tests/test_routing.py Normal file
View File

@@ -0,0 +1,180 @@
"""Distances routières : fournisseurs, cache, application du rayon, liens de navigation."""
import json
import pytest
import app
import routing
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"]
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"
def test_provider_google_requires_key_and_parses_matrix(monkeypatch):
monkeypatch.setattr(routing, "GOOGLE_KEY", "")
with pytest.raises(ValueError):
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()
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)}
def test_routes_uses_cache_then_provider(store, monkeypatch):
calls = []
def fake_provider(origin, targets):
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")
origin = (48.85, 2.35)
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
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 store.route_lookup(["|".join(f"{v:.4f}" for v in (*origin, 48.86, 2.30))])
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)])
assert routes == {}
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)
def fake_routes(origin, targets):
distances = {"proche": 1200.0, "loin": 18500.0, "hors": 40000.0}
return (
{
station_id: dict(
distance_km=distances[station_id] / 1000, duration_min=5.0, 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"
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"
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"]
assert stations[0].route_distance_km is 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")
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"

250
tests/test_synthesis.py Normal file
View File

@@ -0,0 +1,250 @@
"""Synthèse amont : pression, facteurs en langage courant, « En clair » et prudence."""
from datetime import date, timedelta
import pytest
import news
import promotions
import storage
import synthesis
def seed(series, unit, rows):
return storage.save_upstream(series, rows, unit, "test")
def days_ago(n):
return (date.today() - timedelta(days=n)).isoformat()
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"]
def test_brut_factor_detects_a_rise_and_a_fall(store):
seed(
"brent_eur_daily",
"EUR/baril",
[
dict(day=days_ago(9), value=80.0),
dict(day=days_ago(3), value=84.0),
dict(day=days_ago(1), value=88.0),
],
)
factor = synthesis.factor_brut()
assert factor["direction"] == synthesis.UP
assert factor["arrow"] == "↑"
assert factor["change_pct"] == pytest.approx(10.0)
assert factor["fresh"] is True
assert factor["observed_at"] == days_ago(1)
seed(
"brent_eur_daily", "EUR/baril", [dict(day=days_ago(8), value=88.0), dict(day=days_ago(1), value=72.0)]
)
fall = synthesis.factor_brut()
assert fall["direction"] == synthesis.DOWN and fall["arrow"] == "↓"
def test_brut_factor_marks_stale_data_and_flat_move(store):
seed(
"brent_eur_daily",
"EUR/baril",
[dict(day=days_ago(18), value=80.0), dict(day=days_ago(12), value=80.4)],
)
factor = synthesis.factor_brut()
assert factor["direction"] == synthesis.FLAT, "variation sous le seuil : peu d’effet"
assert factor["fresh"] is False and factor["age_days"] >= 11
def test_change_factor_inverts_direction(store):
# Un euro plus faible (USD/EUR en hausse) renchérit le baril : pression haussière.
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["direction"] == synthesis.UP
assert factor["change_pct"] > 0
def test_logistique_factor_reads_chokepoint_traffic(store):
rows = []
for index in range(6):
rows.append(
(
"Strait of Hormuz",
dict(
day=days_ago(25 - index * 4),
transit_tankers=40,
transit_total=90,
capacity_tankers=1000,
capacity_total=2000,
),
)
)
rows.append(
(
"Strait of Hormuz",
dict(
day=days_ago(1),
transit_tankers=22,
transit_total=60,
capacity_tankers=600,
capacity_total=1200,
),
)
)
storage.save_chokepoints(rows, "IMF PortWatch")
factor = synthesis.factor_logistique()
assert factor["direction"] == synthesis.UP, "moins de pétroliers : approvisionnement tendu"
assert "Hormuz" in factor["evidence_text"]
assert "PortWatch" in factor["source"]
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),
)
)
factor = synthesis.factor_evenements()
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
def test_pressure_aggregates_weights_and_confidence(store):
seed(
"brent_eur_daily", "EUR/baril", [dict(day=days_ago(9), value=80.0), dict(day=days_ago(1), value=92.0)]
)
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 = [f["label"] for f in built["factors"] if f["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"]
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"
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")
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"