osint-dashboard/tests/test_geofence.py

844 lines
24 KiB
Python
Raw Permalink Normal View History

"""Geofence hit detection and WS alert routing (no Redis)."""
from __future__ import annotations
import asyncio
import geofence
from geofence import (
matching_geofences,
point_in_geojson,
validate_polygon_geojson,
)
from ws_manager import ConnectionManager
NC_BOX = {
"type": "Polygon",
"coordinates": [[
[-80.0, 35.0],
[-78.0, 35.0],
[-78.0, 36.0],
[-80.0, 36.0],
[-80.0, 35.0],
]],
}
def test_point_inside_polygon_hits():
assert point_in_geojson(-79.0, 35.5, NC_BOX) is True
def test_point_outside_polygon_misses():
assert point_in_geojson(-122.4, 37.7, NC_BOX) is False
def test_validate_rejects_non_polygon():
try:
validate_polygon_geojson({"type": "Point", "coordinates": [-79.0, 35.5]})
assert False, "expected ValueError"
except ValueError:
pass
def test_matching_geofences_only_active_hits():
fences = [
{"id": "a", "name": "NC", "active": True, "geojson": NC_BOX},
{"id": "b", "name": "off", "active": False, "geojson": NC_BOX},
]
hits = matching_geofences(-79.0, 35.5, fences)
assert [h["id"] for h in hits] == ["a"]
assert matching_geofences(-122.4, 37.7, fences) == []
FENCE_ID = "11111111-1111-1111-1111-111111111111"
NC_VIEW = (-80.0, 35.0, -78.0, 36.0)
SF_VIEW = (-123.0, 37.0, -121.0, 38.0)
def _alert_payload(gid=FENCE_ID):
return {
"geofence_id": gid,
"geofence_name": "NC",
"source_kind": "ais",
"entity_id": "366123456",
"lat": 35.5,
"lon": -79.0,
}
def test_geofence_alert_fans_out_only_to_viewport_clients():
mgr = ConnectionManager()
q_nc = mgr.register("nc")
q_sf = mgr.register("sf")
mgr.set_viewport("nc", NC_VIEW)
mgr.set_viewport("sf", SF_VIEW)
async def run():
n = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n == 1
msg = q_nc.get_nowait()
assert msg["type"] == "geofence_alert"
assert msg["payload"]["entity_id"] == "366123456"
assert q_sf.empty()
asyncio.run(run())
def test_off_viewport_watch_receives_geofence_alert():
mgr = ConnectionManager()
q_sf = mgr.register("sf")
mgr.set_viewport("sf", SF_VIEW)
mgr.set_watched_geofences("sf", [FENCE_ID])
async def run():
n = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n == 1
msg = q_sf.get_nowait()
assert msg["type"] == "geofence_alert"
assert msg["payload"]["geofence_id"] == FENCE_ID
asyncio.run(run())
def test_off_viewport_without_watch_does_not_receive_geofence_alert():
mgr = ConnectionManager()
q_sf = mgr.register("sf")
mgr.set_viewport("sf", SF_VIEW)
async def run():
n = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n == 0
assert q_sf.empty()
asyncio.run(run())
def test_on_viewport_receives_geofence_alert_without_watch():
mgr = ConnectionManager()
q_nc = mgr.register("nc")
mgr.set_viewport("nc", NC_VIEW)
async def run():
n = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n == 1
assert q_nc.get_nowait()["type"] == "geofence_alert"
asyncio.run(run())
def test_ais_stays_viewport_only_even_when_watching():
mgr = ConnectionManager()
q_sf = mgr.register("sf")
mgr.set_viewport("sf", SF_VIEW)
mgr.set_watched_geofences("sf", [FENCE_ID])
async def run():
n = await mgr.publish_point("ais", {"id": "366123456"}, lat=35.5, lon=-79.0)
assert n == 0
assert q_sf.empty()
asyncio.run(run())
def test_invalid_watch_uuids_ignored_empty_list_clears():
mgr = ConnectionManager()
q = mgr.register("sf")
mgr.set_viewport("sf", SF_VIEW)
mgr.set_watched_geofences("sf", ["not-a-uuid", FENCE_ID, "also-bad"])
async def run():
n = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n == 1
q.get_nowait()
mgr.set_watched_geofences("sf", [])
n2 = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n2 == 0
assert q.empty()
asyncio.run(run())
def test_unregister_clears_watched_geofences():
mgr = ConnectionManager()
q = mgr.register("sf")
mgr.set_viewport("sf", SF_VIEW)
mgr.set_watched_geofences("sf", [FENCE_ID])
mgr.unregister("sf")
q2 = mgr.register("sf")
mgr.set_viewport("sf", SF_VIEW)
async def run():
n = await mgr.publish_point(
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
)
assert n == 0
assert q2.empty()
asyncio.run(run())
def test_record_and_notify_queries_postgis_when_cache_empty(monkeypatch):
"""FIRMS ingest in the ingester has an empty in-process cache — still ST_Intersects."""
import geofence
geofence._cache.clear()
geofence._recent_hits.clear()
st_called = []
async def fake_st(lon, lat):
st_called.append((lon, lat))
return [{
"id": "11111111-1111-1111-1111-111111111111",
"name": "NC",
"geojson": NC_BOX,
"active": True,
}]
monkeypatch.setattr(geofence, "st_intersects", fake_st)
executed: list = []
class FakeSession:
async def execute(self, stmt, params=None):
executed.append(params or {})
return None
async def commit(self):
executed.append("commit")
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(geofence, "async_session", FakeSession)
async def run():
from ws_manager import manager
q = manager.register("nc")
manager.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
n = await geofence.record_and_notify(
source_kind="firms", entity_id="35.5,-79.0,N",
lat=35.5, lon=-79.0, payload={"satellite": "N"},
)
msg = None if q.empty() else q.get_nowait()
manager.unregister("nc")
return n, msg
n, msg = asyncio.run(run())
assert st_called == [(-79.0, 35.5)]
assert n == 1
assert msg["type"] == "geofence_alert"
assert msg["payload"]["source_kind"] == "firms"
inserts = [p for p in executed if isinstance(p, dict)]
assert inserts and inserts[0]["source_kind"] == "firms"
assert "commit" in executed
def test_list_alerts_sql_filters(monkeypatch):
captured: dict = {}
class FakeResult:
def mappings(self):
return self
def all(self):
return []
class FakeSession:
async def execute(self, stmt, params=None):
captured["sql"] = str(stmt)
captured["params"] = params
return FakeResult()
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(geofence, "async_session", FakeSession)
from datetime import datetime, timezone
since = datetime(2026, 8, 28, tzinfo=timezone.utc)
until = datetime(2026, 8, 29, tzinfo=timezone.utc)
async def run():
return await geofence.list_alerts(
geofence_id=FENCE_ID, since=since, until=until,
source_kind="firms", limit=5,
)
assert asyncio.run(run()) == []
sql = captured["sql"].lower()
assert "geofence_id" in sql
assert "created_at >=" in sql
assert "created_at <=" in sql
assert "source_kind" in sql
assert captured["params"]["geofence_id"] == FENCE_ID
assert captured["params"]["source_kind"] == "firms"
assert captured["params"]["limit"] == 5
def test_alembic_fence_created_index_exists():
from pathlib import Path
text = Path(__file__).resolve().parent.parent.joinpath(
"alembic/versions/011_geofence_alerts_fence.py",
).read_text()
assert "ix_geofence_alerts_fence_created" in text
assert "010_bbox_gist" in text
def test_snapshot_at_404_when_fence_missing(monkeypatch):
geofence._cache.clear()
async def boom():
raise RuntimeError("db down")
monkeypatch.setattr(geofence, "refresh_cache", boom)
async def run():
from datetime import datetime, timezone
return await geofence.snapshot_at(
FENCE_ID, datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc),
)
assert asyncio.run(run()) is None
def test_snapshot_queries_st_intersects(monkeypatch):
geofence._cache[:] = [{
"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True,
}]
sqls: list[str] = []
class FakeResult:
def mappings(self):
return self
def all(self):
return []
class FakeSession:
async def execute(self, stmt, params=None):
sqls.append(str(stmt))
return FakeResult()
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(geofence, "async_session", FakeSession)
async def run():
from datetime import datetime, timezone
return await geofence.snapshot_at(
FENCE_ID, datetime(2026, 8, 28, 12, 4, 30, tzinfo=timezone.utc),
)
body = asyncio.run(run())
assert body["aircraft"] == []
assert body["vessels"] == []
assert body["fires"] == []
blob = "\n".join(sqls).lower()
assert "st_intersects" in blob
assert "aircraft_tracks_1min" in blob
assert "vessel_tracks_1min" in blob
assert "from fires" in blob
def _reset_geofence_state():
geofence._cache.clear()
geofence._recent_hits.clear()
geofence._notified_once.clear()
class _MapResult:
def __init__(self, rows):
self._rows = rows
self.rowcount = 1
self.inserted_primary_key = ["evt-1"]
def mappings(self):
return self
def all(self):
return self._rows
def first(self):
return self._rows[0] if self._rows else None
def _fence_session(inserts, cameras, news, already=None):
"""Fake session: evidence queries return rows; inserts are recorded."""
already_rows = [] if already is None else already
class Sess:
async def execute(self, stmt, params=None):
sql = str(stmt).lower()
if "insert into geofence_alerts" in sql:
inserts.append(params or {})
return _MapResult([])
if "from cameras" in sql:
return _MapResult(cameras)
if "from news_items" in sql and "kind = 'map'" not in sql and "kind = " not in sql:
return _MapResult(news)
if "from geofence_alerts" in sql:
return _MapResult(already_rows)
return _MapResult([])
async def commit(self):
inserts.append("commit")
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
return Sess
def _install_polygon(monkeypatch, inserts, cameras=None, news=None, already=None):
_reset_geofence_state()
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
async def fake_st(lon, lat):
return matching_geofences(lon, lat, [fence])
monkeypatch.setattr(geofence, "st_intersects", fake_st)
if cameras is None:
cameras = [{
"id": "cam-1",
"name": "Dock",
"snapshot_url": "rtsp://agency.example/stream",
}]
if news is None:
news = [{
"headline": "Quake felt",
"url": "https://example.com/q",
"importance": "high",
}]
monkeypatch.setattr(
geofence, "async_session",
lambda: _fence_session(inserts, cameras, news, already)(),
)
return fence
def _alert_rows(inserts):
return [p for p in inserts if isinstance(p, dict)]
def _evidence(row):
import json
return json.loads(row["payload"])["evidence"]
def test_camera_evidence_never_copies_agency_or_rtsp_url():
from geofence import _CAMERAS_INSIDE_SQL, camera_evidence
assert "snapshot_url" not in _CAMERAS_INSIDE_SQL.lower()
row = camera_evidence({
"id": "abc",
"name": "",
"snapshot_url": "rtsp://agency.example/live",
"location_name": "ignored-when-name-set",
})
assert row == {
"id": "abc",
"name": "",
"snapshot_url": "/api/cameras/abc/snapshot",
}
assert "rtsp" not in row["snapshot_url"]
assert not row["snapshot_url"].startswith("http")
def test_evidence_caps_and_empty_arrays():
from datetime import datetime, timezone
from geofence import evidence_pack
now = datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc)
cams = [{"id": f"c{i}", "name": f"n{i}"} for i in range(8)]
news = [
{"headline": f"h{i}", "url": "", "importance": ""} for i in range(6)
]
pack = evidence_pack(FENCE_ID, now, cams, news)
assert len(pack["cameras"]) == 5
assert len(pack["news"]) == 3
empty = evidence_pack(FENCE_ID, now, [], [])
assert empty["cameras"] == []
assert empty["news"] == []
assert empty["snapshot"] == f"/api/geofences/{FENCE_ID}/at?ts=2026-08-28T12:04:00Z"
def test_inside_writes_evidence_outside_writes_nothing(monkeypatch):
"""Polygon fixture: inside → 1 row + evidence; outside → 0. Each new kind."""
import json
from urllib.parse import parse_qs, urlsplit
from tracks import parse_timestamp
for kind, entity in (
("earthquake", "ci1"),
("fire_incident", "IRWIN-1"),
("news", "42"),
):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run(k=kind, eid=entity):
inside = await geofence.record_and_notify(
source_kind=k, entity_id=eid, lat=35.5, lon=-79.0,
payload={"label": "inside"},
)
outside = await geofence.record_and_notify(
source_kind=k, entity_id=eid + "-out", lat=37.7, lon=-122.4,
payload={"label": "outside"},
)
return inside, outside
n_in, n_out = asyncio.run(run())
rows = _alert_rows(inserts)
assert n_out == 0
assert rows and len(rows) == 1, kind
assert rows[0]["source_kind"] == kind
ev = json.loads(rows[0]["payload"])["evidence"]
assert set(ev) == {"cameras", "news", "snapshot"}
assert set(ev["cameras"][0]) == {"id", "name", "snapshot_url"}
assert set(ev["news"][0]) == {"headline", "url", "importance"}
assert ev["cameras"][0]["id"] == "cam-1"
assert ev["cameras"][0]["name"] == "Dock"
assert ev["cameras"][0]["snapshot_url"] == "/api/cameras/cam-1/snapshot"
assert ev["news"][0] == {
"headline": "Quake felt",
"url": "https://example.com/q",
"importance": "high",
}
assert ev["snapshot"].startswith(f"/api/geofences/{FENCE_ID}/at?ts=")
assert "rtsp" not in json.dumps(ev)
assert "http" not in ev["cameras"][0]["snapshot_url"]
qs = parse_qs(urlsplit(ev["snapshot"]).query)
assert "ts" in qs and "timestamp" not in qs
assert parse_timestamp(qs["ts"][0]) is not None
assert n_in == 0 or n_in >= 0 # WS fan-out may be 0 with no clients
def test_firms_hit_omits_evidence(monkeypatch):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run():
return await geofence.record_and_notify(
source_kind="firms", entity_id="35.5,-79.0,N",
lat=35.5, lon=-79.0, payload={"satellite": "N"},
)
asyncio.run(run())
rows = _alert_rows(inserts)
import json
body = json.loads(rows[0]["payload"])
assert "evidence" not in body
assert body["satellite"] == "N"
def test_same_entity_inside_five_minutes_is_one_row(monkeypatch):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run():
a = await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-1",
lat=35.5, lon=-79.0, payload={"label": "Foster"},
)
b = await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-1",
lat=35.5, lon=-79.0, payload={"label": "Foster"},
)
return a, b
asyncio.run(run())
assert len(_alert_rows(inserts)) == 1
def test_skip_existing_does_not_renotify_after_cooldown(monkeypatch):
"""A later poll of the same incident id must not insert again."""
inserts: list = []
already = []
_install_polygon(monkeypatch, inserts, already=already)
async def run():
await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-9",
lat=35.5, lon=-79.0, skip_existing=True,
)
geofence._recent_hits.clear()
geofence._notified_once.clear()
already.append({"one": 1})
await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-9",
lat=35.5, lon=-79.0, skip_existing=True,
)
asyncio.run(run())
assert len(_alert_rows(inserts)) == 1
def test_camera_kind_is_refused(monkeypatch):
inserts: list = []
called = {"st": 0}
_install_polygon(monkeypatch, inserts)
async def fake_st(lon, lat):
called["st"] += 1
return [{"id": FENCE_ID, "name": "NC", "active": True}]
monkeypatch.setattr(geofence, "st_intersects", fake_st)
async def run():
return await geofence.record_and_notify(
source_kind="camera", entity_id="cam-1", lat=35.5, lon=-79.0,
)
assert asyncio.run(run()) == 0
assert called["st"] == 0
assert _alert_rows(inserts) == []
def test_camera_publish_and_insert_do_not_notify(monkeypatch):
import camera_scraper
import ingestor
import run_camera_service
from datetime import datetime, timezone
called = []
async def fake_record(**kwargs):
called.append(kwargs)
return 0
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
class Sess:
async def execute(self, stmt, params=None):
return _MapResult([])
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(camera_scraper, "async_session", lambda: Sess())
async def upsert():
return await camera_scraper.upsert_cameras([{
"source_url": "http://cam.example/snap",
"discovery_source": "test",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"snapshot_url": "rtsp://agency.example/stream",
}])
assert asyncio.run(upsert()) == 1
assert called == []
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
async def ingest_cam():
return await ingestor.ingest_event({
"source_type": "camera",
"title": "Open camera",
"url": "http://cam.example/snap",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
assert asyncio.run(ingest_cam()) == "evt-1"
assert called == []
now = datetime(2026, 8, 28, 12, tzinfo=timezone.utc)
class Pub:
async def publish(self, *a, **k):
return None
class NC:
def jetstream(self):
return Pub()
async def close(self):
return None
class _Nats:
@staticmethod
async def connect(*a, **k):
return NC()
class CamSess:
async def execute(self, stmt, params=None):
return _MapResult([{
"vendor": "x",
"source_url": "http://cam.example/snap",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"discovery_source": "test",
"url_hash": "abc",
"snapshot_url": "rtsp://agency.example/stream",
"device_type": "rtsp",
"first_seen": now,
"last_seen": now,
}])
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(run_camera_service, "nats", _Nats)
monkeypatch.setattr(run_camera_service, "async_session", lambda: CamSess())
async def publish():
return await run_camera_service.publish_new_cameras()
assert asyncio.run(publish()) == 1
assert called == []
assert all(c.get("source_kind") != "camera" for c in called)
def test_fire_poll_inside_notifies_outside_does_not(monkeypatch):
calls = []
async def fake_load(bbox):
assert bbox == "-80.0,35.0,-78.0,36.0"
return [
{
"id": "In Fire", "lat": 35.5, "lon": -79.0, "label": "In Fire",
"extra": {"irwin_id": "IRWIN-IN", "src": "wfigs"},
},
{
"id": "Out Fire", "lat": 37.7, "lon": -122.4, "label": "Out Fire",
"extra": {"irwin_id": "IRWIN-OUT", "src": "wfigs"},
},
]
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr("live_layers.load_fire_incidents", fake_load)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
async def run():
return await geofence.poll_fire_incidents([fence])
assert asyncio.run(run()) == 1
assert len(calls) == 1
assert calls[0]["source_kind"] == "fire_incident"
assert calls[0]["entity_id"] == "IRWIN-IN"
assert calls[0]["skip_existing"] is True
def test_ingest_earthquake_notifies_camera_message_does_not(monkeypatch):
import ingestor
calls = []
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
class Sess:
async def execute(self, stmt, params=None):
return _MapResult([])
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
async def run():
qid = await ingestor.ingest_event({
"source_type": "earthquake",
"title": "M 2.1",
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1",
"location_lat": 35.5,
"location_lon": -79.0,
"raw": {"usgs_id": "ci1"},
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
cid = await ingestor.ingest_event({
"source_type": "camera",
"title": "cam",
"url": "http://cam.example/a",
"location_lat": 35.5,
"location_lon": -79.0,
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
return qid, cid
qid, cid = asyncio.run(run())
assert qid == "evt-1"
assert cid == "evt-1"
assert len(calls) == 1
assert calls[0]["source_kind"] == "earthquake"
assert calls[0]["entity_id"] == "ci1"
assert calls[0]["lat"] == 35.5
assert calls[0]["lon"] == -79.0
def test_news_scan_reads_pins_without_summarizer(monkeypatch):
calls = []
async def fake_rows(sql, params):
assert "news_items" in sql
assert "kind = 'map'" in sql
return [{
"id": "9", "headline": "Bridge", "url": "https://n.example/b",
"importance": "critical", "lat": 35.5, "lon": -79.0,
}]
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr(geofence, "_rows", fake_rows)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
async def run():
return await geofence.scan_news_pins()
assert asyncio.run(run()) == 1
assert calls[0]["source_kind"] == "news"
assert calls[0]["entity_id"] == "9"
assert calls[0]["skip_existing"] is True