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_files.py

"""/v1/files against the fake server: listing, URLs, Range-resumed download, and
Parquet reads that fetch only the row groups a bbox needs."""

from __future__ import annotations

import hashlib
import importlib.util
import io

import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
import pytest

import korp_map_client
from conftest import GRID, PER_CELL

HAS_GEO = importlib.util.find_spec("geopandas") is not None and importlib.util.find_spec("shapely") is not None
geo = pytest.mark.skipif(not HAS_GEO, reason="needs the [geo] extra")
POINTS = "nodes.point.parquet"
CELL = (13.0, 58.0, 13.99, 58.99)  # exactly one 1-degree cell of the 10 x 10 grid


@pytest.fixture()
def c(files_server):
    url, _ = files_server
    with korp_map_client.Client(url) as client:
        yield client


def file_reqs(state, name):
    return [r for r in state.requests if r["path"].endswith("/" + name)]


# -- listing and URLs ------------------------------------------------------------


def test_files_listing(c, files_server, parquet_files):
    _, state = files_server
    files = c.files()
    assert state.requests[-1]["path"] == "/v1/files/testland/"
    by = {(f["set"], f["name"]): f for f in files}
    assert set(by) == set(parquet_files)
    f = by[("native", POINTS)]
    data = parquet_files[("native", POINTS)]
    assert f["size"] == len(data) and f["sha256"] == hashlib.sha256(data).hexdigest()
    assert f["format"] == "geoparquet-1.1-native"


def test_file_url_relative_and_absolute(c, files_server):
    url, _ = files_server
    assert c.file_url(POINTS) == f"{url}/v1/files/testland/native/{POINTS}"
    assert c.file_url("native/blob.bin") == f"{url}/v1/files/testland/native/blob.bin"
    if HAS_GEO:
        assert c.file_url("lines.parquet") == f"{url}/v1/files/testland/geoparquet2/lines.parquet"


def test_file_url_lists_once(c, files_server):
    _, state = files_server
    c.file_url(POINTS)
    c.file_url(POINTS)
    assert sum(r["path"] == "/v1/files/testland/" for r in state.requests) == 1


def test_ambiguous_and_unknown_names(c):
    with pytest.raises(korp_map_client.KorpMapError, match="more than one set"):
        c.file_url("blob.bin")
    assert c.file_url("geoparquet2/blob.bin").endswith("/geoparquet2/blob.bin")
    with pytest.raises(korp_map_client.KorpMapError, match="no file"):
        c.file_url("nope.parquet")


def test_files_unknown_region(c):
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        c.files(region="atlantis")
    assert ei.value.code == "korp-map-108"


def test_files_endpoint_missing(files_server):
    url, state = files_server
    state.files_served = False
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        korp_map_client.Client(url).files()
    assert ei.value.status == 404


# -- download --------------------------------------------------------------------


def test_download(c, files_server, parquet_files, tmp_path):
    _, state = files_server
    seen = []
    p = c.download("native/blob.bin", tmp_path, progress=lambda d, t: seen.append((d, t)))
    assert p == tmp_path / "blob.bin"
    assert p.read_bytes() == parquet_files[("native", "blob.bin")]
    assert not (tmp_path / "blob.bin.part").exists()
    assert seen[-1] == (len(p.read_bytes()), len(p.read_bytes()))
    reqs = file_reqs(state, "blob.bin")
    assert len(reqs) == 1 and "range" not in {k.lower() for k in reqs[0]["headers"]}
    # intact already: no new request
    c.download("native/blob.bin", tmp_path)
    assert len(file_reqs(state, "blob.bin")) == 1


def test_download_to_file_path_and_progress_true(c, tmp_path, capsys):
    p = c.download(POINTS, tmp_path / "sub" / "pts.parquet", progress=True)
    assert p == tmp_path / "sub" / "pts.parquet"
    assert pq.ParquetFile(p).metadata.num_rows == GRID * GRID * PER_CELL
    assert "100 %" in capsys.readouterr().err


def test_download_resumes_with_range(c, files_server, parquet_files, tmp_path):
    _, state = files_server
    data = parquet_files[("native", "blob.bin")]
    (tmp_path / "blob.bin.part").write_bytes(data[:300_000])
    p = c.download("native/blob.bin", tmp_path)
    assert p.read_bytes() == data
    h = {k.lower(): v for k, v in file_reqs(state, "blob.bin")[-1]["headers"].items()}
    assert h["range"] == "bytes=300000-" and h["accept-encoding"] == "identity"


