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

nordisk/korp-map

demo/sverigekartan/test_app.py

"""Streamlit AppTest for Sverigekartan, against the LIVE map server.

    SVERIGEKARTAN_MAP_SERVER_INTERNAL=http://127.0.0.1:8765 python -m pytest test_app.py

Against a v3 server (contract korp-map-v3.0; korp-map-client >= 0.3), with the
addresses from a v1.2 server while the v3 cut has no address index:

    SVERIGEKARTAN_MAP_SERVER_INTERNAL=http://127.0.0.1:8769 \\
    SVERIGEKARTAN_ADDRESS_FALLBACK=http://127.0.0.1:8765 python -m pytest test_app.py

The browser side (does the map draw) needs a real GPU and is not covered here.
"""

from __future__ import annotations

import json
from pathlib import Path

import pytest
from streamlit.testing.v1 import AppTest

APP = str(Path(__file__).with_name("app.py"))


def _server_is_v3() -> bool:
    import os

    import httpx

    url = os.environ.get("SVERIGEKARTAN_MAP_SERVER_INTERNAL", "http://127.0.0.1:8765").rstrip("/")
    try:
        return int(str(httpx.get(f"{url}/openapi.json", timeout=10).json()["info"]["version"]).split(".")[0]) >= 3
    except Exception:
        return False


V3_MODE = _server_is_v3()
AREAS = "v3/areas.parquet" if V3_MODE else "geoparquet2/areas.parquet"


def _map_args(at: AppTest) -> dict:
    (ci,) = at.get("component_instance")
    assert ci.proto.component_name.endswith("facett_map")
    return json.loads(ci.proto.json_args)


@pytest.fixture
def at() -> AppTest:
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    return at


def test_page_renders(at: AppTest) -> None:
    assert at.title[0].value == "Sverigekartan"
    args = _map_args(at)
    assert args["component"] == "osm2d"
    assert args["data"]["region"] == "sweden"
    assert args["data"]["server"].startswith("http")
    assert "bbox" not in args["data"]


def test_footer(at: AppTest) -> None:
    md = " ".join(m.value for m in at.markdown)
    for link in (
        "https://pypi.org/project/facett-map/",
        "https://pypi.org/project/korp-map-client/",
        "https://www.gunnar.rs/nordisk/korp-map",
    ):
        assert link in md
    caps = " ".join(c.value for c in at.caption)
    assert "© OpenStreetMap-bidragsgivare, ODbL" in caps
    assert "dataversion `?`" not in caps
    assert "dataversion `" in caps


def test_show_the_map_howto(at: AppTest) -> None:
    heads = [h.value for h in at.header]
    assert heads[:3] == ["Visa kartan", "Geoexempel i Python", "Data"]
    codes = [c.value for c in at.code]
    assert codes[0] == "pip install facett-map"
    app = codes[1]
    assert "import facett_map" in app and 'facett_map.map("http' in app and 'region="sweden"' in app
    assert len([x for x in app.splitlines() if x.strip()]) <= 6
    assert codes[2] == "streamlit run app.py"
    assert "korp_map_client" not in app and "korp-map-client" not in "".join(codes[:3])
    dl, inst = codes[3].replace("\\\n ", "").splitlines()
    assert dl.startswith("pip download facett-map --python-version 3.11 --only-binary=:all: ") and dl.endswith(" -d wheels/")
    assert "--platform manylinux2014_x86_64" in dl and "--platform manylinux_2_28_x86_64" in dl
    assert inst == "pip install --no-index --find-links wheels/ facett-map"
    assert any(c.value.startswith("Installera på en airgappad dator: hämta alla wheels") for c in at.caption)
    assert any("egen korp-map-server" in c.value and "/v1/files/sweden/" in c.value for c in at.caption)
    # The native Rust viewer: two commands, install and run.
    assert "Rust (egui)" in " ".join(m.value for m in at.markdown)
    assert codes[4] == "cargo install sverigekartan\nsverigekartan"
    assert any(c.value.startswith("Samma karta i ett eget fönster") for c in at.caption)


