"""Tests for real-time satellite IR cloud map engine, collector, APIs, and AI tools.""" from __future__ import annotations import io import json from types import SimpleNamespace from unittest.mock import AsyncMock import httpx import numpy as np from httpx import ASGITransport, AsyncClient from PIL import Image import pytest from app.core.datasource_defaults import DEFAULT_DATASOURCES from app.core.enums import UserRole from app.core.security import create_access_token, get_current_user from app.db.session import get_db from app.main import app from app.models.system_setting import SystemSetting from app.models.user import User from app.services import earth_clouds from app.services.ai.tool_registry import query_cloud_posture_tool from app.services.collectors.cloud_map import EarthCloudMapCollector from app.services.collectors.registry import collector_registry def _make_png_bytes(rgba_arr: np.ndarray) -> bytes: buf = io.BytesIO() Image.fromarray(rgba_arr, mode="RGBA").save(buf, format="PNG") return buf.getvalue() class _ScalarResult: def __init__(self, value=None, rows=None): self._value = value self._rows = rows or [] def scalar_one_or_none(self): return self._value def scalar_one(self): return self._value def scalar(self): return 0 def all(self): return self._rows def first(self): return self._rows[0] if self._rows else None def scalars(self): return SimpleNamespace(all=lambda: self._rows) class _InMemoryCloudDb: def __init__(self): self.setting: SystemSetting | None = None self.audits = [] self.committed = False self.rolled_back = False def get_bind(self): return SimpleNamespace(dialect=SimpleNamespace(name="sqlite")) async def get(self, *_args, **_kwargs): return None async def execute(self, statement): name = statement.__class__.__name__ if name == "Select": return _ScalarResult(value=self.setting, rows=[]) return _ScalarResult() def add(self, obj): if isinstance(obj, SystemSetting): obj.id = 1 self.setting = obj else: self.audits.append(obj) async def delete(self, obj): if isinstance(obj, SystemSetting): self.setting = None async def commit(self): self.committed = True async def rollback(self): self.rolled_back = True @pytest.fixture(autouse=True) def isolated_cloud_dir(tmp_path, monkeypatch): cloud_dir = tmp_path / "earth-clouds" monkeypatch.setattr(earth_clouds, "CLOUD_DATA_DIR", cloud_dir) monkeypatch.setattr("app.core.security.redis_client", SimpleNamespace(sismember=lambda *a, **k: False)) return cloud_dir def test_gibs_band13_colormap_inversion_and_dvorak_core_recovery(): """Severe convective ring enclosing a Dvorak gray hole must decode cold, never as a clear hole.""" h, w = 64, 128 arr = np.zeros((h, w, 4), dtype=np.uint8) arr[:, :, :3] = 20 # warm clear surface ~ +50°C arr[:, :, 3] = 255 # Outer convective ring: dark red (255, 0, 0) -> -60.6°C arr[20:44, 48:80, :3] = [255, 0, 0] # Inner Dvorak gray wrap core: (102, 102, 102) surrounded by <= -52°C ring -> -74.5°C arr[28:36, 56:72, :3] = [102, 102, 102] # Ultra-cold purple peak: (127, 0, 127) -> -90.6°C arr[30:33, 62:66, :3] = [127, 0, 127] temp_c, valid = earth_clouds.decode_gibs_band13_to_temp_and_valid(arr) assert valid.all() assert temp_c[5, 5] > 30.0 assert temp_c[22, 50] < -55.0 assert temp_c[32, 60] < -70.0 # Dvorak gray hole recovered as ultra-cold! assert temp_c[31, 64] < -85.0 # Purple peak decoded accurately! # Pure white GOES scan-band artifact outside convective rings must be masked invalid (no fake -91.5°C cluster) stripe_arr = np.zeros((h, w, 4), dtype=np.uint8) stripe_arr[:, :, :3] = 20 stripe_arr[:, :, 3] = 255 stripe_arr[10:18, 20:100, :3] = [254, 254, 254] stripe_temp, stripe_valid = earth_clouds.decode_gibs_band13_to_temp_and_valid(stripe_arr) assert not np.any(stripe_valid[10:18, 20:100]) assert np.all(np.isnan(stripe_temp[10:18, 20:100])) density = earth_clouds.temperature_to_density(temp_c, ir_threshold=22, contrast_gamma=0.88) assert density[5, 5] == 0 assert density[22, 50] >= 240 assert density[32, 60] == 255 def test_multi_sat_synthesis_analytics_and_artifact_pruning(isolated_cloud_dir): cfg = earth_clouds.CloudMapConfig(resolution="2048x1024", max_history_frames=4) # Create two synthetic geostationary IR frames (Himawari + Meteosat) gibs_arr = np.zeros((128, 256, 4), dtype=np.uint8) gibs_arr[:, :, :3] = 18 gibs_arr[:, :, 3] = 255 # Deep convective cyclone over South China Sea / Western Pacific (~15N, 125E) # 15N -> y = (90-15)/180*128 = 53; 125E -> x = (125+180)/360*256 = 217 gibs_arr[48:58, 210:224, :3] = [255, 0, 0] eumet_arr = np.zeros((128, 256, 4), dtype=np.uint8) eumet_arr[:, :, :3] = 10 eumet_arr[:, :, 3] = 255 eumet_arr[30:38, 120:136, :3] = 210 payloads = [ (earth_clouds.SATELLITE_SOURCES[0], _make_png_bytes(gibs_arr)), (earth_clouds.SATELLITE_SOURCES[3], _make_png_bytes(eumet_arr)), ] density, temp_c, sats = earth_clouds.synthesize_multi_sat_ir(payloads, config=cfg) assert density.shape == (1024, 2048) assert set(sats) == {"himawari", "msg_fes"} analysis = earth_clouds.analyze_cloud_density_grid(density, temp_c, config=cfg) assert analysis["global_summary"]["global_cloud_cover_pct"] > 0 assert len(analysis["regions"]) == len(earth_clouds.FOCUS_REGIONS) assert analysis["global_summary"]["convective_cluster_count"] >= 1 top_cluster = analysis["convective_clusters"][0] assert top_cluster["min_brightness_temp_c"] < -45.0 # Save 5 versions and verify retention prunes to max_history_frames=4 webp_bytes = earth_clouds._encode_cloud_webp(density) for ver in ( "20261203T010000Z", "20261203T020000Z", "20261203T030000Z", "20261203T040000Z", "20261203T050000Z", ): earth_clouds._save_frame_artifacts_sync( version=ver, captured_at=f"2026-12-03T{ver[9:11]}:00:00Z", source_used="multi_sat_ir", satellites=sats, degraded=False, config=cfg, webp_bytes=webp_bytes, grid_density=analysis["grid_density"], grid_temp_i8=analysis["grid_temp_i8"], global_summary=analysis["global_summary"], regions=analysis["regions"], clusters=analysis["convective_clusters"], ) assert earth_clouds.read_cloud_frame_bytes("20261203T050000Z") is not None assert earth_clouds.read_cloud_frame_bytes("20261203T010000Z") is None assert earth_clouds.read_cloud_frame_bytes("../etc/passwd") is None @pytest.mark.asyncio async def test_collector_registration_fallback_and_transform(monkeypatch): assert "global_cloud_map" in DEFAULT_DATASOURCES assert DEFAULT_DATASOURCES["global_cloud_map"]["id"] == 34 assert collector_registry.get("global_cloud_map") is not None # Simulate multi-sat WMS failure -> automatic fallback to matteason_live fallback_arr = np.zeros((128, 256, 4), dtype=np.uint8) fallback_arr[50:65, 180:200, :] = [245, 245, 245, 245] fallback_png = _make_png_bytes(fallback_arr) monkeypatch.setattr(earth_clouds, "_fetch_multi_sat_payloads", AsyncMock(return_value=[])) monkeypatch.setattr(earth_clouds, "_fetch_matteason_bytes", AsyncMock(return_value=fallback_png)) collector = EarthCloudMapCollector() raw = await collector.fetch() transformed = collector.transform(raw) assert len(transformed) >= 1 + len(earth_clouds.FOCUS_REGIONS) assert transformed[0]["source_id"] == "cloud_snapshot:latest" assert transformed[0]["metadata"]["cloud_source"] == "matteason_live" assert transformed[0]["metadata"]["degraded"] is True @pytest.mark.asyncio async def test_cloud_apis_rbac_optimistic_lock_and_analytics(monkeypatch): fake_db = _InMemoryCloudDb() viewer_user = User(id=3, username="viewer", role=UserRole.VIEWER, is_active=True) admin_user = User(id=1, username="admin", role=UserRole.ADMIN, is_active=True) active_user = {"user": admin_user} async def override_get_db(): yield fake_db async def override_get_user(): return active_user["user"] app.dependency_overrides[get_db] = override_get_db app.dependency_overrides[get_current_user] = override_get_user app.dependency_overrides[earth_clouds.get_cloud_datasource_summary] = None # no-op check monkeypatch.setattr(earth_clouds, "get_cloud_datasource_summary", AsyncMock(return_value={"id": 34, "source": "global_cloud_map"})) # Populate one frame cfg = earth_clouds.CloudMapConfig() grid_d = np.full((360, 720), 200, dtype=np.uint8) grid_t = np.full((360, 720), -42, dtype=np.int8) webp = earth_clouds._encode_cloud_webp(np.full((64, 128), 200, dtype=np.uint8)) earth_clouds._save_frame_artifacts_sync( version="20261203T040000Z", captured_at="2026-12-03T04:00:00Z", source_used="multi_sat_ir", satellites=["himawari"], degraded=False, config=cfg, webp_bytes=webp, grid_density=grid_d, grid_temp_i8=grid_t, global_summary={"global_cloud_cover_pct": 78.4, "convective_cluster_count": 1, "min_brightness_temp_c": -42.0}, regions=[], clusters=[], ) try: transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: # 1. Runtime meta + frame + point query r_meta = await client.get("/api/v1/earth/clouds/meta") assert r_meta.status_code == 200 assert r_meta.json()["mode"] == "realtime" assert r_meta.json()["version"] == "20261203T040000Z" r_frame = await client.get("/api/v1/earth/clouds/frames/20261203T040000Z") assert r_frame.status_code == 200 assert r_frame.headers["content-type"] == "image/webp" r_bad_frame = await client.get("/api/v1/earth/clouds/frames/..%2Fsecret") assert r_bad_frame.status_code == 404 r_point = await client.get("/api/v1/data-products/clouds/point", params={"lat": 30.2, "lon": 120.1}) assert r_point.status_code == 200 assert r_point.json()["available"] is True assert r_point.json()["cloud_cover_pct"] > 70.0 assert r_point.json()["brightness_temp_c"] == -42 # 2. RBAC: viewer cannot modify configuration active_user["user"] = viewer_user r_cfg_read = await client.get("/api/v1/earth/clouds/configuration") assert r_cfg_read.status_code == 200 rev = r_cfg_read.json()["revision"] r_viewer_put = await client.put( "/api/v1/earth/clouds/configuration", json={"revision": rev, "config": r_cfg_read.json()["config"]}, ) assert r_viewer_put.status_code == 403 # 3. Admin save & optimistic lock 409 check active_user["user"] = admin_user next_cfg = dict(r_cfg_read.json()["config"], ir_threshold=30) r_admin_put = await client.put( "/api/v1/earth/clouds/configuration", json={"revision": rev, "config": next_cfg}, ) assert r_admin_put.status_code == 200 assert r_admin_put.json()["config"]["ir_threshold"] == 30 assert r_admin_put.json()["revision"] != rev r_stale_put = await client.put( "/api/v1/earth/clouds/configuration", json={"revision": rev, "config": next_cfg}, ) assert r_stale_put.status_code == 409 # 4. AI tool posture read tool_out = await query_cloud_posture_tool(fake_db, latitude=30.2, longitude=120.1) assert tool_out["available"] is True assert tool_out["point_query"]["brightness_temp_c"] == -42 # 5. RBAC & execution for /clouds/test (formerly crashed with UserRole.OPERATOR AttributeError) active_user["user"] = viewer_user r_test_viewer = await client.post("/api/v1/earth/clouds/test", json={"source_id": "multi_sat_ir"}) assert r_test_viewer.status_code == 403 active_user["user"] = admin_user monkeypatch.setattr( earth_clouds, "test_cloud_map_source", AsyncMock( return_value={ "source_id": "multi_sat_ir", "ok": True, "reachable_count": 5, "total_count": 5, "latency_ms": 42.0, "satellites": [{"id": "himawari", "ok": True, "latency_ms": 42.0}], } ), ) r_test_admin = await client.post("/api/v1/earth/clouds/test", json={"source_id": "multi_sat_ir"}) assert r_test_admin.status_code == 200 assert r_test_admin.json()["ok"] is True # 6. Product domain classification & unified data-products status from app.api.v1.datasources import infer_datasource_product_key assert infer_datasource_product_key("global_cloud_map", "Global Satellite Cloud Map") == "weather" r_weather_status = await client.get("/api/v1/data-products/weather/status") assert r_weather_status.status_code == 200 weather_payload = r_weather_status.json() assert weather_payload["product_id"] == "weather" assert weather_payload["has_data"] is True assert weather_payload["datasources_url"] == "/datasources?product=weather" assert weather_payload["total_collector_count"] == 3 # 6b. GeoColor visual compositing + daytime low-cloud fusion + DIS optical flow helpers from datetime import UTC, datetime from app.services.earth_clouds_fx import ( compute_dis_optical_flow_webp, decode_visual_payloads, fuse_daytime_visible_into_density, synthesize_geocolor_visual_webp, ) vis_arr_clean = np.full((32, 64, 4), (240, 240, 245, 255), dtype=np.uint8) vis_arr_clean[24:30, 50:58, :3] = [255, 255, 255] # Clipped white fill artifact where thin cloud < 180 vis_png = _make_png_bytes(vis_arr_clean) d_prev = np.zeros((32, 64), dtype=np.uint8) d_prev[10:22, 46:56] = 210 d_curr = np.zeros((32, 64), dtype=np.uint8) d_curr[10:22, 50:60] = 210 d_curr[24:30, 50:58] = 80 decoded_clean = decode_visual_payloads([({"id": "himawari", "sub_lon": 140.7}, vis_png)], width=64, height=32) assert len(decoded_clean) == 1 vis_webp = synthesize_geocolor_visual_webp( decoded_clean, d_curr, width=64, height=32, ) assert vis_webp is not None and len(vis_webp) > 20 vis_decoded = np.array(Image.open(io.BytesIO(vis_webp)).convert("RGBA")) assert int(vis_decoded[16, 55, 3]) >= 180 assert int(vis_decoded[27, 54, 3]) <= 35 # clipped [255,255,255] outside dense cloud suppressed # Warm daytime low cloud (+8C) over East China (~30N, 120E) recovered while night & orange desert stay dark ir_zero = np.zeros((32, 64), dtype=np.uint8) temp_grid = np.full((32, 64), 16.0, dtype=np.float32) # East China row ~ (90-30)/180*32=10, col ~ (120+180)/360*64=53 temp_grid[9:13, 50:56] = 8.0 # Sahara daytime / hot sand (+34C) col ~ (15+180)/360*64=34 temp_grid[10:14, 32:37] = 34.0 # Winter Tibetan plateau snow (-30C at 32N, 90E -> row ~ 10, col ~ 48) temp_grid[9:12, 47:50] = -30.0 vis_arr = np.zeros((32, 64, 4), dtype=np.uint8) vis_arr[:, :, 3] = 255 vis_arr[9:13, 50:56, :3] = [215, 215, 215] # monochrome Himawari Band3 bright cloud vis_arr[10:14, 32:37, :3] = [210, 145, 85] # orange Sahara desert in RGB vis_arr[9:12, 47:50, :3] = [235, 235, 235] # cold Tibetan surface snow # Pure-white clipped EUMETView artifact over warm Bay of Bengal (+18C at 12N, 85E -> row ~ 14, col ~ 47) temp_grid[13:16, 46:49] = 18.0 vis_arr[13:16, 46:49, :3] = [255, 255, 255] # Night hemisphere over Americas (col 12, ~-112W at 05:00 UTC) vis_arr[10:14, 10:16, :3] = [220, 220, 220] decoded_fused = decode_visual_payloads( [ ({"id": "himawari", "sub_lon": 140.7}, _make_png_bytes(vis_arr)), ({"id": "msg_fes", "sub_lon": 0.0}, _make_png_bytes(vis_arr)), ({"id": "msg_iodc", "sub_lon": 45.5}, _make_png_bytes(vis_arr)), ], width=64, height=32, ) fused = fuse_daytime_visible_into_density( ir_zero, temp_grid, decoded_fused, width=64, height=32, now_utc=datetime(2026, 12, 3, 5, 0, 0, tzinfo=UTC), ) assert int(fused[11, 53]) >= 120 assert int(fused[12, 34]) < 30 assert int(fused[10, 48]) < 35 # snow at -30C suppressed assert int(fused[14, 47]) < 35 # pure-white 255 clipped EUMETView artifact suppressed assert int(fused[12, 13]) == 0 flow_res = compute_dis_optical_flow_webp(d_prev, d_curr, flow_width=64, flow_height=32) assert flow_res is not None flow_bytes, max_uv = flow_res assert len(flow_bytes) > 20 and max_uv > 0.0 # 7. Cache clear resets runtime mode to fallback_static r_clear = await client.delete("/api/v1/earth/clouds/cache") assert r_clear.status_code == 200 assert r_clear.json()["meta"]["mode"] == "fallback_static" finally: app.dependency_overrides.clear() def test_resolve_effective_cloud_config_clamps_on_low_memory(monkeypatch): cfg = earth_clouds.CloudMapConfig(resolution="4096x2048") monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: 500) clamped = earth_clouds.resolve_effective_cloud_config(cfg) assert clamped.resolution == "2048x1024" monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: 2048) assert earth_clouds.resolve_effective_cloud_config(cfg).resolution == "4096x2048" monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: None) assert earth_clouds.resolve_effective_cloud_config(cfg).resolution == "4096x2048" def test_fuse_and_synthesize_visual_layers_streams_png_payloads(): from datetime import UTC, datetime from app.services.earth_clouds_fx import fuse_and_synthesize_visual_layers ir_zero = np.zeros((32, 64), dtype=np.uint8) temp_grid = np.full((32, 64), 16.0, dtype=np.float32) temp_grid[9:13, 50:56] = 8.0 vis_arr = np.zeros((32, 64, 4), dtype=np.uint8) vis_arr[:, :, 3] = 255 vis_arr[9:13, 50:56, :3] = [215, 215, 215] fused, webp = fuse_and_synthesize_visual_layers( ir_zero, temp_grid, [({"id": "himawari", "sub_lon": 140.7}, _make_png_bytes(vis_arr))], width=64, height=32, now_utc=datetime(2026, 12, 3, 5, 0, 0, tzinfo=UTC), ) assert int(fused[11, 53]) >= 120 assert webp is not None and len(webp) > 20