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

"""The client against the fake server in conftest.py."""

from __future__ import annotations

import importlib.util

import pyarrow as pa
import pytest

import korp_map_client
from conftest import ROWS, make_table

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")
BBOX = (17.9, 59.2, 18.2, 59.4)


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


def test_health_and_regions(client):
    assert client.health() is True
    regs = client.regions()
    assert [r["name"] for r in regs] == ["testland", "other"]
    assert regs[0]["bbox"] == [10.0, 55.0, 24.0, 69.0]


def test_region_defaults_to_first_served(client, fake_server):
    _, state = fake_server
    assert client.region == "testland"
    client.map("points", BBOX, lod=14)
    assert state.requests[-1]["query"]["region"] == "testland"


def test_region_given_is_used(fake_server):
    url, state = fake_server
    c = korp_map_client.Client(url + "/", region="testland")
    c.map("points", BBOX, lod=3)
    assert [r["path"] for r in state.requests] == ["/v1/map/points"]  # no /v1/regions lookup


@pytest.mark.parametrize("kind", ["points", "lines", "areas"])
def test_map_returns_table_with_metadata(client, fake_server, kind):
    _, state = fake_server
    res = client.map(kind, bbox=BBOX, lod=14)
    assert isinstance(res, korp_map_client.MapResult)
    assert isinstance(res.table, pa.Table)
    assert res.table.num_rows == len(res) == res.num_rows == len(ROWS[kind])
    assert res.table.column_names == ["id", "tags", "min_zoom", "geometry"]
    assert res.truncated is False
    assert res.data_version == "files-test0001"
    assert (res.row_groups_total, res.row_groups_scanned) == (12, 3)
    assert res.status == "ok" and res.geometry_source == "full"
    assert res.table.schema.metadata[b"data_version"] == b"files-test0001"
    assert b"geo" in res.table.schema.metadata
    assert res.table.equals(make_table(kind))
    q = state.requests[-1]["query"]
    assert q["bbox"] == "17.9,59.2,18.2,59.4" and q["lod"] == "14" and "max" not in q
    assert client.map_table(kind, BBOX, 14).equals(res.table)


def test_truncated_reply(client, fake_server):
    _, state = fake_server
    res = client.map("lines", BBOX, lod=14, max=2)
    assert res.truncated is True
    assert res.num_rows == 2
    assert state.requests[-1]["query"]["max"] == "2"


def test_empty_reply(client):
    res = client.map("areas", BBOX, lod=14, max=0)
    assert res.num_rows == 0 and res.truncated is True


def test_compress_param_passes(client, fake_server):
    _, state = fake_server
    client.map("points", BBOX, lod=14, compress="zstd")
    assert state.requests[-1]["query"]["compress"] == "zstd"


def test_arrow_stream_protocol(client):
    res = client.map("points", BBOX, lod=14)
    back = pa.table(res) if hasattr(pa, "table") else None
    assert back is not None and back.num_rows == res.num_rows


def test_user_agent_and_accept_encoding(client, fake_server):
    _, state = fake_server
    client.regions()
    h = {k.lower(): v for k, v in state.requests[-1]["headers"].items()}
    assert h["user-agent"] == f"korp-map-client/{korp_map_client.__version__}"
    offered = {p.strip() for p in h["accept-encoding"].split(",")}
    assert "gzip" in offered
    if importlib.util.find_spec("zstandard"):
        assert "zstd" in offered
    if importlib.util.find_spec("brotli") or importlib.util.find_spec("brotlicffi"):
        assert "br" in offered


@pytest.mark.parametrize("enc", ["gzip", "br", "zstd", "identity"])
def test_content_encodings(fake_server, enc):
    if enc == "br" and not (importlib.util.find_spec("brotli") or importlib.util.find_spec("brotlicffi")):
        pytest.skip("brotli not installed")
    if enc == "zstd" and not importlib.util.find_spec("zstandard"):
        pytest.skip("zstandard not installed")
    url, state = fake_server
    state.force_encoding = enc
    c = korp_map_client.Client(url)
    res = c.map("areas", BBOX, lod=14)
    assert res.table.equals(make_table("areas"))
    assert c.geocode("Drottninggatan 53", max=1)[0]["housenumber"] == "53"


def test_gzip_only_client(fake_server):
    url, state = fake_server
    c = korp_map_client.Client(url, headers={"accept-encoding": "gzip"})
    assert c.map("lines", BBOX, lod=14).num_rows == len(ROWS["lines"])
    assert state.requests[-1]["headers"]["accept-encoding"] == "gzip"


def test_error_carries_code(client):
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        client.map("lines", BBOX, lod=14, region="atlantis")
    e = ei.value
    assert e.code == "korp-map-108" and e.status == 404
    assert "atlantis" in e.message and "korp-map-108" in str(e)


def test_gzipped_error_body(fake_server):
    url, state = fake_server
    state.force_encoding = "gzip"
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        korp_map_client.Client(url).geocode("   ")
    assert ei.value.code == "korp-map-103" and ei.value.status == 400


def test_non_json_error(client):
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        client._get("/v1/boom")
    assert ei.value.code is None and ei.value.status == 500


def test_wrong_content_type(client):
    with pytest.raises(korp_map_client.KorpMapError, match="expected application/vnd.apache.arrow.stream"):
        client.map("points", BBOX, lod=14, region="other")