def test_geo_examples(at: AppTest) -> None:
    codes = [c.value for c in at.code][5:]
    pip = codes.pop(0)
    joined = "\n".join(codes)
    assert "c.geocode(" in joined and "c.revgeocode(" in joined and "duckdb.sql(" in joined
    if V3_MODE:
        assert pip == 'pip install "korp-map-client>=0.3"'
        assert '.map_view("areas", bbox=(17.98, 59.3, 18.12, 59.35), res=10.0).to_geodataframe()' in joined
        assert "lod" not in joined and "geoparquet2" not in joined
    else:
        assert pip == "pip install korp-map-client"
        assert 'c.map_gdf("areas", bbox=(17.98, 59.3, 18.12, 59.35), lod=16)' in joined
        assert "m = Client(" not in joined
    assert f'.read_parquet("{AREAS}"' in joined
    for c in codes:
        assert 1 <= len(c.splitlines()) <= 5, c
    assert "bbox.xmin <= 18.12" in joined and f"/v1/files/sweden/{AREAS}" in joined


def test_swedish_only(at: AppTest) -> None:
    """No English UI text: the old two-language labels are gone."""
    text = " ".join(
        [x.value for x in (*at.caption, *at.markdown, *at.header, *at.subheader, *at.info)]
        + [at.text_input(key="q").label, at.button[0].label]
    )
    for over in ("hjul", "på distans", "rutan", "Kartans format", "utan nät", "nätlös", "Offline", "adressök"):
        assert over not in text, over
    for en in ("Search", "Show", "Click the map", "Nearest", "Download", "Query", "coming soon", "The map needs", "No address", "Lookup"):
        assert en not in text, en


def test_switch_2d_3d(at: AppTest) -> None:
    at.button_group(key="mode").set_value("3D").run()
    assert not at.exception
    args = _map_args(at)
    assert args["component"] == "osm3d"
    assert args["key"].startswith("map-3d-")
    minlon, minlat, maxlon, maxlat = args["data"]["bbox"]  # 3D opens on Stockholm
    assert minlon < 18.0686 < maxlon and minlat < 59.3324 < maxlat
    at.button_group(key="mode").set_value("2D").run()
    assert _map_args(at)["component"] == "osm2d"


def test_search_moves_map(at: AppTest) -> None:
    at.text_input(key="q").input("Drottninggatan 53 Stockholm")
    at.button[0].click().run()
    assert not at.exception, at.exception
    hits = at.radio(key="hit_pick")
    assert len(hits.options) >= 1
    assert hits.options[0].startswith("Drottninggatan 53")
    assert "Stockholm" in hits.options[0]
    args = _map_args(at)
    minlon, minlat, maxlon, maxlat = args["data"]["bbox"]
    assert minlon < 18.0619 < maxlon and minlat < 59.3334 < maxlat
    key1 = args["key"]
    # Another hit moves the map again, under a new key (a fresh viewer on the new bbox).
    if len(hits.options) > 1:
        at.radio(key="hit_pick").set_value(1).run()
        args2 = _map_args(at)
        assert args2["key"] != key1
        assert args2["data"]["bbox"] != args["data"]["bbox"]
    # The view survives a 2D/3D switch.
    at.button_group(key="mode").set_value("3D").run()
    args3 = _map_args(at)
    assert args3["component"] == "osm3d" and "bbox" in args3["data"]


def test_search_no_match(at: AppTest) -> None:
    at.text_input(key="q").input("Qxzqxzqxz 999999 Ingenstans")
    at.button[0].click().run()
    assert not at.exception
    assert any(i.value == "Ingen träff" for i in at.info)


# -- the browser's map server follows the page's host ---------------------------------

import origin


