import io import json import zipfile from pathlib import Path import pytest from httpx import ASGITransport, AsyncClient from starlette.applications import Starlette from starlette.routing import Route from app.core.datasource_defaults import DEFAULT_DATASOURCES from app.services.collectors.registry import collector_registry from app.services import earth_boundaries REPO = Path(__file__).resolve().parents[2] def patch_paths(monkeypatch, tmp_path): data_dir = tmp_path / "backend/data/earth-boundaries" source_dir = data_dir / "sources" artifact_dir = data_dir / "artifacts" legacy = tmp_path / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson" config = tmp_path / "config/earth-boundary-sources.local.json" example = tmp_path / "config/earth-boundary-sources.example.json" policy = tmp_path / "config/earth-boundary-pov-policy.china-v1.json" geometry = tmp_path / "resources/earth/boundary-pov-geometry.china-v1.json" for path in (source_dir, artifact_dir, legacy.parent, config.parent, geometry.parent): path.mkdir(parents=True, exist_ok=True) policy.write_bytes((REPO / "config/earth-boundary-pov-policy.china-v1.json").read_bytes()) geometry.write_bytes((REPO / "resources/earth/boundary-pov-geometry.china-v1.json").read_bytes()) example.write_text('{"collectorConfigs":{}}\n', encoding="utf-8") monkeypatch.setattr(earth_boundaries, "REPO_ROOT", tmp_path) monkeypatch.setattr(earth_boundaries, "BOUNDARY_DATA_DIR", data_dir) monkeypatch.setattr(earth_boundaries, "SOURCE_OUTPUT_DIR", source_dir) monkeypatch.setattr(earth_boundaries, "SOURCE_MANIFEST_PATH", source_dir / "manifest.json") monkeypatch.setattr(earth_boundaries, "BUILD_RESULT_PATH", data_dir / "build-result.json") monkeypatch.setattr(earth_boundaries, "BUILD_JOB_PATH", data_dir / "build-job.json") monkeypatch.setattr(earth_boundaries, "BOUNDARY_OUTPUT_DIR", artifact_dir) monkeypatch.setattr(earth_boundaries, "BOUNDARY_MANIFEST_PATH", artifact_dir / "manifest.json") monkeypatch.setattr(earth_boundaries, "POLICY_FALLBACK_PATH", legacy) monkeypatch.setattr(earth_boundaries, "LOCAL_CONFIG_PATH", config) monkeypatch.setattr(earth_boundaries, "EXAMPLE_CONFIG_PATH", example) monkeypatch.setattr(earth_boundaries, "POV_POLICY_PATH", policy) monkeypatch.setattr(earth_boundaries, "POV_GEOMETRY_PATH", geometry) return { "repo": tmp_path, "config": config, "legacy": legacy, "artifacts": artifact_dir, "sources": source_dir, "manifest": artifact_dir / "manifest.json", } def verified_coverage(): policy = earth_boundaries._read_json(earth_boundaries.POV_POLICY_PATH) geometry = earth_boundaries._read_json(earth_boundaries.POV_GEOMETRY_PATH) return { "profile": "china-pov-v1", "sha256": earth_boundaries._stable_json_hash(policy), "geometrySha256": earth_boundaries._stable_json_hash(geometry), "reviewedGeometrySourceCommit": geometry["sourceCommit"], "applied": True, "appliedRuleIds": [ "china-hong-kong", "china-macao", "china-maritime-claim-line", "china-taiwan-penghu", "kosovo", ], "publicationReady": False, } def write_fallback(path): path.write_text( json.dumps({"type": "FeatureCollection", "features": [], "povPolicy": verified_coverage()}), encoding="utf-8", ) def write_verified_artifacts(paths, *, pmtiles_bytes=b"PMTiles" + bytes(range(256))): names = { "pmtiles": "earth-boundaries.abc-def.pmtiles", "hover": "hover-index.abc-def.json", "borders": "hover-borders.abc-def.json", } (paths["artifacts"] / names["pmtiles"]).write_bytes(pmtiles_bytes) (paths["artifacts"] / names["hover"]).write_text('{"type":"FeatureCollection","features":[]}', encoding="utf-8") (paths["artifacts"] / names["borders"]).write_text('{"type":"FeatureCollection","features":[]}', encoding="utf-8") manifest = { "schema": earth_boundaries.MANIFEST_SCHEMA, "tileProvider": "pmtiles-mvt", "buildInputHash": "abc", "pmtiles": {"path": names["pmtiles"], "sizeBytes": len(pmtiles_bytes)}, "hoverIndex": names["hover"], "hoverBorders": names["borders"], "povPolicy": verified_coverage(), } paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") return names def test_boundary_status_uses_policy_fallback_when_no_artifact(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) write_fallback(paths["legacy"]) status = earth_boundaries.get_boundary_status() assert status["provider"] == "policy-geojson-fallback" assert status["fallback_available"] is True assert status["high_precision_ready"] is False def test_boundary_status_rejects_unverified_fallback(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) paths["legacy"].write_text('{"type":"FeatureCollection","features":[]}', encoding="utf-8") status = earth_boundaries.get_boundary_status() assert status["provider"] == "missing" assert status["fallback_available"] is False def test_boundary_status_prefers_verified_pmtiles(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) write_fallback(paths["legacy"]) names = write_verified_artifacts(paths) status = earth_boundaries.get_boundary_status() assert status["provider"] == "pmtiles-mvt" assert status["high_precision_ready"] is True assert status["policy_publishable"] is False assert status["pmtiles"]["path"] == names["pmtiles"] assert earth_boundaries.get_public_boundary_manifest()["hoverIndex"] == names["hover"] @pytest.mark.parametrize( "mutate", [ lambda manifest: manifest["povPolicy"].update(applied=False), lambda manifest: manifest["povPolicy"].update(geometrySha256="stale"), lambda manifest: manifest.update(schema="planet-earth-boundaries/v1"), lambda manifest: manifest.update(hoverBorders=None), ], ) def test_boundary_status_rejects_unverified_or_incomplete_manifest(monkeypatch, tmp_path, mutate): paths = patch_paths(monkeypatch, tmp_path) write_fallback(paths["legacy"]) write_verified_artifacts(paths) manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) mutate(manifest) paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") status = earth_boundaries.get_boundary_status() assert status["provider"] == "policy-geojson-fallback" assert status["high_precision_ready"] is False assert earth_boundaries.get_public_boundary_manifest() is None def test_resolve_boundary_artifact_only_serves_manifest_files(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) names = write_verified_artifacts(paths) (paths["artifacts"] / "other.json").write_text("{}", encoding="utf-8") assert earth_boundaries.resolve_boundary_artifact(names["pmtiles"]) is not None assert earth_boundaries.resolve_boundary_artifact("other.json") is None assert earth_boundaries.resolve_boundary_artifact("manifest.json") is None assert earth_boundaries.resolve_boundary_artifact("../artifacts/" + names["hover"]) is None assert earth_boundaries.resolve_boundary_artifact("") is None @pytest.mark.asyncio async def test_boundary_file_route_answers_range_requests(monkeypatch, tmp_path): from app.api.v1 import earth as earth_api paths = patch_paths(monkeypatch, tmp_path) payload = b"PMTiles" + bytes(range(256)) * 4 names = write_verified_artifacts(paths, pmtiles_bytes=payload) async def endpoint(request): return await earth_api.get_earth_boundary_file(request.path_params["name"]) app = Starlette(routes=[Route("/files/{name}", endpoint, methods=["GET", "HEAD"])]) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: head_resp = await client.head(f"/files/{names['pmtiles']}") assert head_resp.status_code == 200 assert head_resp.headers["accept-ranges"] == "bytes" assert head_resp.headers["content-length"] == str(len(payload)) assert head_resp.content == b"" partial = await client.get(f"/files/{names['pmtiles']}", headers={"Range": "bytes=0-15"}) assert partial.status_code == 206 assert partial.content == payload[:16] assert partial.headers["content-range"] == f"bytes 0-15/{len(payload)}" assert partial.headers["content-type"] == "application/vnd.pmtiles" assert "immutable" in partial.headers["cache-control"] unsatisfiable = await client.get( f"/files/{names['pmtiles']}", headers={"Range": f"bytes={len(payload) + 10}-"} ) assert unsatisfiable.status_code == 416 @pytest.mark.asyncio async def test_boundary_file_route_rejects_unlisted_files(monkeypatch, tmp_path): from fastapi import HTTPException from app.api.v1 import earth as earth_api paths = patch_paths(monkeypatch, tmp_path) write_verified_artifacts(paths) with pytest.raises(HTTPException) as exc_info: await earth_api.get_earth_boundary_file("manifest.json") assert exc_info.value.status_code == 404 def test_save_boundary_config_writes_local_config(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) payload = {"collectorConfigs": {"earth_admin0_boundaries": {"endpoint": "file:///tmp/a.geojson"}}} status = earth_boundaries.save_boundary_config(payload) assert paths["config"].exists() assert status["config_source"] == "local" assert status["config"] == payload def test_default_sources_use_osm_coastline_and_china_pov_claims(): sources = earth_boundaries.DEFAULT_PUBLIC_BOUNDARY_SOURCES assert set(sources) == set(earth_boundaries.BOUNDARY_SOURCE_KINDS) assert sources["earth_coastline"]["endpoint"].startswith("https://osmdata.openstreetmap.de/") assert "ODbL" in sources["earth_coastline"]["license"] assert sources["earth_claim_lines"]["endpoint"].endswith("maritime_indicator_chn.geojson") assert sources["earth_admin1_lines"]["endpoint"].endswith("admin_1_states_provinces_lines.geojson") assert sources["earth_populated_places"]["endpoint"].endswith("ne_10m_populated_places.geojson") def test_resolve_boundary_artifact_serves_geo_labels(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) write_fallback(paths["legacy"]) write_verified_artifacts(paths) labels_name = "geo-labels.abc-def.json" (paths["artifacts"] / labels_name).write_text('{"schema":"planet-earth-geo-labels/v1","places":[]}', encoding="utf-8") manifest = json.loads(paths["manifest"].read_text(encoding="utf-8")) manifest["geoLabels"] = labels_name paths["manifest"].write_text(json.dumps(manifest), encoding="utf-8") assert earth_boundaries.resolve_boundary_artifact(labels_name) == paths["artifacts"] / labels_name assert earth_boundaries.resolve_boundary_artifact("../manifest.json") is None @pytest.mark.asyncio async def test_build_fails_loudly_when_tippecanoe_missing(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) monkeypatch.setattr(earth_boundaries.shutil, "which", lambda _tool: None) async def unexpected_download(*_args, **_kwargs): raise AssertionError("sources must not download without build tools") monkeypatch.setattr(earth_boundaries, "_download_source", unexpected_download) with pytest.raises(earth_boundaries.EarthBoundaryBuildError) as exc_info: await earth_boundaries.build_boundary_assets() assert exc_info.value.code == "missing_tools" assert exc_info.value.details == {"missing_tools": ["tippecanoe"]} assert not paths["manifest"].exists() assert earth_boundaries.get_boundary_status()["build_tools_ready"] is False @pytest.mark.asyncio async def test_start_build_job_rejects_missing_tools(monkeypatch, tmp_path): patch_paths(monkeypatch, tmp_path) monkeypatch.setattr(earth_boundaries, "_build_task", None) monkeypatch.setattr(earth_boundaries, "_build_job_state", {}) monkeypatch.setattr(earth_boundaries.shutil, "which", lambda _tool: None) with pytest.raises(earth_boundaries.EarthBoundaryBuildError) as exc_info: await earth_boundaries.start_boundary_build_job() assert exc_info.value.code == "missing_tools" @pytest.mark.asyncio async def test_build_rejects_artifact_without_verified_manifest(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) monkeypatch.setattr(earth_boundaries.shutil, "which", lambda tool: f"/usr/bin/{tool}") async def fake_download(source_key, source_config, _progress=None): return {"id": source_key, "kind": source_config["sourceKind"], "path": f"/tmp/{source_key}", "sha256": source_key} async def fake_builder(_args): paths["manifest"].write_text('{"schema":"planet-earth-boundaries/v2","povPolicy":{"applied":false}}', encoding="utf-8") return {"returncode": 0} monkeypatch.setattr(earth_boundaries, "_download_source", fake_download) monkeypatch.setattr(earth_boundaries, "_run_builder", fake_builder) with pytest.raises(earth_boundaries.EarthBoundaryBuildError) as exc_info: await earth_boundaries.build_boundary_assets() assert exc_info.value.code == "unverified_artifact" @pytest.mark.asyncio async def test_download_streams_zip_sources_and_counts_shapefile_records(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) archive = tmp_path / "coast.zip" shx = io.BytesIO(b"\0" * 100 + b"\0" * 8 * 3) with zipfile.ZipFile(archive, "w") as zf: zf.writestr("coastlines-split-4326/lines.shx", shx.getvalue()) zf.writestr("coastlines-split-4326/lines.shp", b"shape") source = await earth_boundaries._download_source( "earth_coastline", {"endpoint": str(archive), "sourceKind": "coastline"} ) assert source["featureCount"] == 3 assert source["path"].endswith(".zip") stored = list((paths["sources"] / "earth_coastline").iterdir()) assert [path.name for path in stored] == [Path(source["path"]).name] @pytest.mark.asyncio async def test_download_reuses_unchanged_remote_source(monkeypatch, tmp_path): paths = patch_paths(monkeypatch, tmp_path) body = json.dumps({"type": "FeatureCollection", "features": [{"type": "Feature"}]}).encode() seen_headers = [] def handler(request): seen_headers.append(dict(request.headers)) if request.headers.get("if-none-match") == '"v1"': return earth_boundaries.httpx.Response(304) return earth_boundaries.httpx.Response(200, content=body, headers={"etag": '"v1"', "content-type": "application/geo+json"}) real_client = earth_boundaries.httpx.AsyncClient monkeypatch.setattr( earth_boundaries.httpx, "AsyncClient", lambda **kwargs: real_client(transport=earth_boundaries.httpx.MockTransport(handler), **kwargs), ) config = {"endpoint": "https://example.org/admin1.geojson", "sourceKind": "admin1-lines"} first = await earth_boundaries._download_source("earth_admin1_lines", config) paths["sources"].joinpath("manifest.json").write_text(json.dumps({"sources": [first]}), encoding="utf-8") second = await earth_boundaries._download_source("earth_admin1_lines", config) assert first["etag"] == '"v1"' assert second["notModified"] is True assert second["sha256"] == first["sha256"] assert seen_headers[1]["if-none-match"] == '"v1"' assert Path(second["path"]).is_file() def test_earth_boundary_collectors_are_not_registered_as_datasources(): removed = set(earth_boundaries.BOUNDARY_SOURCE_KINDS) | {"earth_boundary_tiles"} assert removed.isdisjoint(DEFAULT_DATASOURCES) for source in removed: assert collector_registry.get(source) is None def test_static_policy_fallback_contains_reviewed_jeju_polygon(): path = REPO / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson" payload = json.loads(path.read_text(encoding="utf-8")) matches = [ feature for feature in payload["features"] if feature["properties"].get("PLANET_GEOMETRY_SUPPLEMENT") == "jeju-island" ] assert len(matches) == 1 jeju = matches[0] assert jeju["properties"]["ISO_A3"] == "KOR" assert jeju["properties"]["PLANET_SOURCE_NE_ID"] == 1159320985 assert payload["povPolicy"]["geometrySupplement"]["jejuComponent"] == 3 ring = jeju["geometry"]["coordinates"][0] assert len(ring) == 61 assert min(point[0] for point in ring) < 126.53 < max(point[0] for point in ring) assert min(point[1] for point in ring) < 33.36 < max(point[1] for point in ring)