Files
ScaenaPublic/crates/scaena-core/tests/props.rs
T

244 lines
8.1 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
//! Property tests: the parsers and the checker never panic; valid files round-trip;
//! adding a valid reference fixes an unsourced sentence.
use std::collections::BTreeMap;
use proptest::prelude::*;
use scaena_core::canon::{self, Canon, Status};
use scaena_core::claims::{self, Problem};
use scaena_core::hooks;
/// Pieces that hit the interesting paths of the parsers and the checker.
fn fragment() -> impl Strategy<Value = String> {
prop_oneof![
Just("---\n".to_string()),
Just("id: tabula\n".to_string()),
Just("name: Tabula\n".to_string()),
Just("status: released\n".to_string()),
Just("aula: https://aula.marek-novak.cz/tabula/\n".to_string()),
Just("- [F".to_string()),
Just("- [F1] ".to_string()),
Just("- [H1] ".to_string()),
Just("[tabula#F1]".to_string()),
Just("[tabula#F2]".to_string()),
Just("[tabula#F".to_string()),
Just("[x#F99999999999999999999]".to_string()),
Just("#F1".to_string()),
Just(" (assumption)".to_string()),
Just("{app}".to_string()),
Just("{".to_string()),
Just("}".to_string()),
Just("https://".to_string()),
Just("www.".to_string()),
Just("evil.com/".to_string()),
Just(". ".to_string()),
Just("? ".to_string()),
Just("\r\n".to_string()),
Just("\r".to_string()),
Just("\n".to_string()),
Just("\u{feff}".to_string()),
Just("\u{202e}".to_string()),
Just("\0".to_string()),
Just("ž".to_string()),
Just("🎉".to_string()),
Just("1.2".to_string()),
Just("$".to_string()),
Just("Windows".to_string()),
Just("Try it today".to_string()),
"[a-zA-Z0-9 ]{0,12}",
any::<String>(),
]
}
fn soup() -> impl Strategy<Value = String> {
prop::collection::vec(fragment(), 0..40).prop_map(|v| v.concat())
}
fn canon() -> Canon {
let mut c = Canon::new();
let f = canon::parse(
"tabula",
"---\nid: tabula\nname: Tabula\none_liner: a\naudience: b\nprice: c\nclicks: d\nstatus: released\n\
aula: https://aula.marek-novak.cz/tabula/\n---\n- [F1] Notes stay local.\n- [F2] Sync. (assumption)\n",
)
.unwrap();
c.insert(f).unwrap();
c
}
#[derive(Debug, Clone)]
struct GenFact {
id: u32,
text: String,
assumption: bool,
}
fn fact_text() -> impl Strategy<Value = String> {
"[A-Za-z0-9ěščřžýáíéůú,.'$€-][A-Za-z0-9ěščřžýáíéůú ,.'$€():/-]{0,60}[A-Za-z0-9.]"
.prop_filter("no marker", |s| !s.to_lowercase().contains("(assumption)"))
}
fn value() -> impl Strategy<Value = String> {
"[A-Za-z0-9][A-Za-z0-9 ,.'()-]{0,40}[A-Za-z0-9.]"
}
fn gen_file() -> impl Strategy<Value = (String, Vec<GenFact>, [String; 5], Status)> {
let id = "[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?";
let facts = prop::collection::btree_map(1u32..=9999, (fact_text(), any::<bool>()), 0..40)
.prop_map(|m| {
m.into_iter()
.map(|(id, (text, assumption))| GenFact {
id,
text,
assumption,
})
.collect::<Vec<_>>()
});
let status = prop_oneof![
Just(Status::Released),
Just(Status::Beta),
Just(Status::Planned)
];
(
id,
facts,
[value(), value(), value(), value(), value()],
status,
)
}
fn render(id: &str, facts: &[GenFact], v: &[String; 5], status: Status, shuffle: u64) -> String {
let st = match status {
Status::Released => "released",
Status::Beta => "beta",
Status::Planned => "planned",
};
let mut s = format!(
"---\nid: {id}\nname: {}\none_liner: {}\naudience: {}\nprice: (assumption) {}\nclicks: {}\nstatus: {st}\n---\n\n# Title\n",
v[0], v[1], v[2], v[3], v[4]
);
// Facts in a scrambled order under several headings.
let mut order: Vec<&GenFact> = facts.iter().collect();
if !order.is_empty() {
let k = (shuffle as usize) % order.len();
order.rotate_left(k);
}
for (i, f) in order.iter().enumerate() {
if i % 7 == 3 {
s.push_str("\n## More\n\nSome prose.\n");
}
s.push_str(&format!(
"- [F{}] {}{}\n",
f.id,
f.text,
if f.assumption { " (assumption)" } else { "" }
));
}
s
}
proptest! {
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
#[test]
fn canon_parse_never_panics(text in soup(), stem in "[a-z-]{0,6}") {
let _ = canon::parse(&stem, &text);
let _ = canon::parse("tabula", &text);
}
#[test]
fn canon_parse_never_panics_on_any_string(text in any::<String>()) {
let _ = canon::parse("tabula", &text);
}
#[test]
fn hooks_parse_never_panics(text in soup()) {
if let Ok(hs) = hooks::parse(&text) {
let v: BTreeMap<String, String> =
hooks::SLOTS.iter().map(|s| (s.to_string(), "{app}".to_string())).collect();
for h in hs {
let filled = h.fill(&v).unwrap();
let slot = format!("{{{}}}", "feature");
prop_assert!(!filled.contains(&slot));
}
}
}
#[test]
fn genome_never_panics(text in soup()) {
let _ = hooks::Genome::of(&text);
}
#[test]
fn check_never_panics(text in soup()) {
let c = canon();
let rep = claims::check(&text, &c);
let mut sorted = rep.refs.clone();
sorted.sort();
sorted.dedup();
prop_assert_eq!(&rep.refs, &sorted);
let _ = rep.problems.iter().map(Problem::reason).collect::<Vec<_>>();
let _ = claims::strip_refs(&text);
let _ = claims::sentences(&text);
}
#[test]
fn check_never_panics_on_any_string(text in any::<String>()) {
let _ = claims::check(&text, &canon());
let _ = claims::strip_refs(&text);
}
#[test]
fn valid_files_round_trip((id, facts, v, status) in gen_file(), shuffle in any::<u64>()) {
let text = render(&id, &facts, &v, status, shuffle);
let f = canon::parse(&id, &text).unwrap();
prop_assert_eq!(&f.id, &id);
prop_assert_eq!(&f.front.name, &v[0]);
prop_assert_eq!(&f.front.price, &format!("(assumption) {}", v[3]));
prop_assert_eq!(f.front.status, status);
let mut got: Vec<(u32, String, bool)> =
f.facts.iter().map(|x| (x.id, x.text.clone(), x.assumption)).collect();
got.sort();
let want: Vec<(u32, String, bool)> =
facts.iter().map(|x| (x.id, x.text.clone(), x.assumption)).collect();
prop_assert_eq!(got, want);
// CRLF gives the same file.
let crlf = canon::parse(&id, &text.replace('\n', "\r\n")).unwrap();
prop_assert_eq!(crlf, f);
}
#[test]
fn adding_a_valid_ref_fixes_an_unsourced_sentence(
words in prop::collection::vec("[A-Za-z0-9$€%'ěščřž]{1,10}", 1..12),
punct in prop_oneof![Just(""), Just("."), Just("!"), Just("?")],
after in any::<bool>(),
) {
let c = canon();
let body = words.join(" ");
let sentence = format!("{body}{punct}");
let rep = claims::check(&sentence, &c);
let only_unsourced = !rep.ok()
&& rep.problems.iter().all(|p| matches!(p, Problem::Unsourced { .. }));
if only_unsourced {
let fixed = if after {
format!("{body}{punct} [tabula#F1]")
} else {
format!("{body} [tabula#F1]{punct}")
};
let rep2 = claims::check(&fixed, &c);
prop_assert!(rep2.ok(), "{:?} -> {:?}", fixed, rep2.problems);
prop_assert_eq!(claims::strip_refs(&fixed), sentence);
}
}
#[test]
fn ref_to_an_assumption_never_passes(words in prop::collection::vec("[A-Za-z]{1,8}", 1..8)) {
let c = canon();
let text = format!("{} [tabula#F2].", words.join(" "));
prop_assert!(!claims::check(&text, &c).ok());
}
}