def test_map_server_follows_host() -> None:
    hosts = origin.public_hosts(None)
    assert hosts == ["karta.gunnar.rs", "sverigekartan.gunnar.rs", "83-190-65-118.sslip.io"]
    f = origin.map_server_for
    assert f("sverigekartan.gunnar.rs", None, hosts) == "https://sverigekartan.gunnar.rs"
    assert f("83-190-65-118.sslip.io", None, hosts) == "https://83-190-65-118.sslip.io"
    assert f("karta.gunnar.rs", None, hosts) == "https://karta.gunnar.rs"
    assert f("SverigeKartan.Gunnar.RS:443", None, hosts) == "https://sverigekartan.gunnar.rs"
    for other in ("localhost:8501", "203.0.113.5:8501", "evil.example", "", None, "[::1]:8501"):
        assert f(other, None, hosts) == "https://karta.gunnar.rs", other
    assert f("sverigekartan.gunnar.rs", "http://x:8765/", hosts) == "http://x:8765"
    assert origin.public_hosts("a.example, B.example.") == ["a.example", "b.example"]


def test_page_default_map_server(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("SVERIGEKARTAN_MAP_SERVER", raising=False)
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    assert _map_args(at)["data"]["server"] == "https://karta.gunnar.rs"


# -- the Data section ----------------------------------------------------------------

import http.server
import threading

import data_files

# The server's shape: {name, format, size, sha256, url}.
GP2_INDEX = [
    {"name": "geoparquet2/areas.parquet", "format": "geoparquet-2.0", "size": 605095955},
    {"name": "geoparquet2/points.parquet", "format": "geoparquet-2.0", "size": 891670047},
    {"name": "geoparquet2/lines.parquet", "format": "geoparquet-2.0", "size": 472935902},
    {"name": "native/nodes.point.parquet", "format": "geoparquet-1.1-native", "size": 957337911},
    {"name": "native/ways.multilinestring.parquet", "format": "geoparquet-1.1-native", "size": 563859979},
    {"name": "native/ways.multipolygon.parquet", "format": "geoparquet-1.1-native", "size": 628865824},
    {"name": "native/relations.resolved.multipolygon.parquet", "format": "geoparquet-1.1-native", "size": 255162225},
    {"name": "README.txt", "format": "text", "size": 10},
]
for _e in GP2_INDEX:
    _e["sha256"] = "0" * 64
    _e["url"] = "/v1/files/sweden/" + _e["name"]


class _Fake(http.server.BaseHTTPRequestHandler):
    body = b"[]"
    ctype = "application/json"
    status = 200

    def do_GET(self) -> None:  # noqa: N802
        if self.path != "/v1/files/sweden/":
            self.send_error(404)
            return
        self.send_response(self.status)
        self.send_header("content-type", self.ctype)
        self.send_header("content-length", str(len(self.body)))
        self.end_headers()
        self.wfile.write(self.body)

    def log_message(self, *a: object) -> None:
        pass


@pytest.fixture
def fake_index(monkeypatch: pytest.MonkeyPatch):
    import streamlit as st

    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Fake)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    monkeypatch.setenv("SVERIGEKARTAN_FILES_INDEX", f"http://127.0.0.1:{srv.server_port}/v1/files/sweden/")
    monkeypatch.setenv("SVERIGEKARTAN_MAP_SERVER", "https://maps.example")
    st.cache_data.clear()
    yield _Fake
    srv.shutdown()
    st.cache_data.clear()


def _all_md(at: AppTest) -> str:
    return "\n".join(m.value for m in at.markdown)


