#![allow(clippy::unwrap_used)]
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use sha2::{Digest, Sha256};
const GEOLITH: &str = env!("CARGO_BIN_EXE_geolith");
const GOLDENS: &[(&str, &str)] = &[
(
"tiles.pmtiles",
"731277617de516a7a8ecdc95cb5c6acd5b45be3541166c57f919415fb0aca017",
),
(
"search.glx",
"ee1d2c35476e9180a840c65e81c2b019a40adefa65411364d25b744b9513d610",
),
(
"search.tsv",
"1d5e0a60f08a77d9ba29cc72a6f8bd7101b0705f5896931e2f90f0a7a77a1a8c",
),
(
"search.pelias.ndjson",
"5877d1e54921eadc8dbafa537a6be20031ac1f99bdb73b7328824b04b154c5a1",
),
(
"search.photon.ndjson",
"dbcfd173228449a7c01be7915456cb76868f8f6c36b166e4a61e21db987da671",
),
(
"routing.glx",
"58a0f2587ec9a1949bdfbdcb23d76e11ffc55420a36d8ef1c10749ac72a5d322",
),
(
"routing-cch.glx",
"1e25d918d024aaf7a9a6b4eedeaaa06bc204850e527f166ab3c591dc937fe2f3",
),
(
"terrain.pmtiles",
"93413f837ec7959b5934afa610bf5e5b8c495a7cb46140670018bdcb2dc78444",
),
(
"splat-tiles",
"863bfb91055130fcabb16d753eaf923c69d9f4b16efa29c4ff00ed646b99e7cb",
),
];
fn crate_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn fixtures() -> PathBuf {
crate_dir().join("tests/fixtures")
}
fn recording() -> bool {
std::env::var_os("GEOLITH_GOLDEN_RECORD").is_some()
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
write!(out, "{byte:02x}").unwrap();
}
out
}
fn sha256(bytes: &[u8]) -> String {
hex(&Sha256::digest(bytes))
}
fn run(args: &[String], threads: Option<&str>) -> Output {
let mut command = Command::new(GEOLITH);
command.args(args);
if let Some(threads) = threads {
command.env("RAYON_NUM_THREADS", threads);
}
let output = command.output().expect("binary runs");
assert!(
output.status.success(),
"geolith {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
output
}
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|arg| (*arg).to_string()).collect()
}
fn path_arg(path: &Path) -> String {
path.to_str().expect("utf-8 path").to_string()
}
fn output_hash(path: &Path) -> String {
if path.is_dir() {
let mut files = BTreeMap::new();
let mut pending = vec![path.to_path_buf()];
while let Some(dir) = pending.pop() {
for entry in std::fs::read_dir(&dir).unwrap() {
let entry = entry.unwrap().path();
if entry.is_dir() {
pending.push(entry);
} else {
let name = entry
.strip_prefix(path)
.unwrap()
.to_string_lossy()
.into_owned();
files.insert(name, sha256(&std::fs::read(&entry).unwrap()));
}
}
}
let mut listing = String::new();
for (name, hash) in files {
writeln!(listing, "{hash} {name}").unwrap();
}
sha256(listing.as_bytes())
} else {
sha256(&std::fs::read(path).unwrap())
}
}
fn keep_output(to: &Path, from: &Path) {
if from.is_dir() {
std::fs::create_dir_all(to).unwrap();
for entry in std::fs::read_dir(from).unwrap() {
let entry = entry.unwrap().path();
keep_output(&to.join(entry.file_name().unwrap()), &entry);
}
} else {
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
std::fs::copy(from, to).unwrap();
}
}
fn golden(name: &str, build: impl Fn(&Path, Option<&str>) -> PathBuf) {
let mut hashes = Vec::new();
for threads in [Some("1"), None] {
let dir = tempfile::tempdir().unwrap();
for scratch in ["scratch", "tmp"] {
std::fs::create_dir_all(dir.path().join(scratch)).unwrap();
}
let out = build(dir.path(), threads);
if out.is_file() {
assert!(
std::fs::metadata(&out).unwrap().len() > 100,
"{name}: the output is empty"
);
}
hashes.push(output_hash(&out));
if let (Some(keep), Some("1")) = (std::env::var_os("GEOLITH_GOLDEN_KEEP"), threads) {
keep_output(&PathBuf::from(keep).join(name), &out);
}
}
assert_eq!(
hashes[0], hashes[1],
"{name}: one thread and the default pool give different bytes"
);
if recording() {
println!("GOLDEN {name} {}", hashes[0]);
return;
}
let expected = GOLDENS
.iter()
.find(|(known, _)| *known == name)
.unwrap_or_else(|| panic!("no golden recorded for {name}"))
.1;
assert_eq!(hashes[0], expected, "{name}: output bytes changed");
}
#[test]
fn tiles_pmtiles() {
let inputs = fixtures().join("golden/tiles");
golden("tiles.pmtiles", |dir, threads| {
let out = dir.join("out.pmtiles");
run(
&strings(&[
"--data",
&path_arg(&inputs.join("overture")),
"--natural-earth",
&path_arg(&inputs.join("ne.sqlite")),
"--land-polygons",
&path_arg(&inputs.join("land")),
"--water-polygons",
&path_arg(&inputs.join("water")),
"--output",
&path_arg(&out),
"--tmpdir",
&path_arg(&dir.join("tmp")),
"--node-store",
&path_arg(&dir.join("nodes.bin")),
"--roads-source",
"overture",
"--no-conflate",
"--bbox",
"-0.3,51.4,0.3,51.6",
"--max-zoom",
"10",
]),
threads,
);
out
});
}
fn search(name: &str, format: &str, extension: &str) {
let inputs = fixtures().join("golden/search/overture");
let pbf = fixtures().join("golden/search/geocoding.osm.pbf");
let outline = Path::new(env!("CARGO_MANIFEST_DIR")).join(
"../packages/routing-builder/tests/fixtures/routing/india-guard/soi-kashmir-excerpt.geojson",
);
golden(name, |dir, threads| {
let out = dir.join(format!("search.{extension}"));
run(
&strings(&[
"--data",
&path_arg(&inputs),
"--natural-earth",
"/nonexistent/natural_earth.sqlite",
"--land-polygons",
"/nonexistent/land-polygons",
"--water-polygons",
"/nonexistent/water-polygons",
"--output",
&path_arg(&dir.join("unused.pmtiles")),
"--output-format",
"geocoding",
"--geocoding-format",
format,
"--geocoding-output",
&path_arg(&out),
"--osm-pbf",
&path_arg(&pbf),
"--india-outline",
&path_arg(&outline),
"--tmpdir",
&path_arg(&dir.join("scratch")),
]),
threads,
);
out
});
}
#[test]
fn search_glx() {
search("search.glx", "glx", "glx");
}
#[test]
fn search_pg_copy() {
search("search.tsv", "pg-copy", "tsv");
}
#[test]
fn search_pelias() {
search("search.pelias.ndjson", "pelias", "ndjson");
}
#[test]
fn search_photon() {
search("search.photon.ndjson", "photon", "ndjson");
}
fn routing(name: &str, extra: &[&str]) {
let pbf =
crate_dir().join("../packages/routing-builder/tests/fixtures/routing/halensee.osm.pbf");
golden(name, |dir, threads| {
let out = dir.join("routing.glx");
let mut args = strings(&[
"--output-format",
"routing",
"--osm-pbf",
&path_arg(&pbf),
"--routing-output",
&path_arg(&out),
"--tmpdir",
&path_arg(&dir.join("scratch")),
]);
args.extend(strings(extra));
run(&args, threads);
out
});
}
#[test]
fn routing_glx() {
routing("routing.glx", &[]);
}
#[test]
fn routing_glx_with_a_cch() {
routing(
"routing-cch.glx",
&["--routing-cch", "auto,pedestrian,bicycle"],
);
}
#[test]
fn terrain_pmtiles() {
let dem = fixtures().join("inspect/f32-lzw-stripped.tif");
golden("terrain.pmtiles", |dir, threads| {
let out = dir.join("terrain.pmtiles");
run(
&strings(&[
"terrain",
"--dem",
&path_arg(&dem),
"--output",
&path_arg(&out),
"--min-zoom",
"3",
"--max-zoom",
"4",
"--tile-size",
"256",
]),
threads,
);
out
});
}
fn ply(count: usize) -> Vec<u8> {
const PROPERTIES: [&str; 14] = [
"x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1", "scale_2",
"rot_0", "rot_1", "rot_2", "rot_3",
];
let mut bytes = b"ply\nformat binary_little_endian 1.0\n".to_vec();
writeln!(bytes, "element vertex {count}").unwrap();
for property in PROPERTIES {
writeln!(bytes, "property float {property}").unwrap();
}
bytes.extend_from_slice(b"end_header\n");
for index in 0..count {
let offset = index as f32;
for value in [
offset,
offset * 0.5,
offset * 0.25,
0.4,
0.5,
0.6,
1.1,
-2.0,
-2.1,
-2.2,
1.0,
0.0,
0.0,
0.0,
] {
bytes.extend_from_slice(&value.to_le_bytes());
}
}
bytes
}
#[test]
fn splat_tiles() {
golden("splat-tiles", |dir, threads| {
let input = dir.join("scene.ply");
std::fs::write(&input, ply(8)).unwrap();
let out = dir.join("tileset");
run(
&strings(&[
"splat-tiles",
"--ply",
&path_arg(&input),
"--output",
&path_arg(&out),
"--longitude",
"7.9797",
"--latitude",
"45.9756",
]),
threads,
);
out
});
}
fn help(args: &[&str]) -> String {
let output = Command::new(GEOLITH)
.args(args)
.output()
.expect("binary runs");
assert!(output.status.success(), "geolith {args:?}: {output:?}");
String::from_utf8(output.stdout).unwrap()
}
fn commands(text: &str) -> Vec<String> {
text.lines()
.skip_while(|line| *line != "Commands:")
.skip(1)
.take_while(|line| line.starts_with(" "))
.filter_map(|line| line.split_whitespace().next())
.filter(|name| *name != "help")
.map(str::to_string)
.collect()
}
fn check_help(snapshots: &mut String, label: &str, args: &[&str]) {
let text = help(args);
writeln!(snapshots, "===== geolith {label}").unwrap();
snapshots.push_str(&text);
if !text.ends_with('\n') {
snapshots.push('\n');
}
}
#[test]
fn help_text_is_unchanged() {
let mut snapshots = String::new();
check_help(&mut snapshots, "--help", &["--help"]);
for verb in [
"terrain",
"splat-tiles",
"raster",
"reconstruct",
"dataset",
"notices",
] {
check_help(&mut snapshots, &format!("{verb} --help"), &[verb, "--help"]);
}
let dataset = help(&["dataset", "--help"]);
for action in commands(&dataset) {
check_help(
&mut snapshots,
&format!("dataset {action} --help"),
&["dataset", &action, "--help"],
);
}
let path = crate_dir().join("tests/fixtures/golden/help.txt");
if recording() {
std::fs::File::create(&path)
.unwrap()
.write_all(snapshots.as_bytes())
.unwrap();
println!("GOLDEN help.txt {}", sha256(snapshots.as_bytes()));
return;
}
let expected = std::fs::read_to_string(&path).unwrap();
assert!(
expected == snapshots,
"the help text of the binary changed; if it should, rerun with GEOLITH_GOLDEN_RECORD=1"
);
}