192 lines
6.6 KiB
Python
192 lines
6.6 KiB
Python
"""Tests for §4.1 4D replay chunking, out-of-retention unavailable markers, and compute as_of linkage."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
from datetime import UTC, datetime, timedelta
|
|
from types import SimpleNamespace
|
|
|
|
from httpx import ASGITransport, AsyncClient
|
|
import pytest
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.access_gate import require_earth_or_api_access
|
|
from app.core.enums import UserRole
|
|
from app.db.migrations import discover_migrations
|
|
from app.db.session import Base, get_db
|
|
from app.main import app
|
|
from app.models.aircraft import AircraftPosition
|
|
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
|
from app.models.vessel import VesselPosition
|
|
|
|
|
|
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)
|
|
|
|
def add_all(self, instances) -> None:
|
|
self._session.add_all(instances)
|
|
|
|
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 in {"0009", "0010", "0011"}:
|
|
await step.upgrade(shim)
|
|
Base.metadata.create_all(raw_conn, checkfirst=True)
|
|
|
|
@asynccontextmanager
|
|
async def _factory():
|
|
with Session(engine) as session:
|
|
yield _AsyncSQLiteSession(session)
|
|
|
|
return engine, _factory
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_replay_chunk_limit_retention_unavailable_and_compute_as_of() -> None:
|
|
_engine, session_factory = await _make_sqlite_session()
|
|
now = datetime.now(UTC)
|
|
t_mid = now - timedelta(hours=1)
|
|
t_start = now - timedelta(hours=2)
|
|
|
|
async with session_factory() as db:
|
|
db.add_all(
|
|
[
|
|
AircraftPosition(
|
|
icao24="ae0001",
|
|
lat=1.25,
|
|
lon=103.80,
|
|
altitude_m=9500.0,
|
|
ground_speed_ms=220.0,
|
|
track_deg=90.0,
|
|
observed_at=t_start + timedelta(minutes=1),
|
|
),
|
|
AircraftPosition(
|
|
icao24="ae0001",
|
|
lat=1.35,
|
|
lon=103.95,
|
|
altitude_m=9600.0,
|
|
ground_speed_ms=220.0,
|
|
track_deg=85.0,
|
|
observed_at=t_mid,
|
|
),
|
|
VesselPosition(
|
|
mmsi=412000111,
|
|
lat=1.22,
|
|
lon=103.75,
|
|
sog=12.0,
|
|
cog=110.0,
|
|
received_at=t_start + timedelta(minutes=2),
|
|
),
|
|
ComputeConfigurationRevision(
|
|
publish_id="pub-rev-1",
|
|
action="publish",
|
|
content_fingerprint="fp1",
|
|
config_payload={},
|
|
published_at=t_start - timedelta(minutes=30),
|
|
),
|
|
ComputeConfigurationRevision(
|
|
publish_id="pub-rev-2",
|
|
action="publish",
|
|
content_fingerprint="fp2",
|
|
config_payload={},
|
|
published_at=t_mid - timedelta(seconds=30),
|
|
),
|
|
]
|
|
)
|
|
await db.commit()
|
|
|
|
async def _override_db():
|
|
async with session_factory() as session:
|
|
yield session
|
|
|
|
async def _override_read():
|
|
return SimpleNamespace(id=1, username="viewer1", role=UserRole.VIEWER.value)
|
|
|
|
app.dependency_overrides[get_db] = _override_db
|
|
app.dependency_overrides[require_earth_or_api_access("visualization:read")] = _override_read
|
|
|
|
try:
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
r_avail = await client.get("/api/v1/replay/availability")
|
|
assert r_avail.status_code == 200
|
|
avail = r_avail.json()
|
|
assert avail["layers"]["aircraft"]["retention_hours"] == 24
|
|
assert avail["layers"]["vessels"]["retention_hours"] == 24
|
|
|
|
# Reject > 6h span
|
|
r_too_long = await client.get(
|
|
"/api/v1/replay/frames",
|
|
params={
|
|
"start": (now - timedelta(hours=8)).isoformat(),
|
|
"end": now.isoformat(),
|
|
},
|
|
)
|
|
assert r_too_long.status_code == 400
|
|
|
|
# Outside 24h retention -> unavailable marker
|
|
r_old = await client.get(
|
|
"/api/v1/replay/frames",
|
|
params={
|
|
"start": (now - timedelta(hours=36)).isoformat(),
|
|
"end": (now - timedelta(hours=34)).isoformat(),
|
|
"layers": "aircraft,vessels",
|
|
},
|
|
)
|
|
assert r_old.status_code == 200
|
|
old_data = r_old.json()
|
|
assert old_data["layers"]["aircraft"]["status"] == "unavailable"
|
|
assert old_data["layers"]["vessels"]["status"] == "unavailable"
|
|
|
|
# Valid window -> columnar frames + compute_as_of switches at t_mid
|
|
r_ok = await client.get(
|
|
"/api/v1/replay/frames",
|
|
params={
|
|
"start": t_start.isoformat(),
|
|
"end": now.isoformat(),
|
|
"step_sec": 600,
|
|
"layers": "aircraft,vessels,satellites,compute",
|
|
},
|
|
)
|
|
assert r_ok.status_code == 200
|
|
ok = r_ok.json()
|
|
assert ok["layers"]["aircraft"]["status"] == "ok"
|
|
assert ok["compute_as_of"][0]["publish_id"] == "pub-rev-1"
|
|
assert ok["compute_as_of"][-1]["publish_id"] == "pub-rev-2"
|
|
assert ok["layers"]["satellites"]["mode"] == "tle_live_propagation"
|
|
finally:
|
|
app.dependency_overrides.clear()
|