def test_data_listing_json(fake_index) -> None:
    fake_index.body, fake_index.ctype, fake_index.status = json.dumps(GP2_INDEX).encode(), "application/json", 200
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    assert [h.value for h in at.subheader][:2] == ["GeoParquet 2.0", "Native"]
    md = _all_md(at)
    for f in GP2_INDEX[:7]:
        assert f"(https://maps.example/v1/files/sweden/{f['name']})" in md
    assert "605 MB" in md and "957 MB" in md
    assert "| `geoparquet2/points.parquet` | POI, adresser, orter |" in md
    assert "| `native/relations.resolved.multipolygon.parquet` | stora områden som Vänern, nationalparker |" in md
    caps = " ".join(c.value for c in at.caption)
    assert "Varje fil är ett lager för hela Sverige" in caps and "≈2,0 GB" in caps and "≈2,4 GB" in caps
    assert md.index("geoparquet2/points.parquet") < md.index("geoparquet2/lines.parquet") < md.index("geoparquet2/areas.parquet")
    assert "README.txt" not in md
    assert "[Ladda ner](https://maps.example/v1/files/sweden/geoparquet2/areas.parquet)" in md
    codes = [c.value for c in at.code]
    assert any(f"FROM 'https://maps.example/v1/files/sweden/{AREAS}'" in c and "bbox.xmin" in c for c in codes)
    assert any(f'.read_parquet("{AREAS}", bbox=(17.98, 59.3, 18.12, 59.35))' in c for c in codes)
    assert not any("kommer snart" in i.value for i in at.info)


V3_INDEX = [
    {"region": "sweden", "set": "v3", "name": n, "format": "korp-map-v3.0", "size": z, "sha256": "0" * 64,
     "url": f"/v1/files/sweden/v3/{n}"}
    for n, z in (("areas.parquet", 546521344), ("land.parquet", 17000000), ("landcover.parquet", 158000000),
                 ("lines.parquet", 341000000), ("points.parquet", 52000000))
]


def test_data_listing_v3(fake_index) -> None:
    fake_index.body, fake_index.ctype, fake_index.status = json.dumps(V3_INDEX).encode(), "application/json", 200
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    assert [h.value for h in at.subheader] == ["Kartdata v3"]
    md = _all_md(at)
    rows = [line for line in md.splitlines() if line.startswith("| `v3/")]
    assert [r.split("`")[1] for r in rows] == [
        "v3/points.parquet", "v3/lines.parquet", "v3/areas.parquet", "v3/land.parquet", "v3/landcover.parquet"
    ]
    assert "| `v3/land.parquet` | landbas |" in md
    assert "| `v3/landcover.parquet` | generaliserat marktäcke |" in md
    assert "| `v3/points.parquet` | POI, adresser, orter |" in md
    caps = " ".join(c.value for c in at.caption)
    assert "Varje fil är ett lager för hela Sverige, ≈1,1 GB totalt." in caps
    assert "Övrigt" not in [h.value for h in at.subheader]


def _v3_has_addresses() -> bool:
    import os

    import httpx

    url = os.environ.get("SVERIGEKARTAN_MAP_SERVER_INTERNAL", "").rstrip("/")
    r = httpx.get(f"{url}/v1/revgeocode", params={"region": "sweden", "lon": "18.0686", "lat": "59.3324"}, timeout=10)
    return not (r.status_code == 404 and "korp-map-116" in r.text)


@pytest.mark.skipif(not V3_MODE, reason="needs a v3 map server")
def test_v3_addresses_follow_the_cut(monkeypatch: pytest.MonkeyPatch) -> None:
    """With a fallback: addresses from it while the v3 cut has none, named in the
    examples. Without one: the search says it failed, and the examples name the v3 server."""
    import os

    import streamlit as st

    own = _v3_has_addresses()
    fallback = os.environ.get("SVERIGEKARTAN_ADDRESS_FALLBACK")
    for fb in ([fallback] if fallback else []) + [None]:
        if fb:
            monkeypatch.setenv("SVERIGEKARTAN_ADDRESS_FALLBACK", fb)
        else:
            monkeypatch.delenv("SVERIGEKARTAN_ADDRESS_FALLBACK", raising=False)
        st.cache_data.clear()
        st.cache_resource.clear()
        at = AppTest.from_file(APP, default_timeout=60).run()
        at.text_input(key="q").input("Drottninggatan 53 Stockholm")
        at.button[0].click().run()
        assert not at.exception, at.exception
        codes = "\n".join(c.value for c in at.code)
        if own or fb:
            assert not at.error and at.radio(key="hit_pick").options[0].startswith("Drottninggatan 53")
        else:
            assert [e.value for e in at.error] == ["Sökningen misslyckades. Försök igen."]
        if fb and not own:
            assert 'c = Client("https://karta.gunnar.rs", region="sweden")' in codes
            assert "m = Client(" in codes and "m.map_view(" in codes and "m.read_parquet(" in codes
        else:
            assert "m = Client(" not in codes
    st.cache_data.clear()
    st.cache_resource.clear()