def test_download_broken_then_resumed(c, files_server, parquet_files, tmp_path):
    _, state = files_server
    data = parquet_files[("native", "blob.bin")]
    state.cut_after = 400_000
    with pytest.raises(korp_map_client.KorpMapError, match="resume"):
        c.download("native/blob.bin", tmp_path)
    assert 0 < (tmp_path / "blob.bin.part").stat().st_size <= 400_000
    assert not (tmp_path / "blob.bin").exists()
    state.cut_after = None
    p = c.download("native/blob.bin", tmp_path)
    assert p.read_bytes() == data
    h = {k.lower(): v for k, v in file_reqs(state, "blob.bin")[-1]["headers"].items()}
    assert h["range"] == "bytes=400000-"


def test_download_no_resume_starts_over(c, files_server, parquet_files, tmp_path):
    _, state = files_server
    (tmp_path / "blob.bin.part").write_bytes(b"junk" * 10)
    p = c.download("native/blob.bin", tmp_path, resume=False)
    assert p.read_bytes() == parquet_files[("native", "blob.bin")]
    assert "range" not in {k.lower() for k in file_reqs(state, "blob.bin")[-1]["headers"]}


def test_download_server_ignores_range(c, files_server, parquet_files, tmp_path):
    _, state = files_server
    state.ignore_range = True
    data = parquet_files[("native", "blob.bin")]
    (tmp_path / "blob.bin.part").write_bytes(data[:1000])
    assert c.download("native/blob.bin", tmp_path).read_bytes() == data


def test_download_bad_part_fails_sha_then_recovers(c, parquet_files, tmp_path):
    data = parquet_files[("native", "blob.bin")]
    (tmp_path / "blob.bin.part").write_bytes(b"\0" * 1000)  # wrong bytes, resumed after
    with pytest.raises(korp_map_client.KorpMapError, match="sha256"):
        c.download("native/blob.bin", tmp_path)
    assert not (tmp_path / "blob.bin.part").exists()
    assert c.download("native/blob.bin", tmp_path).read_bytes() == data


def test_download_sha_mismatch(c, files_server, tmp_path):
    _, state = files_server
    state.sha_override[POINTS] = "0" * 64
    c._files.clear()
    with pytest.raises(korp_map_client.KorpMapError, match="does not match"):
        c.download(POINTS, tmp_path)
    assert not (tmp_path / POINTS).exists() and not (tmp_path / (POINTS + ".part")).exists()


def test_download_redownloads_a_changed_file(c, parquet_files, tmp_path):
    (tmp_path / "blob.bin").write_bytes(b"x" * len(parquet_files[("native", "blob.bin")]))
    assert c.download("native/blob.bin", tmp_path).read_bytes() == parquet_files[("native", "blob.bin")]


# -- read_parquet over Range -----------------------------------------------------


def test_read_parquet_whole(c, parquet_files):
    t = c.read_parquet(POINTS)
    want = pq.read_table(io.BytesIO(parquet_files[("native", POINTS)]))
    assert t.equals(want)
    assert t.schema.metadata[b"geo"] == want.schema.metadata[b"geo"]
    assert c.last_read["row_groups_read"] == c.last_read["row_groups_total"] == GRID * GRID


def test_read_parquet_bbox_reads_one_row_group(c, files_server):
    _, state = files_server
    t = c.read_parquet(POINTS, bbox=CELL)
    assert t.num_rows == PER_CELL
    x = t.column("geometry").combine_chunks().field("x")
    y = t.column("geometry").combine_chunks().field("y")
    assert pc.min(x).as_py() >= 13 and pc.max(x).as_py() < 14 and pc.min(y).as_py() >= 58 and pc.max(y).as_py() < 59
    lr = c.last_read
    assert lr["row_groups_read"] == 1 and lr["row_groups_total"] == GRID * GRID
    assert lr["bytes_fetched"] < lr["file_size"] / 4, lr
    for r in file_reqs(state, POINTS):  # every read was a Range request, never the whole file
        h = {k.lower(): v for k, v in r["headers"].items()}
        assert r["method"] == "HEAD" or h.get("range", "").startswith("bytes=")


