Files
planet/backend/tests/test_earth_tiles_and_wind.py
T
rayd1o 30b44ec00d
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.84.2
2026-12-05 01:56:03 +08:00

471 lines
17 KiB
Python

"""Tests for Phase 2 managed tile pyramid and Phase 3 NOAA GFS wind field pipelines."""
from __future__ import annotations
import asyncio
import gc
import io
import weakref
from unittest.mock import AsyncMock
import httpx
import numpy as np
from PIL import Image
import pytest
from app.core.datasource_defaults import DEFAULT_DATASOURCES
from app.main import app
from app.models.user import User, UserRole
from app.services import earth_tiles, earth_wind
from app.services.ai.tool_registry import query_wind_posture_tool
from app.services.collectors.earth_tiles import (
CloudHDTilesCollector,
Sentinel2ImageryCollector,
VIIRSDailyImageryCollector,
)
from app.services.collectors.wind_gfs import EarthWindGFSCollector
def _sample_jpg_bytes() -> bytes:
arr = np.full((32, 32, 3), (38, 122, 198), dtype=np.uint8)
img = Image.fromarray(arr, mode="RGB")
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=85)
return buf.getvalue()
class _FakeScalarResult:
def __init__(self, rows=None, scalar=None):
self._rows = list(rows or [])
self._scalar = scalar
def all(self):
return self._rows
def first(self):
return self._rows[0] if self._rows else None
def scalar(self):
return 0
def scalar_one_or_none(self):
return self._scalar
def scalar_one(self):
return self._scalar
class _DummyAsyncDB:
def __init__(self, *, active_sources: dict[str, bool] | None = None):
self.active_sources = dict(active_sources or {})
self.settings: dict[str, dict] = {}
self.added = []
async def execute(self, stmt):
sql = str(stmt)
if "FROM data_sources" in sql:
rows = [
(DEFAULT_DATASOURCES[src]["id"], src, is_active)
for src, is_active in self.active_sources.items()
if src in DEFAULT_DATASOURCES
]
single_src = next(
(src for src in self.active_sources if src in sql),
None,
)
scalar_val = self.active_sources.get(single_src) if single_src else None
return _FakeScalarResult(rows=rows, scalar=scalar_val)
if "FROM system_settings" in sql:
for key in ("earth_basemap", "earth_cloud_map"):
if key in self.settings:
return _FakeScalarResult(scalar=self.settings[key])
return _FakeScalarResult(scalar=None)
return _FakeScalarResult()
def add(self, obj):
self.added.append(obj)
cat = getattr(obj, "category", None)
if cat:
self.settings[cat] = obj
async def delete(self, obj):
cat = getattr(obj, "category", None)
if cat and cat in self.settings:
del self.settings[cat]
async def commit(self):
return None
async def rollback(self):
return None
def get_bind(self):
return None
async def get(self, *_args, **_kwargs):
return None
def test_cloud_hd_tile_routes_across_five_satellites():
# Nighttime / pure IR routes across 5 geostationary satellites (z=7 GIBS clamps to Level6)
url_west_ir, params_west_ir, prov_west_ir = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 2, 7, daytime=False
)
assert prov_west_ir == "gibs" and params_west_ir is None and "GOES-West_ABI_Band13_Clean_Infrared" in url_west_ir
url_east_ir, params_east_ir, prov_east_ir = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 4, 7, daytime=False
)
assert prov_east_ir == "gibs" and params_east_ir is None and "GOES-East_ABI_Band13_Clean_Infrared" in url_east_ir
url_fes_ir, params_fes_ir, prov_fes_ir = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 8, 7, daytime=False
)
assert prov_fes_ir == "eumetview" and params_fes_ir is not None and params_fes_ir["LAYERS"] == "msg_fes:ir108"
assert params_fes_ir["SRS"] == "EPSG:3857"
url_iodc_ir, params_iodc_ir, prov_iodc_ir = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 4, 10, 7, daytime=False
)
assert prov_iodc_ir == "eumetview" and params_iodc_ir is not None and params_iodc_ir["LAYERS"] == "msg_iodc:ir108"
url_hima_ir, params_hima_ir, prov_hima_ir = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 7, 112, 52, daytime=False
)
assert (
prov_hima_ir == "gibs"
and params_hima_ir is None
and "Himawari_AHI_Band13_Clean_Infrared" in url_hima_ir
and "/GoogleMapsCompatible_Level6/6/26/56.png" in url_hima_ir
)
# Daytime 1km/2km visible & GeoColor routes across 5 satellites up to Level 7
url_west_vis, _, prov_west_vis = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 10, 24, daytime=True
)
assert prov_west_vis == "gibs_geocolor" and "GOES-West_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7" in url_west_vis
url_east_vis, _, prov_east_vis = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 18, 24, daytime=True
)
assert prov_east_vis == "gibs_geocolor" and "GOES-East_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7" in url_east_vis
_, params_fes_vis, prov_fes_vis = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 33, 24, daytime=True
)
assert prov_fes_vis == "eumetview_visible" and params_fes_vis["LAYERS"] == "msg_fes:rgb_naturalenhncd"
_, params_iodc_vis, prov_iodc_vis = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 6, 40, 24, daytime=True
)
assert prov_iodc_vis == "eumetview_visible" and params_iodc_vis["LAYERS"] == "msg_iodc:rgb_naturalenhncd"
url_hima_vis, _, prov_hima_vis = earth_tiles._resolve_cloud_hd_request(
earth_tiles.DEFAULT_TILE_TEMPLATES["cloud_hd_tiles"], 7, 108, 52, daytime=True
)
assert (
prov_hima_vis == "gibs_visible"
and "Himawari_AHI_Band3_Red_Visible_1km/default/default/GoogleMapsCompatible_Level7/7/52/108.png" in url_hima_vis
)
def test_alpha5_tle_encoding_and_stale_70char_rebuild():
from types import SimpleNamespace
from app.core.satellite_tle import build_tle_lines_from_elements, format_tle_norad_id
from app.api.v1.visualization import _extract_satellite_record
assert format_tle_norad_id(25544) == "25544"
assert format_tle_norad_id(100001) == "A0001"
assert format_tle_norad_id(100504) == "A0504"
assert format_tle_norad_id(339999) == "Z9999"
l1, l2 = build_tle_lines_from_elements(
norad_cat_id=100504,
epoch="2026-12-03T06:00:00Z",
inclination=70.0,
raan=120.0,
eccentricity=0.00015,
arg_of_perigee=90.0,
mean_anomaly=270.0,
mean_motion=15.3,
)
assert l1 is not None and l2 is not None
assert len(l1) == 69 and len(l2) == 69
assert l1[2:7] == "A0504" and l2[2:7] == "A0504"
# Malformed 70-char stored lines from prior 6-digit NORAD padding must rebuild cleanly
fake_record = SimpleNamespace(
name="STARLINK-38356",
extra_data={
"norad_cat_id": 100504,
"epoch": "2026-12-03T06:00:00Z",
"inclination": 70.0,
"raan": 120.0,
"eccentricity": 0.00015,
"arg_of_perigee": 90.0,
"mean_anomaly": 270.0,
"mean_motion": 15.3,
"tle_line1": "1 100504U 00001A 26337.25000000 .00000000 00000-0 00000-0 0 9990",
"tle_line2": "2 100504 70.0000 120.0000 0001500 90.0000 270.0000 15.30000000000000",
},
)
_, _, fixed_l1, fixed_l2, _, _ = _extract_satellite_record(fake_record)
assert fixed_l1 is not None and fixed_l2 is not None
assert len(fixed_l1) == 69 and len(fixed_l2) == 69
assert fixed_l1[2:7] == "A0504" and fixed_l2[2:7] == "A0504"
assert earth_tiles.BasemapConfig().cloud_hd_tiles_enabled is False
def test_erddap_csv0_wind_parser_and_analytics(tmp_path, monkeypatch):
monkeypatch.setattr(earth_wind, "WIND_DATA_DIR", tmp_path / "wind")
csv_lines = []
# 0..360 lon grid (every 60 deg) x (-30..30 lat)
for lat in (-30.0, 0.0, 30.0):
for lon in (0.0, 60.0, 120.0, 180.0, 240.0, 300.0):
# Strong westerly jet near lon=120E, lat=30N and moderate elsewhere
u_val = 22.0 if (lat == 30.0 and lon in (120.0, 180.0)) else 6.0
v_val = 4.0 if (lat == 30.0 and lon in (120.0, 180.0)) else 1.5
csv_lines.append(f"2026-12-03T12:00:00Z,{lat},{lon},{u_val},{v_val}")
parsed = earth_wind.parse_erddap_csv0_wind("\n".join(csv_lines))
assert float(parsed["lons"][0]) < 0.0 # rolled from 0..360 to -180..180
assert parsed["u"].shape == (3, 6)
analysis = earth_wind.analyze_wind_grid(parsed, config=earth_wind.WindFieldConfig())
assert analysis["global_summary"]["max_speed_ms"] > 22.0
assert analysis["global_summary"]["mean_speed_ms"] > 6.0
# Verify save + point query + grid payload
entry = earth_wind._save_wind_run_sync(
version="20261203T120000Z",
captured_at="2026-12-03T12:00:00Z",
parsed=parsed,
analysis=analysis,
max_history_runs=4,
)
assert entry["grid_url"] == "/api/v1/earth/wind/grid/20261203T120000Z"
payload = earth_wind.read_wind_grid_payload("20261203T120000Z")
assert payload is not None
assert payload["width"] == 6 and payload["height"] == 3
@pytest.mark.asyncio
async def test_tile_proxy_gating_cache_lru_and_basemap_api(tmp_path, monkeypatch):
monkeypatch.setattr(earth_tiles, "TILES_DATA_DIR", tmp_path / "tiles")
monkeypatch.setattr(earth_wind, "WIND_DATA_DIR", tmp_path / "wind")
from app.api.v1.datasources import infer_datasource_product_key
assert infer_datasource_product_key("earth_imagery_sentinel2", "Sentinel-2") == "geo"
assert infer_datasource_product_key("earth_imagery_viirs_daily", "NASA VIIRS") == "geo"
assert infer_datasource_product_key("global_wind_gfs", "NOAA GFS Wind") == "weather"
# Pre-seed Sentinel-2 cached tile and inactive flag test
cached_path = earth_tiles._tile_path("earth_imagery_sentinel2", 0, 0, 0)
earth_tiles._atomic_write_bytes(cached_path, b"RIFFdemoWEBP")
# Test DataSource.is_active=False enforcement directly
class _DisabledTileDB(_DummyAsyncDB):
async def execute(self, stmt):
sql = str(stmt)
if "FROM data_sources" in sql:
return _FakeScalarResult(
rows=[(36, "earth_imagery_sentinel2", False)],
scalar=type("_DS", (), {"source": "earth_imagery_sentinel2", "is_active": False})(),
)
return await super().execute(stmt)
_raw, allowed = await earth_tiles.get_or_fetch_tile(
"earth_imagery_sentinel2", 0, 0, 0, db=_DisabledTileDB()
)
assert allowed is False
# Test active source serves cached bytes without upstream call
class _EnabledTileDB(_DummyAsyncDB):
async def execute(self, stmt):
sql = str(stmt)
if "FROM data_sources" in sql:
return _FakeScalarResult(
rows=[(36, "earth_imagery_sentinel2", True)],
scalar=type("_DS", (), {"source": "earth_imagery_sentinel2", "is_active": True})(),
)
return await super().execute(stmt)
served, allowed_ok = await earth_tiles.get_or_fetch_tile(
"earth_imagery_sentinel2", 0, 0, 0, db=_EnabledTileDB()
)
assert allowed_ok is True
assert served == b"RIFFdemoWEBP"
# Collector instantiation checks (catches missing abstract methods!)
c_hd = CloudHDTilesCollector()
c_s2 = Sentinel2ImageryCollector()
c_viirs = VIIRSDailyImageryCollector()
c_wind = EarthWindGFSCollector()
assert c_hd.name == "cloud_hd_tiles"
assert c_s2.name == "earth_imagery_sentinel2"
assert c_viirs.name == "earth_imagery_viirs_daily"
assert c_wind.name == "global_wind_gfs"
monkeypatch.setattr(
earth_tiles,
"get_or_fetch_tile",
AsyncMock(return_value=(b"RIFFdemoWEBP", True)),
)
from app.core.security import get_current_user
from app.db.session import get_db
fake_db = _DummyAsyncDB(
active_sources={
"earth_imagery_sentinel2": True,
"earth_imagery_viirs_daily": False,
"global_cloud_map": True,
"cloud_hd_tiles": True,
"global_wind_gfs": True,
}
)
admin_user = User(id=1, username="admin", role=UserRole.ADMIN)
async def _override_db():
yield fake_db
app.dependency_overrides[get_db] = _override_db
app.dependency_overrides[get_current_user] = lambda: admin_user
try:
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
r_tile = await client.get("/api/v1/earth/tiles/earth_imagery_sentinel2/0/0/0.webp")
assert r_tile.status_code == 200
assert r_tile.headers["content-type"].startswith("image/webp")
r_cfg = await client.get("/api/v1/earth/basemap/configuration")
assert r_cfg.status_code == 200
rev = r_cfg.json()["revision"]
r_put = await client.put(
"/api/v1/earth/basemap/configuration",
json={
"revision": rev,
"config": {**r_cfg.json()["config"], "active_source": "earth_imagery_viirs_daily"},
},
)
assert r_put.status_code == 200
assert r_put.json()["config"]["active_source"] == "earth_imagery_viirs_daily"
r_stale = await client.put(
"/api/v1/earth/basemap/configuration",
json={"revision": rev, "config": r_cfg.json()["config"]},
)
assert r_stale.status_code == 409
r_geo = await client.get("/api/v1/data-products/geo/status")
assert r_geo.status_code == 200
assert r_geo.json()["product_id"] == "geo"
assert r_geo.json()["total_collector_count"] == 2
wind_tool = await query_wind_posture_tool(fake_db, latitude=30.0, longitude=120.0)
assert wind_tool["domain"] == "wind"
finally:
app.dependency_overrides.clear()
@pytest.mark.asyncio
async def test_get_or_fetch_tile_coalesces_concurrent_requests(tmp_path, monkeypatch):
monkeypatch.setattr(earth_tiles, "TILES_DATA_DIR", tmp_path / "tiles")
monkeypatch.setattr(
earth_tiles,
"_get_source_runtime_settings",
AsyncMock(
return_value=(
True,
earth_tiles.DEFAULT_TILE_TEMPLATES["earth_imagery_sentinel2"],
{"max_zoom": 8, "request_timeout_seconds": 10},
)
),
)
calls = 0
async def slow_fetch(*_args, **_kwargs):
nonlocal calls
calls += 1
await asyncio.sleep(0.05)
return b"RIFFcoalescedWEBP"
monkeypatch.setattr(earth_tiles, "_fetch_and_encode_tile", slow_fetch)
results = await asyncio.gather(
*(
earth_tiles.get_or_fetch_tile("earth_imagery_sentinel2", 2, 1, 1)
for _ in range(4)
)
)
assert calls == 1
assert results == [(b"RIFFcoalescedWEBP", True)] * 4
def test_tile_encode_semaphore_limits_concurrency_without_retaining_closed_loop(monkeypatch):
monkeypatch.setenv("PLANET_TILE_ENCODE_CONCURRENCY", "1")
async def contend_for_semaphore():
waiting = asyncio.Event()
entered = asyncio.Event()
async def acquire():
waiting.set()
async with earth_tiles._get_tile_encode_semaphore():
entered.set()
async with earth_tiles._get_tile_encode_semaphore():
contender = asyncio.create_task(acquire())
await waiting.wait()
assert not entered.is_set()
await contender
assert entered.is_set()
return weakref.ref(asyncio.get_running_loop())
loop_ref = asyncio.run(contend_for_semaphore())
gc.collect()
assert loop_ref() is None
@pytest.mark.asyncio
async def test_cleanup_stale_running_tasks_include_all_running(monkeypatch):
from datetime import UTC, datetime
from types import SimpleNamespace
from contextlib import asynccontextmanager
from app.services import scheduler
fresh_task = SimpleNamespace(
id=111,
status="running",
phase="fetching",
started_at=datetime.now(UTC),
completed_at=None,
error_message="",
)
committed = False
class _FakeDb:
async def execute(self, _stmt):
return SimpleNamespace(scalars=lambda: SimpleNamespace(all=lambda: [fresh_task]))
async def commit(self):
nonlocal committed
committed = True
@asynccontextmanager
async def _fake_session_factory():
yield _FakeDb()
monkeypatch.setattr(scheduler, "async_session_factory", _fake_session_factory)
cleaned = await scheduler.cleanup_stale_running_tasks(include_all_running=True)
assert cleaned == 1
assert committed is True
assert fresh_task.status == "failed"
assert fresh_task.phase == "failed"
assert fresh_task.completed_at is not None
assert "backend restart" in fresh_task.error_message