Files
planet/backend/tests/test_gps_jamming.py
T
linkong 1c0066edc6
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.85.0
2026-12-06 22:47:23 +08:00

132 lines
4.1 KiB
Python

"""Phase 2 GPS/GNSS interference H3 parsing, cell generation, and API tests."""
from __future__ import annotations
from contextlib import asynccontextmanager
import h3
from httpx import ASGITransport, AsyncClient
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from app.db.migrations import discover_migrations
from app.db.session import get_db
from app.main import app
from app.models.gps_jamming import GPSJammingCell
from app.services.collectors.gps_jamming import (
classify_jamming_level,
parse_gpsjam_csv,
parse_manifest_latest_date,
)
class _AsyncSQLiteSession:
def __init__(self, session: Session):
self._session = session
def get_bind(self):
return self._session.get_bind()
def add(self, instance) -> None:
self._session.add(instance)
async def execute(self, statement, params=None):
return self._session.execute(statement, params) if params is not None else self._session.execute(statement)
async def commit(self) -> None:
self._session.commit()
class _AsyncConnShim:
def __init__(self, conn):
self._conn = conn
self.dialect = conn.dialect
async def execute(self, stmt, params=None):
return self._conn.execute(stmt, params) if params is not None else self._conn.execute(stmt)
async def _make_sqlite_session():
engine = create_engine("sqlite:///:memory:")
with engine.begin() as raw_conn:
shim = _AsyncConnShim(raw_conn)
for step in discover_migrations():
if step.version == "0008":
await step.upgrade(shim)
@asynccontextmanager
async def _factory():
with Session(engine) as session:
yield _AsyncSQLiteSession(session)
return engine, _factory
def test_gpsjam_manifest_and_h3_cell_parsing():
manifest = "date,url\n2026-12-04,2026-12-04-h3_4.csv\n2026-12-05,2026-12-05-h3_4.csv\n"
assert parse_manifest_latest_date(manifest) == "2026-12-05"
cell_high = h3.latlng_to_cell(35.0, 33.0, 4)
cell_med = h3.latlng_to_cell(54.7, 20.5, 4)
cell_clean = h3.latlng_to_cell(48.8, 2.3, 4)
csv_text = (
"hex,count_good_aircraft,count_bad_aircraft\n"
f"{cell_high},80,25\n"
f"{cell_med},95,5\n"
f"{cell_clean},100,0\n"
)
cells = parse_gpsjam_csv(csv_text, observed_date="2026-12-05")
assert len(cells) == 2
by_hex = {c["h3_index"]: c for c in cells}
assert by_hex[cell_high]["level"] == "high"
assert by_hex[cell_high]["resolution"] == 4
assert len(by_hex[cell_high]["boundary"]) >= 5
assert by_hex[cell_med]["level"] == "medium"
assert classify_jamming_level(0.01) == "low"
@pytest.mark.asyncio
async def test_gps_jamming_snapshot_api():
engine, factory = await _make_sqlite_session()
async def _override_db():
async with factory() as session:
yield session
app.dependency_overrides[get_db] = _override_db
try:
cell_high = h3.latlng_to_cell(35.0, 33.0, 4)
async with factory() as db:
db.add(
GPSJammingCell(
h3_index=cell_high,
observed_date="2026-12-05",
lat=35.0,
lon=33.0,
resolution=4,
level="high",
bad_ratio=0.238,
aircraft_count=105,
boundary=[[lat, lon] for lat, lon in h3.cell_to_boundary(cell_high)],
source="gpsjam_interference",
)
)
await db.commit()
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
resp = await client.get("/api/v1/gps-jamming/snapshot")
assert resp.status_code == 200
data = resp.json()
assert data["date"] == "2026-12-05"
assert data["stats"]["high"] == 1
assert len(data["cells"]) == 1
assert data["cells"][0]["h3_index"] == cell_high
assert "gpsjam.org" in data["attribution"]
finally:
app.dependency_overrides.pop(get_db, None)
engine.dispose()