mirror of
https://github.com/BigBodyCobain/Shadowbroker.git
synced 2026-12-05 09:03:39 +01:00
Directions between two places with the incidents, closures and public cameras along the way, in the app (Tools), for AI agents and on the public map. Traffic incidents come from keyless agency feeds (US state DOT work zones, Caltrans, TfL, NDW). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
210 lines
9.1 KiB
Python
210 lines
9.1 KiB
Python
"""Route and traffic report: geometry, picking, and the report with a fake network."""
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
from services import route_report as rr
|
|
|
|
|
|
def _encode(points, precision=6):
|
|
"""Reference polyline encoder, used only to build test input."""
|
|
factor = 10**precision
|
|
out, plat, plon = [], 0, 0
|
|
for lat, lon in points:
|
|
ilat, ilon = round(lat * factor), round(lon * factor)
|
|
for d in (ilat - plat, ilon - plon):
|
|
v = ~(d << 1) if d < 0 else d << 1
|
|
while v >= 0x20:
|
|
out.append(chr((0x20 | (v & 0x1F)) + 63))
|
|
v >>= 5
|
|
out.append(chr(v + 63))
|
|
plat, plon = ilat, ilon
|
|
return "".join(out)
|
|
|
|
|
|
# A straight road due north from Denver, about 100 km long.
|
|
LINE = [(39.70 + i * 0.09, -104.99) for i in range(11)]
|
|
|
|
|
|
class _Res:
|
|
def __init__(self, status, payload):
|
|
self.status_code = status
|
|
self._payload = payload
|
|
|
|
def json(self):
|
|
return self._payload
|
|
|
|
|
|
def _fake_fetch(calls):
|
|
def fetch(url, method="GET", json_data=None, timeout=20):
|
|
calls.append(url)
|
|
if "photon" in url:
|
|
if "Nowhere" in url:
|
|
return _Res(200, {"features": []})
|
|
lat = 39.70 if "Denver" in url else 40.60
|
|
return _Res(200, {"features": [{"geometry": {"coordinates": [-104.99, lat]}, "properties": {"name": "Denver" if lat < 40 else "North End", "state": "Colorado", "country": "United States"}}]})
|
|
if "valhalla" in url:
|
|
return _Res(200, {"trip": {"summary": {"length": 100.1, "time": 3900}, "legs": [{"shape": _encode(LINE), "maneuvers": [{"instruction": "Drive north on Test Road.", "length": 100.1, "street_names": ["Test Road"]}]}]}})
|
|
if "tomtom" in url:
|
|
return _Res(200, {"flowSegmentData": {"currentSpeed": 30, "freeFlowSpeed": 100, "roadClosure": False}})
|
|
return _Res(500, {})
|
|
return fetch
|
|
|
|
|
|
def test_polyline_round_trip():
|
|
assert [tuple(round(v, 6) for v in p) for p in rr.decode_polyline(_encode(LINE))] == [tuple(round(v, 6) for v in p) for p in LINE]
|
|
|
|
|
|
def test_truncated_polyline_is_rejected():
|
|
with pytest.raises(ValueError):
|
|
rr.decode_polyline(_encode(LINE)[:-1])
|
|
|
|
|
|
def test_index_finds_points_near_the_line_and_how_far_along():
|
|
idx = rr.RouteIndex(LINE)
|
|
assert 98 < idx.length_km < 102
|
|
near = idx.locate(40.15, -104.985, 1.0) # ~0.4 km east of the road, half way
|
|
assert near is not None
|
|
assert near[0] < 0.6 and 48 < near[1] < 52
|
|
assert idx.locate(40.15, -104.90, 1.0) is None # ~7.7 km away
|
|
assert idx.locate(45.0, -104.99, 1.0) is None # past the end
|
|
|
|
|
|
def test_items_near_route_sorts_along_and_skips_bad_rows():
|
|
idx = rr.RouteIndex(LINE)
|
|
items = [
|
|
{"id": "far", "lat": 40.0, "lon": -104.5},
|
|
{"id": "late", "lat": 40.50, "lon": -104.99},
|
|
{"id": "early", "lat": 39.75, "lon": -104.991},
|
|
{"id": "bad", "lat": "x", "lon": None},
|
|
"not a dict",
|
|
]
|
|
out = rr.items_near_route(idx, items, 0.6)
|
|
assert [o["id"] for o in out] == ["early", "late"]
|
|
assert out[0]["along_km"] < out[1]["along_km"]
|
|
|
|
|
|
def test_spread_along_picks_evenly():
|
|
items = [{"id": i, "along_km": float(i)} for i in range(100)]
|
|
picked = rr.spread_along(items, 100.0, 4)
|
|
assert [p["id"] for p in picked] == [12, 38, 62, 88] or [p["id"] for p in picked] == [12, 37, 62, 87]
|
|
assert rr.spread_along(items[:3], 100.0, 4) == items[:3]
|
|
assert rr.spread_along(items, 100.0, 0) == []
|
|
|
|
|
|
def test_latlon_text_skips_the_geocoder():
|
|
calls = []
|
|
place = rr.geocode("39.7392, -104.9903", _fake_fetch(calls))
|
|
assert (place["lat"], place["lon"]) == (39.7392, -104.9903)
|
|
assert calls == []
|
|
|
|
|
|
def test_unknown_place_is_a_clear_error():
|
|
with pytest.raises(rr.RouteReportError, match="no place found"):
|
|
rr.geocode("Nowhere at all", _fake_fetch([]))
|
|
|
|
|
|
def test_report_without_tomtom_key(monkeypatch):
|
|
monkeypatch.delenv("TOMTOM_API_KEY", raising=False)
|
|
calls = []
|
|
cams = [{"id": f"c{i}", "source_agency": "Test DOT", "lat": 39.70 + i * 0.05, "lon": -104.991, "media_url": f"https://cams.example/{i}.jpg", "media_type": "image"} for i in range(18)]
|
|
cams.append({"id": "off", "lat": 40.0, "lon": -104.0})
|
|
incs = [{"id": "i1", "lat": 40.30, "lon": -104.993, "type": "crash", "description": "Two-car crash, right lane blocked", "road": "Test Road"}]
|
|
report = rr.build_report("Denver", "North End", cams, incs, fetch=_fake_fetch(calls), max_cameras=5)
|
|
assert report["route"]["engine"] == "valhalla"
|
|
assert report["route"]["distance_km"] == 100.1
|
|
assert report["route"]["duration_min"] == 65.0
|
|
assert report["route"]["steps"][0]["instruction"] == "Drive north on Test Road."
|
|
assert report["cameras"]["near_route"] == 18
|
|
assert len(report["cameras"]["picked"]) == 5
|
|
assert all(c["id"] != "off" for c in report["cameras"]["picked"])
|
|
assert report["incidents"][0]["description"].startswith("Two-car crash")
|
|
assert report["incidents"][0]["on_route"] is True
|
|
assert report["traffic"]["available"] is False
|
|
assert not any("tomtom" in u for u in calls)
|
|
assert "crash" in report["summary"] and "18 public camera" in report["summary"]
|
|
json.dumps(report) # must be JSON-safe
|
|
|
|
|
|
def test_incidents_on_the_route_road_beat_side_street_works():
|
|
steps = [{"instruction": "Take I-10 East", "roads": ["I 10", "I-10 East"], "distance_km": 90.0},
|
|
{"instruction": "Turn onto 4th St", "roads": ["4th Street"], "distance_km": 1.0},
|
|
{"instruction": "Turn onto Main St", "roads": ["Main Street"], "distance_km": 1.0}]
|
|
near = [{"id": f"side{i}", "road": "4TH ST", "along_km": 0.1 * i, "off_route_km": 0.1} for i in range(50)]
|
|
near.append({"id": "hwy", "road": "I-10 EB", "along_km": 80.0, "off_route_km": 0.3})
|
|
near.append({"id": "shut", "road": "Main St", "closure": True, "along_km": 40.0, "off_route_km": 0.35})
|
|
picked = rr.pick_incidents(near, steps, limit=5)
|
|
ids = [p["id"] for p in picked]
|
|
assert "hwy" in ids and "shut" in ids and len(ids) == 5
|
|
assert [p["along_km"] for p in picked] == sorted(p["along_km"] for p in picked)
|
|
assert next(p for p in picked if p["id"] == "hwy")["on_route"] is True
|
|
assert next(p for p in picked if p["id"] == "shut")["on_route"] is True
|
|
# the highway work outranks the side streets, and every kept incident has a rank
|
|
assert next(p for p in picked if p["id"] == "hwy")["rank"] == 2
|
|
assert sorted(p["rank"] for p in picked) == [1, 2, 3, 4, 5]
|
|
|
|
|
|
def test_report_with_tomtom_key_flags_slow_traffic(monkeypatch):
|
|
monkeypatch.setenv("TOMTOM_API_KEY", "test-key")
|
|
report = rr.build_report("Denver", "North End", [], [], fetch=_fake_fetch([]))
|
|
flow = report["traffic"]
|
|
assert flow["available"] is True
|
|
assert flow["slow_points"] == len(flow["samples"]) > 0
|
|
assert "slow or closed" in report["summary"]
|
|
|
|
|
|
def test_falls_back_to_osrm_when_valhalla_fails(monkeypatch):
|
|
monkeypatch.delenv("TOMTOM_API_KEY", raising=False)
|
|
base = _fake_fetch([])
|
|
|
|
def fetch(url, method="GET", json_data=None, timeout=20):
|
|
if "valhalla" in url:
|
|
return _Res(503, {})
|
|
if "project-osrm" in url:
|
|
return _Res(200, {"code": "Ok", "routes": [{"geometry": _encode(LINE), "distance": 100000, "duration": 3600, "legs": [{"steps": [{"name": "Test Road", "distance": 100000, "maneuver": {"type": "depart"}}]}]}]})
|
|
return base(url, method, json_data, timeout)
|
|
|
|
report = rr.build_report("Denver", "North End", [], [], fetch=fetch)
|
|
assert report["route"]["engine"] == "osrm"
|
|
assert report["route"]["distance_km"] == 100.0
|
|
assert report["route"]["steps"][0]["instruction"] == "Depart onto Test Road"
|
|
|
|
|
|
def test_very_long_trips_are_refused():
|
|
with pytest.raises(rr.RouteReportError, match="not supported"):
|
|
rr.build_report("0,0", "60,100", [], [], fetch=_fake_fetch([]))
|
|
|
|
|
|
def test_agent_command_returns_the_report_and_compact_drops_geometry(monkeypatch):
|
|
from services import openclaw_channel
|
|
|
|
fake = {
|
|
"from": {"name": "A"}, "to": {"name": "B"},
|
|
"route": {"distance_km": 1.0, "geometry": [[0, 0], [1, 1]], "steps": []},
|
|
"incidents": [], "cameras": {"near_route": 0, "picked": []}, "traffic": {"available": False}, "summary": "s",
|
|
}
|
|
seen = {}
|
|
|
|
def fake_report(start, dest, cams, traffic):
|
|
seen.update(start=start, dest=dest, cams=cams, traffic=traffic)
|
|
return fake
|
|
|
|
monkeypatch.setattr(rr, "report_from_store", fake_report)
|
|
full = openclaw_channel._dispatch_command("route_report", {"from": "A", "to": "B", "cameras": 99})
|
|
assert full["ok"] is True and full["data"]["route"]["geometry"]
|
|
assert seen == {"start": "A", "dest": "B", "cams": 20, "traffic": True}
|
|
compact = openclaw_channel._dispatch_command("route_report", {"from": "A", "to": "B", "compact": True})
|
|
assert "geometry" not in compact["data"]["route"]
|
|
|
|
|
|
def test_agent_command_reports_errors_plainly(monkeypatch):
|
|
from services import openclaw_channel
|
|
|
|
def boom(*_a):
|
|
raise rr.RouteReportError("no place found for 'x'")
|
|
|
|
monkeypatch.setattr(rr, "report_from_store", boom)
|
|
res = openclaw_channel._dispatch_command("route_report", {"from": "x", "to": "y"})
|
|
assert res == {"ok": False, "detail": "no place found for 'x'"}
|