def test_read_parquet_bbox_rows_exact(c):
    # a bbox inside one cell: one row group, and the rows cut to the bbox
    q = (13.0, 58.0, 13.5, 58.5)
    t = c.read_parquet(POINTS, bbox=q, columns=["id", "geometry"])
    assert t.column_names == ["id", "geometry"]  # the covering column used for the cut is dropped
    g = t.column("geometry").combine_chunks()
    xs, ys = g.field("x").to_pylist(), g.field("y").to_pylist()
    assert 0 < len(xs) < PER_CELL
    assert all(q[0] <= x <= q[2] and q[1] <= y <= q[3] for x, y in zip(xs, ys))
    full = c.read_parquet(POINTS, columns=["geometry"]).column("geometry").combine_chunks()
    inside = sum(q[0] <= x <= q[2] and q[1] <= y <= q[3] for x, y in zip(full.field("x").to_pylist(), full.field("y").to_pylist()))
    assert inside == len(xs)


def test_read_parquet_bbox_spanning_cells(c):
    t = c.read_parquet(POINTS, bbox=(12.5, 57.5, 14.5, 58.5), columns=["id"])
    assert c.last_read["row_groups_read"] == 6  # 3 lon cells x 2 lat cells
    assert t.num_rows > 0


def test_read_parquet_bbox_outside(c):
    t = c.read_parquet(POINTS, bbox=(-10, -10, -9, -9))
    assert t.num_rows == 0 and c.last_read["row_groups_read"] == 0
    assert t.schema.names == ["id", "tags", "geometry", "bbox"]


def test_read_parquet_server_ignores_range(c, files_server):
    _, state = files_server
    state.ignore_range = True
    assert c.read_parquet(POINTS, bbox=CELL).num_rows == PER_CELL


@geo
def test_read_parquet_gp2_by_geo_statistics(c):
    t = c.read_parquet("lines.parquet", bbox=CELL)
    assert c.last_read["row_groups_read"] == 1
    assert t.num_rows == PER_CELL
    assert c.last_read["bytes_fetched"] < c.last_read["file_size"] / 4


@geo
def test_read_gdf_gp2_lines_and_areas(c):
    gdf = c.read_gdf("lines.parquet", bbox=CELL)
    assert len(gdf) == PER_CELL and set(gdf.geom_type) == {"LineString"}
    assert gdf.crs.to_epsg() == 4326
    minx, miny, maxx, maxy = gdf.total_bounds
    assert 13 <= minx and maxx < 14 and 58 <= miny and maxy < 59
    areas = c.read_gdf("areas.parquet", bbox=(10, 55, 11, 56), columns=["id", "geometry"])
    assert list(areas.columns) == ["id", "geometry"] and set(areas.geom_type) == {"Polygon"}
    import numpy as np
    import shapely

    assert np.allclose(shapely.area(np.asarray(areas.geometry)), 0.0001)


@geo
def test_read_gdf_gp2_extension_registered(c):
    from conftest import _WKB

    pa.register_extension_type(_WKB())
    try:
        gdf = c.read_gdf("lines.parquet", bbox=CELL)
        assert len(gdf) == PER_CELL and gdf.crs.to_epsg() == 4326
    finally:
        pa.unregister_extension_type("geoarrow.wkb")


@geo
def test_read_gdf_native(c):
    gdf = c.read_gdf(POINTS, bbox=CELL, columns=["id", "geometry"])
    assert len(gdf) == PER_CELL and set(gdf.geom_type) == {"Point"} and gdf.crs.to_epsg() == 4326


def test_set_field_drives_names_and_fallback_url(c, files_server):
    url, _ = files_server
    from korp_map_client._client import _pick_file, _set_of

    rows = [{"name": "a.parquet", "set": "geoparquet2", "format": "geoparquet-2.0", "size": 1, "sha256": None, "url": None},
            {"name": "a.parquet", "set": "native", "format": "geoparquet-1.1-native", "size": 1, "sha256": None,
             "url": "/v1/files/testland/native/a.parquet"}]
    assert _set_of(rows[0]) == "geoparquet2" and _set_of({"url": "/v1/files/r/native/x.parquet"}) == "native"
    assert _pick_file(rows, "geoparquet2/a.parquet") is rows[0]
    c._files["testland"] = rows
    assert c.file_url("geoparquet2/a.parquet") == f"{url}/v1/files/testland/geoparquet2/a.parquet"
    assert c.file_url("native/a.parquet") == f"{url}/v1/files/testland/native/a.parquet"