Files
planet/backend/tests/test_maritime_intelligence.py
T

127 lines
5.3 KiB
Python

"""Phase 3.4 strategic ports, maritime chokepoints, warship/cable-ship recognition, and baseline tests."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from httpx import ASGITransport, AsyncClient
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from app.db.session import Base, get_db
from app.main import app
from app.models.vessel import VesselCurrentState, VesselPosition
from app.services.maritime_geography import (
compute_chokepoint_vessel_summary,
enrich_vessel_feature_roles,
find_chokepoint_for_point,
load_chokepoints,
load_strategic_ports,
)
from app.services.vessel_types import classify_military_vessel, is_cable_repair_vessel
class _AsyncSQLiteSession:
def __init__(self, session: Session):
self._session = session
def get_bind(self):
return self._session.get_bind()
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()
def test_cited_dictionaries_and_warship_cable_ship_recognition():
chokepoints = load_chokepoints()
ports = load_strategic_ports()
cp_ids = {c["id"] for c in chokepoints}
assert {"malacca_strait", "strait_of_hormuz", "bab_el_mandeb", "suez_canal", "panama_canal", "strait_of_gibraltar", "bosphorus_strait", "taiwan_strait", "korea_strait"}.issubset(cp_ids)
assert all(c.get("source_citation") for c in chokepoints)
assert len(ports) >= 20
assert all(p.get("source_citation") and p.get("port_type") for p in ports)
# Warship classification
role1, src1 = classify_military_vessel(vessel_type=35, name="UNKNOWN VESSEL")
assert role1 == "warship" and "35" in src1
role2, _ = classify_military_vessel(vessel_type=70, name="USS ARLEIGH BURKE")
assert role2 == "destroyer"
role3, _ = classify_military_vessel(vessel_type=0, name="HMS DIAMOND")
assert role3 == "destroyer"
role4, _ = classify_military_vessel(vessel_type=0, name="ROKS SEJONG")
assert role4 == "warship"
role_civ, _ = classify_military_vessel(vessel_type=70, name="COSCO SHIPPING UNIVERSE")
assert role_civ is None
# Cable repair ship classification
is_cs, cs_src = is_cable_repair_vessel(vessel_type=33, name="CS RESOLUTE")
assert is_cs is True and "ICPC" in cs_src
is_cs2, _ = is_cable_repair_vessel(vessel_type=70, name="C/S ORANGE PACIFIC")
assert is_cs2 is True
assert is_cable_repair_vessel(vessel_type=70, name="EVER GIVEN")[0] is False
@pytest.mark.asyncio
async def test_chokepoint_counting_rolling_baseline_api_and_ai_tool():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(bind=engine)
now = datetime.now(UTC)
with Session(engine) as s:
# 2 current vessels in Strait of Hormuz (26.55N, 56.35E), 1 warship
s.add_all(
[
VesselCurrentState(mmsi="999000111", name="USS NIMITZ", vessel_type=35, lat=26.55, lon=56.35, source="aisstream_vessels", observed_at=now - timedelta(minutes=5)),
VesselCurrentState(mmsi="999000222", name="CS RESOLUTE", vessel_type=33, lat=26.50, lon=56.40, source="aisstream_vessels", observed_at=now - timedelta(minutes=5)),
]
)
# 7d history baseline inside Strait of Hormuz: 1 ship on day -2, 1 ship on day -3 -> avg 1.0/day
s.add_all(
[
VesselPosition(mmsi="888000111", lat=26.55, lon=56.35, received_at=now - timedelta(days=2)),
VesselPosition(mmsi="888000222", lat=26.52, lon=56.30, received_at=now - timedelta(days=3)),
]
)
s.commit()
async def _override_db():
with Session(engine) as s:
yield _AsyncSQLiteSession(s)
app.dependency_overrides[get_db] = _override_db
try:
assert find_chokepoint_for_point(26.55, 56.35)["id"] == "strait_of_hormuz"
sample_feat = {
"type": "Feature",
"geometry": {"type": "Point", "coordinates": [56.35, 26.55]},
"properties": {"mmsi": "999000111", "name": "USS NIMITZ", "vessel_type": 35},
}
enrich_vessel_feature_roles(sample_feat)
assert sample_feat["properties"]["is_warship"] is True
assert sample_feat["properties"]["chokepoint_id"] == "strait_of_hormuz"
with Session(engine) as s:
summary = await compute_chokepoint_vessel_summary(_AsyncSQLiteSession(s), now=now)
hormuz = next(c for c in summary if c["id"] == "strait_of_hormuz")
assert hormuz["vessel_count"] == 2
assert hormuz["warship_count"] == 1
assert hormuz["cable_ship_count"] == 1
assert hormuz["baseline_7d_avg"] == 1.0
assert hormuz["delta_vs_7d"] == 1.0
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
resp = await client.get("/api/v1/vessels/maritime-context")
assert resp.status_code == 200
body = resp.json()
assert body["chokepoint_count"] >= 9
assert body["port_count"] >= 20
hormuz_api = next(c for c in body["chokepoints"] if c["id"] == "strait_of_hormuz")
assert hormuz_api["vessel_count"] == 2
finally:
app.dependency_overrides.clear()
engine.dispose()