Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

python/tests/test_live_files.py

"""Opt-in, LIVE: /v1/files on a running korp-map server.

    KORP_MAP_URL=https://karta.gunnar.rs pytest -m live tests/test_live_files.py

Needs the server's file downloads (lane TL). Until that server is deployed,
/v1/files answers 404 and these tests SKIP with "no /v1/files yet". Set
KORP_MAP_FILES=1 to make that a failure instead (once the server has it).
"""

from __future__ import annotations

import hashlib
import importlib.util
import os

import httpx
import pyarrow as pa
import pytest

import korp_map_client

URL = os.environ.get("KORP_MAP_URL")
REQUIRE = os.environ.get("KORP_MAP_FILES") == "1"
pytestmark = [pytest.mark.live, pytest.mark.skipif(not URL, reason="set KORP_MAP_URL to run the live tests")]
HAS_GEO = importlib.util.find_spec("geopandas") is not None
STHLM = (18.05, 59.32, 18.08, 59.34)


@pytest.fixture(scope="module")
def c():
    with korp_map_client.Client(URL) as client:
        try:
            client.files()
        except korp_map_client.KorpMapError as e:
            if e.status == 404 and not REQUIRE:
                pytest.skip(f"the server at {URL} has no /v1/files yet (lane TL): {e}")
            raise
        yield client


def _pick(c, set_, *words, smallest=False):
    cands = [f for f in c.files() if f.get("set") == set_ and (not words or any(w in f["name"] for w in words))]
    if not cands:
        pytest.skip(f"no {set_} file matching {words} in the listing")
    cands.sort(key=lambda f: f.get("size") or 0)
    return cands[0] if smallest else cands[-1]


def test_listing(c):
    files = c.files()
    assert files and {"name", "set", "format", "size", "sha256", "url"} <= set(files[0])
    assert {"native", "geoparquet2"} <= {f["set"] for f in files}
    assert {"geoparquet-1.1-native", "geoparquet-2.0"} <= {f["format"] for f in files}


def test_file_url_head(c):
    f = _pick(c, "native", smallest=True)
    url = c.file_url(f"native/{f['name']}")
    r = httpx.head(url, headers={"accept-encoding": "identity"})
    assert r.status_code == 200 and int(r.headers["content-length"]) == f["size"]
    assert r.headers.get("accept-ranges") == "bytes"


def test_range_request(c):
    f = _pick(c, "native", smallest=True)
    r = httpx.get(c.file_url(f"native/{f['name']}"), headers={"range": "bytes=0-3", "accept-encoding": "identity"})
    assert r.status_code == 206 and r.content == b"PAR1"


def test_read_parquet_native_lines_bbox(c):
    f = _pick(c, "native", "multilinestring")
    t = c.read_parquet(f"native/{f['name']}", bbox=STHLM, columns=["id", "tags", "geometry"])
    assert t.num_rows > 100
    lr = c.last_read
    assert lr["row_groups_read"] < lr["row_groups_total"] / 4
    assert lr["bytes_fetched"] < f["size"] / 10, lr


def test_read_parquet_gp2_bbox(c):
    f = _pick(c, "geoparquet2", "line")
    t = c.read_parquet(f"geoparquet2/{f['name']}", bbox=STHLM)
    assert t.num_rows > 100 and isinstance(t, pa.Table)
    assert c.last_read["bytes_fetched"] < f["size"] / 4


@pytest.mark.skipif(not HAS_GEO, reason="needs the [geo] extra")
@pytest.mark.parametrize("words", [("point", "node"), ("line",), ("area", "polygon")])
def test_read_gdf_gp2(c, words):
    f = _pick(c, "geoparquet2", *words)
    gdf = c.read_gdf(f"geoparquet2/{f['name']}", bbox=STHLM)
    assert len(gdf) > 0 and gdf.crs.to_epsg() == 4326
    import shapely

    assert gdf.intersects(shapely.box(*STHLM).buffer(1e-3)).mean() > 0.95


def test_download_and_resume(c, tmp_path):
    f = _pick(c, "native", smallest=True)
    name = f"native/{f['name']}"
    # a broken earlier download: the first third already on disk
    head = httpx.get(c.file_url(name), headers={"range": f"bytes=0-{f['size'] // 3 - 1}", "accept-encoding": "identity"})
    assert head.status_code == 206
    (tmp_path / (f["name"] + ".part")).write_bytes(head.content)
    p = c.download(name, tmp_path)
    assert p.stat().st_size == f["size"]
    h = hashlib.sha256(p.read_bytes()).hexdigest()
    assert f["sha256"] is None or h == f["sha256"].lower()