use std::fmt;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConformanceReport {
pub subject: String,
pub passed: Vec<String>,
pub failed: Vec<(String, String)>,
pub notes: Vec<String>,
}
impl ConformanceReport {
pub fn new(subject: impl Into<String>) -> Self {
Self {
subject: subject.into(),
..Self::default()
}
}
pub fn pass(&mut self, check: impl Into<String>) {
self.passed.push(check.into());
}
pub fn fail(&mut self, check: impl Into<String>, reason: impl Into<String>) {
self.failed.push((check.into(), reason.into()));
}
pub fn record(&mut self, check: impl Into<String>, result: Result<(), String>) {
match result {
Ok(()) => self.pass(check),
Err(reason) => self.fail(check, reason),
}
}
pub fn note(&mut self, note: impl Into<String>) {
self.notes.push(note.into());
}
pub fn is_ok(&self) -> bool {
self.failed.is_empty()
}
pub fn passed_check(&self, check: &str) -> bool {
self.passed.iter().any(|c| c == check)
}
pub fn failure(&self, check: &str) -> Option<&str> {
self.failed
.iter()
.find(|(c, _)| c == check)
.map(|(_, r)| r.as_str())
}
pub fn merge(&mut self, other: ConformanceReport) {
let prefix = if other.subject.is_empty() || other.subject == self.subject {
String::new()
} else {
format!("{}: ", other.subject)
};
self.passed
.extend(other.passed.into_iter().map(|c| format!("{prefix}{c}")));
self.failed.extend(
other
.failed
.into_iter()
.map(|(c, r)| (format!("{prefix}{c}"), r)),
);
self.notes
.extend(other.notes.into_iter().map(|n| format!("{prefix}{n}")));
}
#[track_caller]
pub fn assert_all_passed(&self) {
if !self.is_ok() {
panic!("{self}");
}
}
}
impl fmt::Display for ConformanceReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let subject = if self.subject.is_empty() {
"conformance"
} else {
self.subject.as_str()
};
writeln!(
f,
"{subject}: {} passed, {} failed",
self.passed.len(),
self.failed.len()
)?;
for (check, reason) in &self.failed {
writeln!(f, " FAIL {check}: {reason}")?;
}
for note in &self.notes {
writeln!(f, " note: {note}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn merge_prefixes_and_assert_lists_every_failure() {
let mut all = ConformanceReport::new("tools");
let mut one = ConformanceReport::new("read_file");
one.pass("a");
one.fail("b", "broken");
let mut two = ConformanceReport::new("shell");
two.fail("c", "also broken");
all.merge(one);
all.merge(two);
assert_eq!(all.passed, ["read_file: a"]);
assert_eq!(all.failure("shell: c"), Some("also broken"));
let message = std::panic::catch_unwind(|| all.assert_all_passed())
.unwrap_err()
.downcast::<String>()
.unwrap();
assert!(message.contains("read_file: b: broken"), "{message}");
assert!(message.contains("shell: c: also broken"), "{message}");
}
}