mod common;
use std::fmt::Write as _;
use std::panic;
use std::path::Path;
use osmflow::{PbfReader, ReadMode, Select};
use test_each_file::test_each_path;
test_each_path! { for ["pbf"] in "crates/osmflow/fixtures" => fixture }
const FULL_SNAPSHOT_LINES: usize = 200;
const MISREAD: &[(&str, &str, &str)] = &[
(
"generated__split_messages.osm.pbf",
"osmpbf",
LAST_OCCURRENCE,
),
(
"generated__split_messages.osm.pbf",
"osmpbfreader",
LAST_OCCURRENCE,
),
(
"generated__split_string_table_zlib.osm.pbf",
"osmpbf",
LAST_OCCURRENCE,
),
(
"generated__split_string_table_zlib.osm.pbf",
"osmpbfreader",
LAST_OCCURRENCE,
),
];
const LAST_OCCURRENCE: &str =
"it keeps only the last occurrence of a message field, where protobuf merges them";
#[test]
fn split_messages_are_merged() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/generated");
let read =
|name: &str| common::osmflow(&PbfReader::open(dir.join(name)).unwrap(), false).unwrap();
let packed = read("packed.osm.pbf");
let of_type = |kind: char| packed.iter().filter(move |l| l.starts_with(kind)).cloned();
let expected: Vec<String> = of_type('n')
.chain(of_type('n'))
.chain(of_type('w'))
.collect();
assert_eq!(read("split_messages.osm.pbf"), expected);
}
fn check_filters(path: &Path, lines: &[String]) {
type Narrow = fn(PbfReader) -> PbfReader;
let cases: [(char, Narrow); 3] = [
('n', |f| f.nodes_where(|_| false)),
('w', |f| f.ways_where(|_| false)),
('r', |f| f.relations_where(|_| false)),
];
for (kind, narrow) in cases {
let file = narrow(PbfReader::open(path).unwrap());
let want: Vec<&String> = lines.iter().filter(|l| !l.starts_with(kind)).collect();
let modes = [
("one thread", common::osmflow(&file, false)),
("ordered", common::osmflow_ordered(&file)),
("unordered", common::osmflow_unordered(&file)),
];
for (mode, got) in modes {
let got = got.unwrap();
assert_eq!(
got.iter().collect::<Vec<_>>(),
want,
"{mode} read without {kind}"
);
}
}
let ways: Vec<&String> = lines.iter().filter(|l| l.starts_with('w')).collect();
for mode in [ReadMode::Sequential, ReadMode::Selective] {
let file = PbfReader::open(path)
.unwrap()
.read_mode(mode)
.nodes_where(|_| false)
.relations_where(|_| false);
let got = common::osmflow(&file, false).unwrap();
assert_eq!(
got.iter().collect::<Vec<_>>(),
ways,
"{mode:?} read of ways"
);
}
let reader = PbfReader::open(path).unwrap();
common::osmflow(&reader.clone().ways_where(|s| s.has("highway")), false).unwrap();
let split = path.ends_with("generated/split_string_table_zlib.osm.pbf");
assert_eq!(
reader.split_string_tables() > 0,
split,
"split string tables found"
);
let file = reader
.nodes_where(|s| s.has("highway"))
.ways_where(|s| s.has("highway"))
.relations_where(|s| s.has("highway"));
let got = common::osmflow(&file, false).unwrap();
let mut got = got.iter();
for line in lines
.iter()
.filter(|l| l.contains(" Thighway=") || l.contains(",highway="))
{
assert!(got.any(|g| g == line), "a filter of highway lost {line}");
}
}
#[test]
fn a_split_string_table_is_checked_once_one_is_found() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("fixtures/generated/split_string_table_zlib.osm.pbf");
let highway = |f: PbfReader| {
f.nodes_where(|s| s.has("highway"))
.ways_where(|s| s.has("highway"))
.relations_where(|s| s.has("highway"))
};
let reader = PbfReader::open(&path).unwrap();
let ways = |f: &PbfReader| {
common::osmflow(f, false)
.unwrap()
.iter()
.filter(|l| l.starts_with('w'))
.count()
};
assert_eq!(
ways(&highway(reader.clone())),
0,
"skipped by the start of its table"
);
assert_eq!(reader.split_string_tables(), 0);
assert_eq!(ways(&reader.clone().ways_where(|s| s.has("highway"))), 1);
assert_eq!(reader.split_string_tables(), 1);
assert_eq!(
ways(&highway(reader.clone())),
1,
"checked whole once one was found"
);
assert_eq!(reader.split_string_tables(), 2);
}
fn misread(name: &str, reader: &str) -> Option<String> {
MISREAD
.iter()
.find(|(n, r, _)| *n == name && *r == reader)
.map(|(_, r, why)| format!("# {r} is not compared: {why}"))
}
fn snapshot_name(path: &Path) -> String {
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.canonicalize()
.unwrap();
let rel = path
.strip_prefix(&fixtures)
.expect("the fixture is under the canonical fixtures directory");
rel.to_string_lossy().replace(['/', '\\'], "__")
}
fn fixture([path]: [&Path; 1]) {
let name = snapshot_name(path);
let read = PbfReader::open(path).and_then(|file| Ok((common::osmflow(&file, false)?, file)));
let snapshot = match read {
Err(e) => {
let osmpbf = match panic::catch_unwind(|| common::osmpbf(path)) {
Ok(Ok(lines)) => format!("osmpbf reads {} objects", lines.len()),
Ok(Err(e)) => format!("osmpbf fails too: {e}"),
Err(_) => "osmpbf panics".to_owned(),
};
format!("osmflow error: {e}\n{osmpbf}\n")
}
Ok((lines, file)) => {
check_modes(&file, &lines);
check_filters(path, &lines);
let (osmpbf, osmpbfreader) = (misread(&name, "osmpbf"), misread(&name, "osmpbfreader"));
let dropped = if osmpbf.is_none() {
check_osmpbf(path, &lines)
} else {
0
};
if !file.header().is_history() && osmpbfreader.is_none() {
let ours = common::osmflow(&file, true).unwrap();
let other = common::osmpbfreader(path).expect("osmpbfreader reads the file");
assert_lines_eq(&ours, &other, "osmpbfreader");
}
let mut out = render(&file, &lines, dropped);
for note in [osmpbf, osmpbfreader].into_iter().flatten() {
out.push_str(¬e);
out.push('\n');
}
out
}
};
insta::with_settings!({ snapshot_path => "snapshots", prepend_module_to_snapshot => false }, {
insta::assert_snapshot!(name, snapshot);
});
}
fn check_modes(file: &PbfReader, lines: &[String]) {
let ordered = common::osmflow_ordered(file).expect("parallel ordered read");
assert_eq!(lines, ordered.as_slice(), "parallel ordered read differs");
let locations =
common::node_locations(file, Select::node_locations()).expect("node locations read");
let all = common::node_locations(file, Select::all()).expect("full read");
assert_eq!(locations, all, "node locations read differs");
let unordered = common::osmflow_unordered(file).expect("parallel unordered read");
assert_eq!(
lines,
unordered.as_slice(),
"parallel unordered read differs"
);
}
fn check_osmpbf(path: &Path, lines: &[String]) -> usize {
const NO_META: &str = "v-1 dV c0 t0 i0 u ";
let other = common::osmpbf(path).expect("osmpbf reads the file");
let mut dropped = 0;
let ours: Vec<String> = lines
.iter()
.zip(&other)
.map(|(ours, theirs)| {
let (Some((id, rest)), Some((tid, trest))) =
(ours.split_once(' '), theirs.split_once(' '))
else {
return ours.clone();
};
if id == tid
&& id.starts_with('n')
&& trest.starts_with(NO_META)
&& !rest.starts_with(NO_META)
{
let tags = rest.find(" T").map_or(rest, |at| &rest[at + 1..]);
dropped += 1;
format!("{id} {NO_META}{tags}")
} else {
ours.clone()
}
})
.chain(lines.iter().skip(other.len()).cloned())
.collect();
assert_lines_eq(&ours, &other, "osmpbf");
dropped
}
#[allow(clippy::panic, reason = "a test helper fails the test")]
fn assert_lines_eq(ours: &[String], other: &[String], name: &str) {
if ours == other {
return;
}
let first = ours.iter().zip(other).position(|(a, b)| a != b);
match first {
Some(i) => panic!(
"{name} differs at object {i}:\n osmflow: {}\n {name}: {}",
ours[i], other[i]
),
None => panic!(
"{name} reads {} objects, osmflow {}",
other.len(),
ours.len()
),
}
}
fn render(file: &PbfReader, lines: &[String], dropped: usize) -> String {
let mut out = common::osmflow_header(file).join("\n");
let count = |c: u8| lines.iter().filter(|l| l.as_bytes()[0] == c).count();
writeln!(
out,
"\n# {} nodes, {} ways, {} relations, hash {:016x}",
count(b'n'),
count(b'w'),
count(b'r'),
common::fnv(lines)
)
.unwrap();
let shown = if lines.len() > FULL_SNAPSHOT_LINES {
writeln!(out, "# the first 20 objects:").unwrap();
&lines[..20]
} else {
lines
};
for line in shown {
writeln!(out, "{line}").unwrap();
}
if dropped > 0 {
writeln!(
out,
"# osmpbf drops the metadata of {dropped} dense nodes that lack some metadata columns"
)
.unwrap();
}
out
}