def test_transport_error():
    c = korp_map_client.Client("http://127.0.0.1:9", timeout=2)
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        c.regions()
    assert ei.value.code is None and ei.value.status is None


def test_bad_args(client):
    with pytest.raises(ValueError):
        client.map("roads", BBOX, lod=14)  # type: ignore[arg-type]
    with pytest.raises(ValueError):
        client.map("lines", (1, 2, 3), lod=14)


def test_geocode(client, fake_server):
    _, state = fake_server
    hits = client.geocode("Drottninggatan 53 Stockholm", max=5)
    assert len(hits) == 2 and hits[0]["city"] == "Stockholm" and hits[0]["score"] >= hits[1]["score"]
    assert state.requests[-1]["query"] == {"region": "testland", "q": "Drottninggatan 53 Stockholm", "max": "5"}
    assert client.geocode("nowhere at all") == []
    assert len(client.geocode("Drottninggatan", max=1)) == 1


def test_revgeocode(client):
    hit = client.revgeocode(18.07, 59.33)
    assert hit is not None and hit["street"] == "Jakobs Torg" and hit["distance_m"] == pytest.approx(11.85)
    assert client.revgeocode(0.0, 0.0) is None
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        client.revgeocode(500.0, 59.0)
    assert ei.value.code == "korp-map-115"


# -- geometry ------------------------------------------------------------------


@geo
def test_points_geometry():
    import shapely

    g = korp_map_client.geometry_to_shapely(make_table("points").column("geometry"), "point")
    assert g[2] is None
    assert shapely.equals(g[0], shapely.Point(18.07, 59.33))
    assert g[3].x == 18.01


@geo
def test_lines_geometry():
    import shapely

    g = korp_map_client.geometry_to_shapely(make_table("lines", chunks=2).column("geometry"), "multilinestring")
    assert g[0].geom_type == "MultiLineString"
    assert shapely.equals(g[1], shapely.MultiLineString([[(18.0, 59.3), (18.05, 59.31), (18.1, 59.3)], [(18.2, 59.2), (18.3, 59.3)]]))
    assert g[2] is None
    assert shapely.equals(g[3], shapely.MultiLineString([[(17.9, 59.2), (17.95, 59.25)]]))


@geo
def test_areas_geometry_with_hole_and_slice():
    import shapely
    from conftest import HOLE, SQUARE, TRI

    col = make_table("areas").column("geometry")
    g = korp_map_client.geometry_to_shapely(col, "multipolygon")
    assert shapely.equals(g[0], shapely.MultiPolygon([(SQUARE, [HOLE])]))
    assert g[0].area == pytest.approx(0.01 - 0.0004)
    assert shapely.equals(g[1], shapely.MultiPolygon([(TRI, []), (SQUARE, [])]))
    assert g[2] is None
    # a sliced array (non-zero offset) must line up
    sliced = col.combine_chunks().slice(1, 3)
    gs = korp_map_client.geometry_to_shapely(sliced)
    assert len(gs) == 3 and shapely.equals(gs[0], g[1]) and gs[1] is None and shapely.equals(gs[2], g[3])


@geo
def test_polygon_by_encoding():
    from conftest import POLY, SQUARE

    arr = pa.array([[[{"x": x, "y": y} for x, y in SQUARE]]], type=POLY)
    assert korp_map_client.geometry_to_shapely(arr, "polygon")[0].geom_type == "Polygon"
    assert korp_map_client.geometry_to_shapely(arr)[0].geom_type == "MultiLineString"
    with pytest.raises(TypeError):
        korp_map_client.geometry_to_shapely(arr, "multipolygon")


@geo
@pytest.mark.parametrize("kind,gtype", [("points", "Point"), ("lines", "MultiLineString"), ("areas", "MultiPolygon")])
def test_map_gdf(client, kind, gtype):
    gdf = client.map_gdf(kind, BBOX, lod=14, max=2)
    assert gdf.crs.to_epsg() == 4326
    assert list(gdf.columns) == ["id", "tags", "min_zoom", "geometry"]
    assert len(gdf) == 2 and set(gdf.geom_type.dropna()) == {gtype}
    assert gdf.attrs["truncated"] is True and gdf.attrs["data_version"] == "files-test0001"


@geo
def test_empty_gdf(client):
    gdf = client.map_gdf("areas", BBOX, lod=14, max=0)
    assert len(gdf) == 0 and gdf.crs.to_epsg() == 4326


def test_https(fake_tls_server):
    import ssl

    url, state, cert = fake_tls_server
    c = korp_map_client.Client(url, verify=ssl.create_default_context(cafile=cert))
    assert c.regions()[0]["name"] == "testland"
    res = c.map("areas", BBOX, lod=14, max=2)
    assert res.truncated is True and res.num_rows == 2
    with pytest.raises(korp_map_client.KorpMapError) as ei:
        c.map("areas", BBOX, lod=14, region="atlantis")
    assert ei.value.code == "korp-map-108"
    with pytest.raises(korp_map_client.KorpMapError):  # untrusted cert is refused by default
        korp_map_client.Client(url).regions()


def test_default_url_is_the_public_server():
    c = korp_map_client.Client()
    assert c.base_url == korp_map_client.DEFAULT_URL == "https://karta.gunnar.rs"
    c.close()