crates/korp-map-wire/tests/client.rs
//! The client doors against a running server: HTTP and Flight ask the same queries and
//! get the same replies and the same refusals as an in-process reader of the same source.
mod common;
use std::sync::Arc;
use common::*;
use korp_map_wire::{
BBox, Code, FakeMapClient, FlightMapClient, GeocodeQuery, GeocodeReply, HttpMapClient, Kind,
MapClient, MapQuery, MapSource, Region, ReplyMeta, RevGeocodeQuery, RevGeocodeReply,
ServerConfig, SourceClient,
};
fn doors(s: &TestServer) -> Vec<(&'static str, Box<dyn MapClient>)> {
let base = format!("http://{}", s.addr);
vec![
("http", Box::new(HttpMapClient::new(&base))),
("flight", Box::new(FlightMapClient::new(&base).unwrap())),
("in-process", Box::new(SourceClient::new(s.source.clone()))),
]
}
fn q(region: &str, bbox: [f64; 4], lod: u8, kind: Kind, max: Option<u64>) -> MapQuery {
MapQuery {
region: region.to_string(),
bbox: BBox::new(bbox[0], bbox[1], bbox[2], bbox[3]).unwrap(),
lod,
kind,
max,
}
}
#[tokio::test(flavor = "multi_thread")]
async fn every_door_gives_the_same_reply_as_the_raw_http_body() {
let s = TestServer::start(ServerConfig::default()).await;
for kind in Kind::ALL {
for (bbox, lod, max) in [
([11.0, 55.0, 14.2, 57.1], 12, None),
([10.0, 55.0, 20.0, 65.0], 15, None),
([10.0, 55.0, 20.0, 65.0], 15, Some(9)),
([0.0, 0.0, 1.0, 1.0], 12, None),
] {
let max_q = max.map(|m| format!("&max={m}")).unwrap_or_default();
let raw = get(&s.url(&format!(
"/v1/map/{kind}?region={REGION}&bbox={},{},{},{}&lod={lod}{max_q}",
bbox[0], bbox[1], bbox[2], bbox[3]
)))
.await;
assert_eq!(raw.status, 200);
let (schema, batches) = decode(&raw.body);
for (door, c) in doors(&s) {
let r = c.query(&q(REGION, bbox, lod, kind, max)).await.unwrap();
assert_eq!(
*r.schema, *schema,
"{door} {kind} {bbox:?}: schema and metadata"
);
assert_eq!(r.batches, batches, "{door} {kind} {bbox:?}: rows");
assert_eq!(
Some(r.meta.clone()),
ReplyMeta::from_metadata(schema.metadata()),
"{door} {kind} {bbox:?}: the meta is the schema's"
);
}
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn every_door_lists_the_same_regions_and_is_healthy() {
let s = TestServer::start(ServerConfig::default()).await;
let want = MapSource::regions(&*s.source).unwrap();
for (door, c) in doors(&s) {
c.health().await.unwrap_or_else(|e| panic!("{door}: {e}"));
assert_eq!(c.regions().await.unwrap(), want, "{door}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn every_door_gives_the_same_refusal() {
let s = TestServer::start(ServerConfig::default()).await;
for (asked, code) in [
(
q("atlantis", [11.0, 55.0, 14.0, 57.0], 12, Kind::Lines, None),
Code::UnknownRegion,
),
(
q(REGION, [11.0, 55.0, 14.0, 57.0], 31, Kind::Points, None),
Code::BadLod,
),
(
q(REGION, [11.0, 55.0, 14.0, 57.0], 12, Kind::Areas, Some(0)),
Code::BadMax,
),
] {
let mut seen = Vec::new();
for (door, c) in doors(&s) {
let e = c.query(&asked).await.expect_err(door);
assert_eq!(e.code, code, "{door}: {e}");
seen.push(e);
}
assert!(
seen.windows(2).all(|w| w[0] == w[1]),
"the same code AND the same sentence on every door: {seen:?}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_server_that_is_not_there_is_unreachable_on_both_wires() {
// Bind and drop: a port nothing listens on.
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let base = format!("http://127.0.0.1:{port}");
let wires: Vec<(&str, Box<dyn MapClient>)> = vec![
("http", Box::new(HttpMapClient::new(&base))),
("flight", Box::new(FlightMapClient::new(&base).unwrap())),
];
for (door, c) in wires {
let e = c.regions().await.expect_err(door);
assert_eq!(e.code, Code::Unreachable, "{door}: {e}");
assert!(
e.message.contains(&base),
"{door}: the sentence names the server: {e}"
);
let e = c
.query(&q(REGION, [11.0, 55.0, 14.0, 57.0], 12, Kind::Lines, None))
.await
.expect_err(door);
assert_eq!(e.code, Code::Unreachable, "{door}: {e}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn the_fake_records_what_it_was_asked_and_refuses_an_unserved_region() {
let s = TestServer::start(ServerConfig::default()).await;
let regions = MapSource::regions(&*s.source).unwrap();
let real = SourceClient::new(s.source.clone());
let lines = real
.query(&q(REGION, [10.0, 55.0, 20.0, 65.0], 15, Kind::Lines, None))
.await
.unwrap();
let fake = Arc::new(FakeMapClient::new(regions.clone()).with_reply(Kind::Lines, lines.clone()));
let asked = q(REGION, [12.0, 56.0, 13.0, 57.0], 9, Kind::Lines, Some(3));
assert_eq!(fake.query(&asked).await.unwrap(), lines);
assert_eq!(
fake.query(&q(REGION, [12.0, 56.0, 13.0, 57.0], 9, Kind::Points, None))
.await
.unwrap()
.num_rows(),
0,
"a kind with no canned reply is an empty answer"
);
let e = fake
.query(&q(
"atlantis",
[12.0, 56.0, 13.0, 57.0],
9,
Kind::Lines,
None,
))
.await
.unwrap_err();
assert_eq!(e.code, Code::UnknownRegion);
assert_eq!(fake.asked().len(), 3);
assert_eq!(fake.asked()[0], asked);
assert_eq!(fake.regions().await.unwrap(), regions);
}
// ── The address lookups (contract v1.2) ──────────────────────────────────────────────
fn address_doors(s: &AddressServer) -> Vec<(&'static str, Box<dyn MapClient>)> {
let base = format!("http://{}", s.addr);
vec![
("http", Box::new(HttpMapClient::new(&base))),
("flight", Box::new(FlightMapClient::new(&base).unwrap())),
("in-process", Box::new(SourceClient::new(s.source.clone()))),
]
}
#[tokio::test(flavor = "multi_thread")]
async fn every_door_gives_the_same_address_answers_as_the_raw_http_body() {
let s = AddressServer::start(ServerConfig::default()).await;
for (text, max) in [
("storgatan 5 uppsala", None),
("Storgatan", Some(4)),
("Kungsgatan 3 Umeå", None),
] {
let g = GeocodeQuery {
region: REGION.to_string(),
q: text.to_string(),
max,
};
let max_q = max.map(|m| format!("&max={m}")).unwrap_or_default();
let enc: String = text.bytes().map(|b| format!("%{b:02X}")).collect();
let raw: GeocodeReply = serde_json::from_slice(
&get(&s.url(&format!("/v1/geocode?region={REGION}&q={enc}{max_q}")))
.await
.body,
)
.unwrap();
assert!(!raw.hits.is_empty(), "{text}");
for (door, c) in address_doors(&s) {
assert_eq!(c.geocode(&g).await.unwrap(), raw, "{door} {text}");
}
}
let r = RevGeocodeQuery {
region: REGION.to_string(),
lon: 17.6351,
lat: 59.8502,
};
let raw: RevGeocodeReply = serde_json::from_slice(
&get(&s.url(&format!(
"/v1/revgeocode?region={REGION}&lon=17.6351&lat=59.8502"
)))
.await
.body,
)
.unwrap();
assert_eq!(raw.hit.as_ref().map(|h| h.source), Some(505));
for (door, c) in address_doors(&s) {
assert_eq!(c.revgeocode(&r).await.unwrap(), raw, "{door}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn every_door_gives_the_same_address_refusal() {
let s = AddressServer::start(ServerConfig::default()).await;
let cases = [
(
GeocodeQuery {
region: "atlantis".to_string(),
q: "a".to_string(),
max: None,
},
Code::UnknownRegion,
),
(
GeocodeQuery {
region: REGION.to_string(),
q: "a".to_string(),
max: Some(0),
},
Code::BadMax,
),
(
GeocodeQuery {
region: REGION.to_string(),
q: " ".to_string(),
max: None,
},
Code::MissingParam,
),
];
for (q, code) in &cases {
for (door, c) in address_doors(&s) {
assert_eq!(c.geocode(q).await.unwrap_err().code, *code, "{door} {q:?}");
}
}
let far = RevGeocodeQuery {
region: REGION.to_string(),
lon: 190.0,
lat: 0.0,
};
for (door, c) in address_doors(&s) {
assert_eq!(
c.revgeocode(&far).await.unwrap_err().code,
Code::BadLonLat,
"{door}"
);
}
// A map-only source: every door says the region has no address index.
let m = TestServer::start(ServerConfig::default()).await;
let g = GeocodeQuery {
region: REGION.to_string(),
q: "storgatan".to_string(),
max: None,
};
for (door, c) in doors(&m) {
assert_eq!(
c.geocode(&g).await.unwrap_err().code,
Code::NoAddressIndex,
"{door}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn the_fake_answers_its_canned_addresses_and_records_the_lookups() {
let region = Region {
name: "sweden".to_string(),
bbox: BBox::new(10.0, 55.0, 25.0, 70.0).unwrap(),
data_version: "fake".to_string(),
};
let hit = addresses()[0].clone();
let fake = FakeMapClient::new(vec![region])
.with_geocode(GeocodeReply {
region: String::new(),
query: String::new(),
indexed: 14,
hits: vec![hit.clone(), addresses()[1].clone()],
})
.with_revgeocode(RevGeocodeReply {
region: String::new(),
lon: 0.0,
lat: 0.0,
indexed: 14,
hit: Some(hit.clone()),
distance_m: 3.5,
});
let g = fake
.geocode(&GeocodeQuery {
region: "sweden".to_string(),
q: "storgatan".to_string(),
max: Some(1),
})
.await
.unwrap();
assert_eq!(
(g.region.as_str(), g.query.as_str(), g.hits.len()),
("sweden", "storgatan", 1)
);
let r = fake
.revgeocode(&RevGeocodeQuery {
region: "sweden".to_string(),
lon: 17.6,
lat: 59.8,
})
.await
.unwrap();
assert_eq!((r.lon, r.lat, r.hit), (17.6, 59.8, Some(hit)));
let e = fake
.geocode(&GeocodeQuery {
region: "norway".to_string(),
q: "a".to_string(),
max: None,
})
.await
.unwrap_err();
assert_eq!(e.code, Code::UnknownRegion);
assert_eq!(
fake.asked_addresses(),
[
"/v1/geocode?region=sweden&q=storgatan&max=1",
"/v1/revgeocode?region=sweden&lon=17.6&lat=59.8",
"/v1/geocode?region=norway&q=a",
]
);
}