"""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"