430 lines
14 KiB
Python
430 lines
14 KiB
Python
"""Tests for the shared location resolution pipeline.
|
|
|
|
Validates the abstraction itself: the protocol contract, the orchestrator,
|
|
each built-in resolver, and the pluggability promise (a custom resolver can
|
|
be slotted in without touching consumers).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from app.services.location import (
|
|
InheritFromAnotherEntityResolver,
|
|
LocationCandidate,
|
|
LocationPipeline,
|
|
LocationQuery,
|
|
NominatimResolver,
|
|
RegistryResolver,
|
|
ResolverOutput,
|
|
SourceCoordinatesResolver,
|
|
)
|
|
|
|
|
|
# ── Test fixtures ────────────────────────────────────────────────────
|
|
|
|
|
|
@pytest.fixture
|
|
def tmp_registry(tmp_path: Path) -> Path:
|
|
payload = {
|
|
"locations": [
|
|
{
|
|
"canonical_name": "Test Site Alpha",
|
|
"aliases": ["alpha", "alpha-one", "Acme HQ"],
|
|
"operator": "Acme Networks",
|
|
"site": "Acme HQ",
|
|
"city": "Lyon",
|
|
"country": "France",
|
|
"latitude": 45.764,
|
|
"longitude": 4.8357,
|
|
"precision": "site",
|
|
"confidence": 0.92,
|
|
"source_note": "Test fixture",
|
|
"verified_at": "2026-05-08",
|
|
},
|
|
{
|
|
"canonical_name": "Test Site Bravo",
|
|
"aliases": ["bravo"],
|
|
"operator": "Acme Networks",
|
|
"site": "Bravo POP",
|
|
"city": "Berlin",
|
|
"country": "Germany",
|
|
"latitude": 52.52,
|
|
"longitude": 13.405,
|
|
"precision": "city",
|
|
"confidence": 0.85,
|
|
},
|
|
],
|
|
"city_fallbacks": [
|
|
{
|
|
"city": "Bhutan-Capital",
|
|
"country": "Bhutan",
|
|
"latitude": 27.4728,
|
|
"longitude": 89.639,
|
|
"precision": "city",
|
|
"confidence": 0.5,
|
|
}
|
|
],
|
|
}
|
|
path = tmp_path / "registry.json"
|
|
path.write_text(json.dumps(payload), encoding="utf-8")
|
|
return path
|
|
|
|
|
|
# ── SourceCoordinatesResolver ────────────────────────────────────────
|
|
|
|
|
|
def test_source_coordinates_resolver_passes_through_valid_coordinates():
|
|
resolver = SourceCoordinatesResolver()
|
|
query = LocationQuery(
|
|
name="Acme HQ",
|
|
source_latitude=45.0,
|
|
source_longitude=4.0,
|
|
country="France",
|
|
)
|
|
output = resolver.resolve(query)
|
|
assert len(output.candidates) == 1
|
|
candidate = output.candidates[0]
|
|
assert candidate.latitude == 45.0
|
|
assert candidate.longitude == 4.0
|
|
assert candidate.precision == "precise"
|
|
assert candidate.source == "source_coordinates"
|
|
assert candidate.needs_confirmation is False
|
|
|
|
|
|
def test_source_coordinates_resolver_skips_zero_coordinates():
|
|
resolver = SourceCoordinatesResolver()
|
|
output = resolver.resolve(
|
|
LocationQuery(name="X", source_latitude=0.0, source_longitude=0.0)
|
|
)
|
|
assert output.candidates == ()
|
|
|
|
|
|
def test_source_coordinates_resolver_skips_when_missing():
|
|
resolver = SourceCoordinatesResolver()
|
|
output = resolver.resolve(LocationQuery(name="X"))
|
|
assert output.candidates == ()
|
|
|
|
|
|
# ── RegistryResolver ─────────────────────────────────────────────────
|
|
|
|
|
|
def test_registry_resolver_matches_alias(tmp_registry):
|
|
resolver = RegistryResolver(registry_path=tmp_registry)
|
|
resolver.reload()
|
|
output = resolver.resolve(
|
|
LocationQuery(name="alpha", country="France")
|
|
)
|
|
candidates = list(output.candidates)
|
|
assert candidates, "should match registry entry"
|
|
assert any(c.matched_location_name == "Test Site Alpha" for c in candidates)
|
|
alpha = next(c for c in candidates if c.matched_location_name == "Test Site Alpha")
|
|
assert alpha.precision == "site"
|
|
assert alpha.confidence == pytest.approx(0.92)
|
|
assert alpha.needs_confirmation is True
|
|
assert alpha.location_verified_at is None
|
|
|
|
|
|
def test_registry_resolver_filters_country_mismatch(tmp_registry):
|
|
resolver = RegistryResolver(registry_path=tmp_registry)
|
|
resolver.reload()
|
|
# alpha is in France; query says Spain → should reject
|
|
output = resolver.resolve(
|
|
LocationQuery(name="alpha", country="Spain")
|
|
)
|
|
assert all(
|
|
c.matched_location_name != "Test Site Alpha" for c in output.candidates
|
|
)
|
|
|
|
|
|
def test_registry_resolver_emits_city_fallback_candidate(tmp_registry):
|
|
resolver = RegistryResolver(registry_path=tmp_registry)
|
|
resolver.reload()
|
|
output = resolver.resolve(
|
|
LocationQuery(city="Bhutan-Capital", country="Bhutan")
|
|
)
|
|
candidates = list(output.candidates)
|
|
assert candidates, "city fallback should fire"
|
|
assert any(c.source == "local_registry_city" for c in candidates)
|
|
|
|
|
|
# ── NominatimResolver ───────────────────────────────────────────────
|
|
|
|
|
|
def test_nominatim_resolver_calls_geocoder_with_plan_queries():
|
|
calls = []
|
|
|
|
def fake_geocoder(query: str):
|
|
calls.append(query)
|
|
return {
|
|
"lat": "12.34",
|
|
"lon": "56.78",
|
|
"display_name": "Test City, Country",
|
|
"address": {"city": "Test City", "country": "Country"},
|
|
}
|
|
|
|
def plan(query: LocationQuery):
|
|
return [
|
|
("primary query", ("name",)),
|
|
("secondary query", ("city",)),
|
|
]
|
|
|
|
resolver = NominatimResolver(
|
|
query_plan_builder=plan,
|
|
geocoder=fake_geocoder,
|
|
)
|
|
output = resolver.resolve(LocationQuery(name="X", country="Country"))
|
|
assert calls == ["primary query", "secondary query"]
|
|
assert output.attempted_queries == ("primary query", "secondary query")
|
|
assert len(output.candidates) == 2
|
|
assert all(c.precision == "city" for c in output.candidates)
|
|
assert all(c.needs_confirmation for c in output.candidates)
|
|
|
|
|
|
def test_nominatim_resolver_skips_when_geocoder_returns_none():
|
|
resolver = NominatimResolver(
|
|
query_plan_builder=lambda q: [("only", ("name",))],
|
|
geocoder=lambda q: None,
|
|
)
|
|
output = resolver.resolve(LocationQuery(name="X"))
|
|
assert output.candidates == ()
|
|
assert output.attempted_queries == ("only",)
|
|
|
|
|
|
def test_nominatim_resolver_swallows_exceptions_per_query():
|
|
def boom(query):
|
|
raise RuntimeError("network down")
|
|
|
|
resolver = NominatimResolver(
|
|
query_plan_builder=lambda q: [("a", ()), ("b", ())],
|
|
geocoder=boom,
|
|
)
|
|
output = resolver.resolve(LocationQuery(name="X"))
|
|
assert output.candidates == ()
|
|
assert output.attempted_queries == ("a", "b")
|
|
|
|
|
|
# ── InheritFromAnotherEntityResolver ────────────────────────────────
|
|
|
|
|
|
def test_inherit_resolver_returns_provided_candidate():
|
|
sentinel = LocationCandidate(
|
|
latitude=10.0,
|
|
longitude=20.0,
|
|
display_name="Inherited",
|
|
precision="city",
|
|
confidence=0.7,
|
|
query="inherit::test",
|
|
source="inherited",
|
|
source_note=None,
|
|
matched_fields=("collector",),
|
|
needs_confirmation=False,
|
|
)
|
|
resolver = InheritFromAnotherEntityResolver(
|
|
source_lookup=lambda q: sentinel
|
|
)
|
|
output = resolver.resolve(LocationQuery(name="X"))
|
|
assert output.candidates == (sentinel,)
|
|
|
|
|
|
def test_inherit_resolver_skips_when_lookup_returns_none():
|
|
resolver = InheritFromAnotherEntityResolver(source_lookup=lambda q: None)
|
|
assert resolver.resolve(LocationQuery(name="X")).candidates == ()
|
|
|
|
|
|
# ── LocationPipeline orchestration ──────────────────────────────────
|
|
|
|
|
|
def test_pipeline_aggregates_candidates_across_resolvers(tmp_registry):
|
|
pipeline = LocationPipeline(
|
|
[
|
|
SourceCoordinatesResolver(),
|
|
RegistryResolver(registry_path=tmp_registry),
|
|
NominatimResolver(
|
|
query_plan_builder=lambda q: [("nominatim attempt", ("name",))],
|
|
geocoder=lambda q: {
|
|
"lat": "1.0",
|
|
"lon": "2.0",
|
|
"display_name": "Online City",
|
|
"address": {"city": "Online City", "country": "France"},
|
|
},
|
|
),
|
|
]
|
|
)
|
|
pipeline.resolvers[1].reload()
|
|
candidates, attempted = pipeline.collect_candidates(
|
|
LocationQuery(
|
|
name="alpha",
|
|
country="France",
|
|
source_latitude=44.0,
|
|
source_longitude=5.0,
|
|
)
|
|
)
|
|
sources = {c.source for c in candidates}
|
|
assert "source_coordinates" in sources
|
|
assert "local_registry" in sources
|
|
assert "nominatim_online_geocode" in sources
|
|
assert "nominatim attempt" in attempted
|
|
|
|
|
|
def test_pipeline_dedupes_by_source_and_coordinates():
|
|
same = LocationCandidate(
|
|
latitude=1.0,
|
|
longitude=2.0,
|
|
display_name="dup",
|
|
precision="city",
|
|
confidence=0.5,
|
|
query="x",
|
|
source="dup_source",
|
|
source_note=None,
|
|
matched_fields=(),
|
|
needs_confirmation=False,
|
|
)
|
|
|
|
class _DupResolver:
|
|
name = "dup_source"
|
|
|
|
def resolve(self, query):
|
|
return ResolverOutput(candidates=(same, same))
|
|
|
|
pipeline = LocationPipeline([_DupResolver()])
|
|
candidates, _ = pipeline.collect_candidates(LocationQuery(name="X"))
|
|
assert len(candidates) == 1
|
|
|
|
|
|
def test_registry_short_aliases_do_not_match_inside_larger_tokens(tmp_path: Path):
|
|
registry_path = tmp_path / "registry.json"
|
|
registry_path.write_text(
|
|
json.dumps(
|
|
{
|
|
"locations": [
|
|
{
|
|
"canonical_name": "Aurora",
|
|
"aliases": ["Aurora", "ANL"],
|
|
"site": "DOE/SC/Argonne National Laboratory",
|
|
"country": "United States",
|
|
"city": "Lemont",
|
|
"latitude": 41.713,
|
|
"longitude": -87.982,
|
|
"precision": "site",
|
|
},
|
|
{
|
|
"canonical_name": "Venado",
|
|
"aliases": ["Venado"],
|
|
"site": "DOE/NNSA/LANL",
|
|
"country": "United States",
|
|
"city": "Los Alamos",
|
|
"latitude": 35.8443,
|
|
"longitude": -106.2872,
|
|
"precision": "site",
|
|
},
|
|
],
|
|
"city_fallbacks": [],
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
resolver = RegistryResolver(registry_path=registry_path)
|
|
resolver.reload()
|
|
|
|
output = resolver.resolve(
|
|
LocationQuery(
|
|
name="Venado",
|
|
country="United States",
|
|
extra={"site": "DOE/NNSA/LANL"},
|
|
)
|
|
)
|
|
|
|
assert len(output.candidates) == 1
|
|
assert output.candidates[0].matched_location_name == "Venado"
|
|
|
|
|
|
def test_pipeline_resolve_best_returns_highest_priority():
|
|
online = LocationCandidate(
|
|
latitude=10.0,
|
|
longitude=20.0,
|
|
display_name="online",
|
|
precision="city",
|
|
confidence=0.9,
|
|
query="x",
|
|
source="nominatim_online_geocode",
|
|
source_note=None,
|
|
matched_fields=(),
|
|
needs_confirmation=True,
|
|
)
|
|
source = LocationCandidate(
|
|
latitude=11.0,
|
|
longitude=21.0,
|
|
display_name="src",
|
|
precision="precise",
|
|
confidence=1.0,
|
|
query="x",
|
|
source="source_coordinates",
|
|
source_note=None,
|
|
matched_fields=(),
|
|
needs_confirmation=False,
|
|
)
|
|
|
|
class _StubResolver:
|
|
def __init__(self, c, name):
|
|
self._c = c
|
|
self.name = name
|
|
|
|
def resolve(self, query):
|
|
return ResolverOutput(candidates=(self._c,))
|
|
|
|
pipeline = LocationPipeline(
|
|
[
|
|
_StubResolver(online, "online"),
|
|
_StubResolver(source, "src"),
|
|
]
|
|
)
|
|
result = pipeline.resolve_best(LocationQuery(name="X"))
|
|
assert result.location is source, "source_coordinates should beat nominatim"
|
|
|
|
|
|
def test_pipeline_returns_diagnostic_when_nothing_resolves():
|
|
pipeline = LocationPipeline([SourceCoordinatesResolver()])
|
|
result = pipeline.resolve_best(LocationQuery(name="X", country="Bhutan"))
|
|
assert result.location is None
|
|
assert result.diagnostic is not None
|
|
assert result.diagnostic.country == "Bhutan"
|
|
|
|
|
|
def test_pluggability_custom_resolver_works_without_changing_pipeline():
|
|
"""Validates the abstraction promise: a new algorithm = a new class."""
|
|
|
|
class _PeeringDBStubResolver:
|
|
name = "fake_peeringdb"
|
|
|
|
def resolve(self, query):
|
|
asn = (query.extra or {}).get("asn")
|
|
if asn != 174:
|
|
return ResolverOutput()
|
|
return ResolverOutput(
|
|
candidates=(
|
|
LocationCandidate(
|
|
latitude=1.0,
|
|
longitude=2.0,
|
|
display_name="Cogent HQ",
|
|
precision="site",
|
|
confidence=0.8,
|
|
query=f"peeringdb::{asn}",
|
|
source="peeringdb_stub",
|
|
source_note="Stub for testing",
|
|
matched_fields=("asn",),
|
|
needs_confirmation=False,
|
|
),
|
|
)
|
|
)
|
|
|
|
pipeline = LocationPipeline([_PeeringDBStubResolver()])
|
|
candidates, _ = pipeline.collect_candidates(
|
|
LocationQuery(name="X", extra={"asn": 174})
|
|
)
|
|
assert len(candidates) == 1
|
|
assert candidates[0].source == "peeringdb_stub"
|