def test_data_listing_html(fake_index) -> None:
    html = '<a href="geoparquet2/areas.parquet">areas</a> <a href="nodes.point.parquet">n</a> <a href="../">up</a>'
    fake_index.body, fake_index.ctype, fake_index.status = html.encode(), "text/html", 200
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    md = _all_md(at)
    assert "(https://maps.example/v1/files/sweden/geoparquet2/areas.parquet)" in md
    assert "(https://maps.example/v1/files/sweden/nodes.point.parquet)" in md


def test_data_coming_soon(fake_index) -> None:
    fake_index.body, fake_index.ctype, fake_index.status = b'{"error":"no"}', "application/json", 404
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    assert any(i.value == "Filerna kommer snart." for i in at.info)
    assert not any("Ladda ner" in m.value for m in at.markdown)
    # the rest of the page is still there
    assert _map_args(at)["component"] == "osm2d"


def test_data_live(at: AppTest) -> None:
    """Against the live server: either its file index or the coming-soon note, never an error."""
    soon = any("kommer snart" in i.value for i in at.info)
    links = "/v1/files/sweden/" in _all_md(at)
    assert soon or links
    assert not at.error


def test_parse_index_shapes() -> None:
    base, pub = "http://h/v1/files/sweden/", "https://p/v1/files/sweden"
    shapes = [
        json.dumps({"files": [{"name": "geoparquet2/areas.parquet", "bytes": 5}]}),
        json.dumps({"geoparquet2/areas.parquet": 5}),
        json.dumps([{"name": "areas.parquet", "size": 5, "url": "/v1/files/sweden/geoparquet2/areas.parquet"}]),
        json.dumps([{"key": "geoparquet2/areas.parquet", "length": 5, "href": "http://h/v1/files/sweden/geoparquet2/areas.parquet"}]),
    ]
    for body in shapes:
        (f,) = data_files.parse_index(body, "application/json", base, pub)
        assert f.path == "geoparquet2/areas.parquet", body
        assert f.url == "https://p/v1/files/sweden/geoparquet2/areas.parquet"
        assert f.size == 5 and f.group == data_files.GP2
    (n,) = data_files.parse_index('[{"path": "ways.multipolygon.parquet"}]', "application/json", base, pub)
    assert n.group == data_files.NATIVE and n.size is None
    # format, not the name, picks the set
    body = json.dumps([
        {"name": "x/areas.parquet", "format": "geoparquet-1.1-native", "size": 1, "sha256": "ab", "url": "http://h/v1/files/sweden/x/areas.parquet"},
        {"name": "native/nodes.point.parquet", "format": "geoparquet-2.0", "size": 2, "sha256": "cd", "url": "http://h/v1/files/sweden/native/nodes.point.parquet"},
        {"name": "y/z.parquet", "format": "something-new", "size": 3},
    ])
    groups = data_files.by_group(data_files.parse_index(body, "application/json", base, pub))
    assert [f.path for f in groups[data_files.NATIVE]] == ["x/areas.parquet"]
    assert [f.path for f in groups[data_files.GP2]] == ["native/nodes.point.parquet"]
    assert [f.path for f in groups[data_files.OTHER]] == ["y/z.parquet"]
    assert groups[data_files.NATIVE][0].sha256 == "ab"
    assert data_files.human_size(605095955) == "605 MB"
    assert data_files.human_size(1_200_000_000) == "1.2 GB"


