mod common;
use std::collections::BTreeSet;
use std::path::Path;
use knobe::verify_path;
const CORE_NINE: &[&str] = &[
"minimal-valid.knobe.md",
"full-valid.knobe.md",
"body-modified.knobe.md",
"payload-modified.knobe.md",
"unreadable.knobe.md",
"unicode-valid.knobe.md",
"numeric-violation.knobe.md",
"omitted-body-hash.knobe.md",
"multi-block.knobe.md",
];
struct Expectation {
file: String,
status: String,
body: String,
conformance: String,
}
fn table_cells(line: &str) -> Option<Vec<&str>> {
let row = line.trim().strip_prefix('|')?;
let mut cells = Vec::new();
let (mut start, mut escaped) = (0, false);
for (i, c) in row.char_indices() {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'|' => {
cells.push(row[start..i].trim());
start = i + 1;
}
_ => {}
}
}
let last = row[start..].trim();
if !last.is_empty() {
cells.push(last); }
Some(cells)
}
fn column(header: &[&str], name: &str) -> Option<usize> {
header.iter().position(|h| {
let h = h.to_ascii_lowercase();
h == name || h.strip_prefix("expected ") == Some(name)
})
}
fn published_expected(vectors: &Path) -> Vec<Expectation> {
let mut out = Vec::new();
for dir in ["", "adversarial", "interpretation"] {
let readme = vectors.join(dir).join("README.md");
let text = std::fs::read_to_string(&readme).unwrap_or_else(|e| panic!("{}: {e}", readme.display()));
let mut header: Option<Vec<&str>> = None;
for line in text.lines() {
let Some(cells) = table_cells(line) else {
header = None;
continue;
};
let is_header = cells.first().is_some_and(|c| c.eq_ignore_ascii_case("file"));
let head = match &header {
Some(head) if !is_header => head,
_ => {
header = Some(cells);
continue;
}
};
let Some(file) =
cells.first().and_then(|c| c.strip_prefix('`')?.strip_suffix('`')).filter(|f| f.ends_with(".knobe.md"))
else {
continue; };
assert!(
cells.len() == head.len(),
"{}: row has {} cells, header {}: {line:?}",
readme.display(),
cells.len(),
head.len()
);
let at = |name: &str| {
let i = column(head, name).unwrap_or_else(|| {
panic!(
"{}: the table listing {file} has no {name} column (upstream added body_verified \
to every table in PR #30; use a checkout at 8d664d3 or later)",
readme.display()
)
});
let cell = cells[i].split_whitespace().next().unwrap_or("");
assert!(!cell.is_empty(), "{}: blank {name} cell in the row {line:?}", readme.display());
cell.to_string()
};
out.push(Expectation {
file: if dir.is_empty() { file.to_string() } else { format!("{dir}/{file}") },
status: at("status"),
body: at("body_verified"),
conformance: at("conformance"),
});
}
}
out
}
fn vector_files(dir: &Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let entries = std::fs::read_dir(dir).unwrap_or_else(|e| panic!("cannot list {}: {e}", dir.display()));
for entry in entries {
let p = entry.unwrap_or_else(|e| panic!("cannot list {}: {e}", dir.display())).path();
if p.is_dir() {
out.extend(vector_files(&p));
} else if p.to_string_lossy().ends_with(".knobe.md") {
out.push(p);
}
}
out
}
#[test]
fn every_published_vector_matches_its_expected_result() {
let dir = common::protocol_dir().join("test-vectors");
let rows = published_expected(&dir);
let listed: BTreeSet<&str> = rows.iter().map(|r| r.file.as_str()).collect();
let mut failures = Vec::new();
for want in &rows {
let path = dir.join(&want.file);
if !path.is_file() {
failures.push(format!("{}: listed in the README but missing", want.file));
continue;
}
let r = verify_path(&path);
let got_body = r.body_verified.map(|b| b.as_str());
let body_ok = match want.body.as_str() {
"—" => got_body.is_none(),
b => got_body == Some(b),
};
if r.state.as_str() != want.status || r.conformance.as_str() != want.conformance || !body_ok {
failures.push(format!(
"{}: want {}/{:?}/{}, got {}/{got_body:?}/{} ({:?})",
want.file,
want.status,
want.body,
want.conformance,
r.state.as_str(),
r.conformance.as_str(),
r.conformance_issues
));
}
}
for core in CORE_NINE {
if !listed.contains(core) {
failures.push(format!("the README tables do not list the core vector {core}"));
}
}
for p in vector_files(&dir) {
let rel = p.strip_prefix(&dir).unwrap().to_string_lossy().replace('\\', "/");
if !listed.contains(rel.as_str()) {
failures.push(format!("{rel} has no expected result in the test-vectors READMEs"));
}
}
assert!(failures.is_empty(), "vector mismatches:\n{}", failures.join("\n"));
}
#[test]
fn unreadable_vectors_exit_2_and_verified_valid_exit_0() {
let dir = common::protocol_dir().join("test-vectors");
assert_eq!(verify_path(&dir.join("unreadable.knobe.md")).exit_code(), 2);
assert_eq!(verify_path(&dir.join("minimal-valid.knobe.md")).exit_code(), 0);
assert_eq!(verify_path(&dir.join("numeric-violation.knobe.md")).exit_code(), 1);
assert_eq!(verify_path(&dir.join("payload-modified.knobe.md")).exit_code(), 1);
}
#[test]
fn missing_file_is_unreadable_not_a_panic() {
let r = verify_path(std::path::Path::new("/definitely/not/here.knobe.md"));
assert_eq!(r.state.as_str(), "unreadable");
assert_eq!(r.exit_code(), 2);
}