# -- a map that reports its view and clicks (facett-map 0.3.1 contract), faked ---------

import facett_map


class FakeMap:
    """Stands in for facett_map.map: records each call, returns the state set per mode."""

    def __init__(self) -> None:
        self.calls: list[dict] = []
        self.state: dict[str, dict | None] = {}
        self.seen: set[str | None] = set()

    def __call__(self, server, region="sweden", mode="3d", *, bbox=None, center=None, zoom=None,
                 title=None, max=None, height=520, key=None):  # noqa: A002
        self.calls.append(dict(server=server, region=region, mode=mode, bbox=bbox, center=center, zoom=zoom, key=key))
        # A new mount has not drawn yet on its first run: None, as the real map.
        if key not in self.seen:
            self.seen.add(key)
            return None
        return self.state.get(mode)

    @property
    def last(self) -> dict:
        return self.calls[-1]


@pytest.fixture
def fake_map(monkeypatch: pytest.MonkeyPatch) -> FakeMap:
    fm = FakeMap()
    monkeypatch.setattr(facett_map, "map", fm)
    return fm


def _cam(mode, lon, lat, zoom, click=None):
    return {"mode": mode, "bbox": [lon - 0.01, lat - 0.01, lon + 0.01, lat + 0.01], "center": [lon, lat],
            "zoom": zoom, "clicked": click}


def test_no_manual_box_and_a_click_hint(fake_map: FakeMap) -> None:
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.exception, at.exception
    assert not at.number_input, "the manual lon/lat box is still there"
    assert any(c.value == "Klicka på kartan för närmaste adress" for c in at.caption)
    assert fake_map.last["mode"] == "2d" and fake_map.last["center"] is None and fake_map.last["bbox"] is None


def test_click_nearest_address(fake_map: FakeMap) -> None:
    fake_map.state["2d"] = _cam("2d", 18.06, 59.335, 15, {"lon": 18.06, "lat": 59.335, "seq": 1})
    at = AppTest.from_file(APP, default_timeout=60).run()
    assert not at.success  # the map has not drawn yet
    at.run()
    assert not at.exception, at.exception
    first = at.success[0].value
    assert first.startswith("Närmaste adress: ") and "Drottninggatan" in first and " m)" in first
    # The same click again (same seq), even with other coordinates: no new lookup.
    fake_map.state["2d"] = _cam("2d", 11.9746, 57.7089, 15, {"lon": 11.9746, "lat": 57.7089, "seq": 1})
    at.run()
    assert at.success[0].value == first
    # A new click: a new address.
    fake_map.state["2d"] = _cam("2d", 11.9746, 57.7089, 15, {"lon": 11.9746, "lat": 57.7089, "seq": 2})
    at.run()
    assert at.success[0].value != first


def test_mode_switch_opens_where_the_other_was(fake_map: FakeMap) -> None:
    fake_map.state["2d"] = _cam("2d", 11.97, 57.70, 14)
    at = AppTest.from_file(APP, default_timeout=60).run().run()
    at.button_group(key="mode").set_value("3D").run()
    assert not at.exception, at.exception
    last = fake_map.last
    assert last["mode"] == "3d" and last["bbox"] is None
    assert last["center"] == (11.97, 57.70) and last["zoom"] == 14
    k3 = last["key"]
    # The 3D viewer moves; reruns of the same mount keep its opening payload.
    fake_map.state["3d"] = _cam("3d", 12.0, 57.71, 16)
    at.run()
    assert fake_map.last["key"] == k3 and fake_map.last["center"] == (11.97, 57.70)
    at.button_group(key="mode").set_value("2D").run()
    last = fake_map.last
    assert last["mode"] == "2d" and last["center"] == (12.0, 57.71) and last["zoom"] == 16
    assert last["key"] not in (k3,) and last["key"] != fake_map.calls[0]["key"]


def test_first_3d_from_country_view_opens_on_stockholm(fake_map: FakeMap) -> None:
    fake_map.state["2d"] = _cam("2d", 17.4, 62.9, 4.5)
    at = AppTest.from_file(APP, default_timeout=60).run().run()
    at.button_group(key="mode").set_value("3D").run()
    last = fake_map.last
    assert last["center"] is None
    minlon, minlat, maxlon, maxlat = last["bbox"]
    assert minlon < 18.0686 < maxlon and minlat < 59.3324 < maxlat
    # Later 3D opens follow the camera, even zoomed out.
    at.button_group(key="mode").set_value("2D").run().run()
    at.button_group(key="mode").set_value("3D").run()
    assert fake_map.last["center"] == (17.4, 62.9)


def test_address_then_switch_keeps_the_view(fake_map: FakeMap) -> None:
    at = AppTest.from_file(APP, default_timeout=60).run()
    at.text_input(key="q").input("Drottninggatan 53 Stockholm")
    at.button[0].click().run()
    last = fake_map.last
    minlon, minlat, maxlon, maxlat = last["bbox"]
    assert minlon < 18.0619 < maxlon and minlat < 59.3334 < maxlat and last["center"] is None
    fake_map.state["2d"] = _cam("2d", 18.0619, 59.3334, 16.4)
    at.run()
    at.button_group(key="mode").set_value("3D").run()
    assert fake_map.last["center"] == (18.0619, 59.3334) and fake_map.last["zoom"] == 16.4


def test_switch_right_after_a_search_opens_on_the_address(fake_map: FakeMap) -> None:
    fake_map.state["2d"] = _cam("2d", 17.4, 62.9, 4.5)  # the country view, reported
    at = AppTest.from_file(APP, default_timeout=60).run().run()
    at.text_input(key="q").input("Drottninggatan 53 Stockholm")
    at.button[0].click().run()
    # Switch before the new 2D viewer has reported: the old country camera must not win.
    at.button_group(key="mode").set_value("3D").run()
    last = fake_map.last
    assert last["mode"] == "3d" and last["center"] is None
    minlon, minlat, maxlon, maxlat = last["bbox"]
    assert minlon < 18.0619 < maxlon and minlat < 59.3334 < maxlat


def test_click_far_from_any_address(fake_map: FakeMap) -> None:
    fake_map.state["2d"] = _cam("2d", 17.0, 66.5, 6, {"lon": 17.0, "lat": 66.5, "seq": 1})
    at = AppTest.from_file(APP, default_timeout=60).run().run()
    assert not at.exception, at.exception
    assert not at.success
    assert any(i.value.startswith("Ingen adress inom 1 km (närmast: ") for i in at.info)


def test_a_click_in_a_new_viewer_counts_even_with_the_same_seq(fake_map: FakeMap) -> None:
    fake_map.state["2d"] = _cam("2d", 18.06, 59.335, 15, {"lon": 18.06, "lat": 59.335, "seq": 1})
    at = AppTest.from_file(APP, default_timeout=60).run().run()
    first = at.success[0].value
    # The 3D viewer counts its own clicks from 1 again.
    fake_map.state["3d"] = _cam("3d", 11.9746, 57.7089, 15, {"lon": 11.9746, "lat": 57.7089, "seq": 1})
    at.button_group(key="mode").set_value("3D").run().run()
    assert not at.exception, at.exception
    assert at.success and at.success[0].value != first


def test_search_hits_are_distinct(at: AppTest) -> None:
    at.text_input(key="q").input("Kungsportsavenyen 1 Göteborg")
    at.button[0].click().run()
    opts = at.radio(key="hit_pick").options
    assert len(opts) == len(set(opts)) >= 2, opts
    assert opts[0].startswith("Kungsportsavenyen 1")