[core] Tests: canon parser, claim checker, hook templates, property tests

This commit is contained in:
2026-11-23 01:18:18 +01:00
parent 6f30efb79b
commit db21efcddf
4 changed files with 1014 additions and 0 deletions
+341
View File
@@ -0,0 +1,341 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
use scaena_core::canon::{self, Canon, CanonCode, CanonFile, Status};
const TABULA: &str = "---
id: tabula
name: Tabula
one_liner: Notes that stay on your own computer.
audience: People who want notes without an account.
price: (assumption) one-time purchase
clicks: New note in 1 click.
status: released
aula: https://aula.marek-novak.cz/tabula/
---
<!-- sources: Mark, 2026-11-23 -->
# Tabula
## What it does
- [F1] Tabula keeps notes on your own computer.
- [F2] It syncs between your devices without a cloud account. (assumption)
## Honest limits
- [F3] There is no phone app yet. Docs: https://aula.marek-novak.cz/tabula/limits.
";
fn code(stem: &str, text: &str) -> (usize, CanonCode) {
let e = canon::parse(stem, text).expect_err("must be rejected");
(e.line, e.code)
}
fn with_front(front: &str, body: &str) -> String {
format!("---\n{front}---\n{body}")
}
const FRONT: &str = "id: tabula
name: Tabula
one_liner: Notes.
audience: Everyone.
price: free
clicks: 1 click.
status: beta
";
#[test]
fn parses_the_sample_file() {
let f = canon::parse("tabula", TABULA).unwrap();
assert_eq!(f.id, "tabula");
assert_eq!(f.front.name, "Tabula");
assert_eq!(f.front.one_liner, "Notes that stay on your own computer.");
assert_eq!(f.front.audience, "People who want notes without an account.");
assert_eq!(f.front.price, "(assumption) one-time purchase");
assert!(canon::is_assumption_value(&f.front.price));
assert!(!canon::is_assumption_value(&f.front.name));
assert_eq!(f.front.clicks, "New note in 1 click.");
assert_eq!(f.front.status, Status::Released);
assert_eq!(f.front.aula.as_deref(), Some("https://aula.marek-novak.cz/tabula/"));
assert_eq!(f.front.site, None);
assert_eq!(f.facts.len(), 3);
let f1 = f.fact(1).unwrap();
assert_eq!(f1.text, "Tabula keeps notes on your own computer.");
assert!(!f1.assumption);
assert_eq!(f1.line, 16);
let f2 = f.fact(2).unwrap();
assert_eq!(f2.text, "It syncs between your devices without a cloud account.");
assert!(f2.assumption);
assert_eq!(f2.line, 17);
assert!(f.fact(4).is_none());
assert!(f.fact(0).is_none());
}
#[test]
fn urls_are_front_matter_plus_https_in_facts() {
let f = canon::parse("tabula", TABULA).unwrap();
assert_eq!(
f.urls(),
vec![
"https://aula.marek-novak.cz/tabula/".to_string(),
"https://aula.marek-novak.cz/tabula/limits".to_string(),
]
);
}
#[test]
fn http_urls_in_facts_are_not_allowed() {
let text = with_front(FRONT, "- [F1] See http://example.com/x and https://example.com/y.\n");
let f = canon::parse("tabula", &text).unwrap();
assert_eq!(f.urls(), vec!["https://example.com/y".to_string()]);
}
#[test]
fn site_and_status_values() {
for (s, st) in [("released", Status::Released), ("beta", Status::Beta), ("planned", Status::Planned)] {
let front = FRONT.replace("status: beta", &format!("status: {s}"));
let text = with_front(&format!("{front}site: https://tabula.example/\n"), "");
let f = canon::parse("tabula", &text).unwrap();
assert_eq!(f.front.status, st);
assert_eq!(f.front.site.as_deref(), Some("https://tabula.example/"));
assert!(f.facts.is_empty());
}
}
#[test]
fn rejects_bad_status() {
let front = FRONT.replace("status: beta", "status: Released");
assert_eq!(code("tabula", &with_front(&front, "")), (8, CanonCode::BadStatus("Released".into())));
}
#[test]
fn rejects_missing_unknown_duplicate_and_empty_keys() {
let front = FRONT.replace("price: free\n", "");
assert_eq!(code("tabula", &with_front(&front, "")).1, CanonCode::MissingKey("price".into()));
let front = format!("{FRONT}colour: brass\n");
assert_eq!(code("tabula", &with_front(&front, "")), (9, CanonCode::UnknownKey("colour".into())));
let front = format!("{FRONT}name: Other\n");
assert_eq!(code("tabula", &with_front(&front, "")), (9, CanonCode::DuplicateKey("name".into())));
let front = FRONT.replace("price: free", "price:");
assert_eq!(code("tabula", &with_front(&front, "")).1, CanonCode::EmptyValue("price".into()));
let front = FRONT.replace("price: free", "price: ");
assert_eq!(code("tabula", &with_front(&front, "")).1, CanonCode::EmptyValue("price".into()));
}
#[test]
fn rejects_non_flat_front_matter() {
for bad in ["just text", " indented: yes", "list:\n - a", "", "# comment", "Name: Tabula", "key:value"] {
let front = format!("{FRONT}{bad}\n");
let (line, c) = code("tabula", &with_front(&front, ""));
assert_eq!(line, 9, "{bad:?}");
assert!(
matches!(c, CanonCode::FrontMatterLine | CanonCode::UnknownKey(_)),
"{bad:?} gave {c:?}"
);
}
}
#[test]
fn rejects_missing_or_unclosed_front_matter() {
assert_eq!(code("tabula", "# Tabula\n- [F1] x\n"), (1, CanonCode::NoFrontMatter));
assert_eq!(code("tabula", ""), (1, CanonCode::NoFrontMatter));
assert_eq!(code("tabula", " ---\n"), (1, CanonCode::NoFrontMatter));
assert_eq!(code("tabula", &format!("---\n{FRONT}")).1, CanonCode::UnclosedFrontMatter);
}
#[test]
fn id_must_match_stem_and_be_valid() {
assert_eq!(
code("other", &with_front(FRONT, "")),
(1, CanonCode::IdMismatch { id: "tabula".into(), stem: "other".into() })
);
for bad in ["Tabula", "-tabula", "tabula-", "tab_ula", "tab ula", "a234567890123456789012345678901234"] {
let front = FRONT.replace("id: tabula", &format!("id: {bad}"));
let c = code(bad, &with_front(&front, "")).1;
assert_eq!(c, CanonCode::BadId(bad.trim().into()), "{bad:?}");
}
assert!(canon::is_valid_app_id("a"));
assert!(canon::is_valid_app_id("my-app-2"));
assert!(canon::is_valid_app_id("a2345678901234567890123456789012"));
assert!(!canon::is_valid_app_id(""));
assert!(!canon::is_valid_app_id("a23456789012345678901234567890123"));
assert!(!canon::is_valid_app_id("é"));
}
#[test]
fn urls_in_front_matter_must_be_https() {
for bad in ["http://aula.example/", "aula.example", "https://a b", "https://"] {
let text = with_front(&format!("{FRONT}aula: {bad}\n"), "");
assert_eq!(code("tabula", &text).1, CanonCode::BadUrl(bad.into()), "{bad:?}");
}
}
#[test]
fn rejects_malformed_fact_lines() {
for bad in [
"- [F] no number",
"- [Fx] letters",
"- [F1]no space",
"- [F1 missing bracket",
"- [F1]",
"- [f1] lowercase",
"- [F1] two spaces",
"* [F1] star bullet",
" - [F1] indented",
"- [F1a] suffix",
"- [F-1] negative",
] {
let text = with_front(FRONT, &format!("\n{bad}\n"));
let (line, c) = code("tabula", &text);
assert_eq!(line, 10, "{bad:?}");
assert!(
matches!(c, CanonCode::MalformedFact | CanonCode::EmptyFact),
"{bad:?} gave {c:?}"
);
}
}
#[test]
fn fact_ids_in_range_without_leading_zeros() {
let ok = with_front(FRONT, "- [F1] a\n- [F9999] b\n");
let f = canon::parse("tabula", &ok).unwrap();
assert_eq!(f.facts.iter().map(|x| x.id).collect::<Vec<_>>(), vec![1, 9999]);
for bad in ["- [F0] zero", "- [F10000] big", "- [F01] lead", "- [F99999999999999999999] huge"] {
let text = with_front(FRONT, &format!("{bad}\n"));
assert_eq!(code("tabula", &text), (9, CanonCode::FactIdOutOfRange), "{bad:?}");
}
}
#[test]
fn rejects_duplicate_facts_and_empty_facts() {
let text = with_front(FRONT, "- [F1] a\n## Limits\n- [F1] b\n");
assert_eq!(code("tabula", &text), (11, CanonCode::DuplicateFact(1)));
let text = with_front(FRONT, "- [F1] \n");
assert_eq!(code("tabula", &text), (9, CanonCode::EmptyFact));
let text = with_front(FRONT, "- [F1] (assumption)\n");
assert_eq!(code("tabula", &text), (9, CanonCode::EmptyFact));
}
#[test]
fn assumption_marker() {
let text = with_front(
FRONT,
"- [F1] Plain.\n- [F2] Unsure. (assumption)\n- [F3] Odd case (Assumption)\n\
- [F4] Inside (assumption) the text.\n- [F5] Trailing spaces (assumption) \n",
);
let f = canon::parse("tabula", &text).unwrap();
let got: Vec<(&str, bool)> = f.facts.iter().map(|x| (x.text.as_str(), x.assumption)).collect();
assert_eq!(
got,
vec![
("Plain.", false),
("Unsure.", true),
("Odd case", true),
("Inside (assumption) the text.", true),
("Trailing spaces", true),
]
);
}
#[test]
fn other_body_lines_are_ignored() {
let text = with_front(FRONT, "# T\n\nSome prose [F7] here.\n- plain bullet\n> - [F9] quoted\n- [F1] fact\n");
let f = canon::parse("tabula", &text).unwrap();
assert_eq!(f.facts.len(), 1);
}
#[test]
fn size_limit_is_64_kib() {
let mut text = with_front(FRONT, "");
while text.len() < canon::MAX_FILE_BYTES {
text.push('\n');
}
assert_eq!(text.len(), canon::MAX_FILE_BYTES);
assert!(canon::parse("tabula", &text).is_ok());
text.push('\n');
assert_eq!(code("tabula", &text), (0, CanonCode::TooLarge { bytes: canon::MAX_FILE_BYTES + 1 }));
}
#[test]
fn a_huge_line_is_fine_under_the_limit_and_rejected_over_it() {
let long = "a".repeat(60 * 1024);
let text = with_front(FRONT, &format!("- [F1] {long}\n"));
assert_eq!(canon::parse("tabula", &text).unwrap().facts[0].text.len(), long.len());
let long = "a".repeat(70 * 1024);
let text = with_front(FRONT, &format!("- [F1] {long}\n"));
assert!(matches!(code("tabula", &text).1, CanonCode::TooLarge { .. }));
}
#[test]
fn bom_and_crlf_are_tolerated() {
let crlf = TABULA.replace('\n', "\r\n");
let a = canon::parse("tabula", TABULA).unwrap();
let b = canon::parse("tabula", &crlf).unwrap();
assert_eq!(a, b);
let bom = format!("\u{feff}{TABULA}");
assert_eq!(canon::parse("tabula", &bom).unwrap(), a);
}
#[test]
fn lone_cr_nul_and_hidden_characters_are_rejected() {
let text = with_front(FRONT, "- [F1] a\rb\n");
assert_eq!(code("tabula", &text), (9, CanonCode::LoneCarriageReturn));
for (ch, cp) in [
('\0', 0u32),
('\u{7}', 7),
('\u{7f}', 0x7f),
('\u{85}', 0x85),
('\u{202e}', 0x202e),
('\u{2066}', 0x2066),
('\u{200f}', 0x200f),
('\u{061c}', 0x061c),
('\u{200b}', 0x200b),
('\u{feff}', 0xfeff),
('\u{e0041}', 0xe0041),
] {
let text = with_front(FRONT, &format!("- [F1] a{ch}b\n"));
assert_eq!(code("tabula", &text), (9, CanonCode::ForbiddenCharacter { codepoint: cp }), "{cp:X}");
}
// In the front matter too.
let front = FRONT.replace("name: Tabula", "name: Tab\u{202e}ula");
assert_eq!(code("tabula", &with_front(&front, "")), (3, CanonCode::ForbiddenCharacter { codepoint: 0x202e }));
// Tabs and ordinary non-ASCII text are fine.
let text = with_front(FRONT, "- [F1] Poznámky\tžluťoučký kůň 📝\n");
assert!(canon::parse("tabula", &text).is_ok());
}
#[test]
fn canon_set() {
let mut c = Canon::new();
c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap();
let err = c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap_err();
assert_eq!(err.code, CanonCode::DuplicateApp("tabula".into()));
c.insert(CanonFile::adhoc("release", "Tabula", vec![(1, "Tabula 1.2 is out.".into())])).unwrap();
assert_eq!(c.apps().map(|f| f.id.as_str()).collect::<Vec<_>>(), vec!["release", "tabula"]);
assert!(c.get("tabula").is_some());
assert!(c.get("nope").is_none());
assert_eq!(c.fact("tabula", 1).unwrap().text, "Tabula keeps notes on your own computer.");
assert!(c.fact("tabula", 9).is_none());
assert!(c.fact("nope", 1).is_none());
let urls = c.allowed_urls();
assert!(urls.contains("https://aula.marek-novak.cz/tabula/"));
assert!(urls.contains("https://aula.marek-novak.cz/tabula/limits"));
assert_eq!(urls.len(), 2);
}
#[test]
fn adhoc_release_file() {
let f = CanonFile::adhoc(
"release",
"Tabula",
vec![(1, "Tabula 1.2 is out.".into()), (2, "Faster search. (assumption)".into())],
);
assert_eq!(f.id, "release");
assert_eq!(f.front.name, "Tabula");
assert_eq!(f.facts.len(), 2);
assert!(f.facts.iter().all(|x| !x.assumption), "release facts count as confirmed");
assert_eq!(f.fact(2).unwrap().text, "Faster search. (assumption)");
}
+294
View File
@@ -0,0 +1,294 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
use scaena_core::canon::{self, Canon, CanonFile};
use scaena_core::claims::{self, Problem, Ref};
const TABULA: &str = "---
id: tabula
name: Tabula
one_liner: Notes that stay on your own computer.
audience: People who want notes without an account.
price: (assumption) one-time purchase
clicks: New note in 1 click.
status: released
aula: https://aula.marek-novak.cz/tabula/
---
- [F1] Tabula keeps notes on your own computer.
- [F2] It syncs between your devices without a cloud account. (assumption)
- [F3] It runs on Windows. More: https://aula.marek-novak.cz/tabula/windows
- [F7] A new note takes 1 click.
";
fn canon() -> Canon {
let mut c = Canon::new();
c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap();
c.insert(CanonFile::adhoc(
"release",
"Tabula",
vec![(1, "Tabula 1.2 is out.".into()), (2, "Search is faster.".into())],
))
.unwrap();
c
}
fn r(app: &str, fact: u32) -> Ref {
Ref { app: app.into(), fact }
}
fn unsourced(text: &str) -> bool {
let rep = claims::check(text, &canon());
!rep.ok() && rep.problems.iter().all(|p| matches!(p, Problem::Unsourced { .. }))
}
fn passes(text: &str) -> bool {
claims::check(text, &canon()).ok()
}
#[test]
fn sourced_sentences_pass_and_refs_are_collected() {
let c = canon();
let rep = claims::check(
"Tabula keeps your notes on your computer [tabula#F1]. A new note takes 1 click.[tabula#F7][tabula#F1] \
Tabula 1.2 is out! [release#F1]",
&c,
);
assert!(rep.ok(), "{:?}", rep.problems);
assert_eq!(rep.refs, vec![r("release", 1), r("tabula", 1), r("tabula", 7)]);
}
#[test]
fn numbers_prices_platforms_and_features_need_refs() {
for s in [
"Tabula 1.2 is out.",
"A new note takes 1 click.",
"It costs $5.",
"Only 5 € once.",
"It costs five dollars.",
"Pay once, own it forever.",
"It runs on Windows.",
"Now on Linux and macOS.",
"Coming to Android and iOS.",
"Install it as a PWA.",
"Works in your browser.",
"Use it on your phone.",
"A desktop app.",
"Runs on your home server.",
"It syncs between your devices.",
"Tabula keeps notes on your own computer.",
"No account needed",
"The fastest notes app ever made!",
"Search is faster now.",
"Tabula",
"Tabula is free.",
"100% private",
"Your notes never leave your computer?",
"Ten times faster",
"I made this for myself.",
"#tabula",
] {
assert!(unsourced(s), "{s:?} must be rejected as unsourced");
}
}
#[test]
fn plain_sentences_pass_without_refs() {
for s in [
"Here's what's new.",
"Here’s what’s new:",
"What's new",
"Try it today.",
"Try it today! 🎉",
"Try Tabula today.",
"try it now",
"Check it out.",
"Learn more.",
"Read more: https://aula.marek-novak.cz/tabula/",
"Get it here: https://aula.marek-novak.cz/tabula/",
"Thanks for reading.",
"Let me know what you think.",
"Feedback welcome.",
"🎉",
"---",
"",
" \n\n ",
] {
let rep = claims::check(s, &canon());
assert!(rep.ok(), "{s:?} should pass: {:?}", rep.problems);
}
}
#[test]
fn a_plain_phrase_with_anything_extra_needs_a_ref() {
for s in [
"Try it today on Windows.",
"Try it today for $5.",
"Try it today, it's free.",
"Here's what's new in 1.2.",
"Try the fastest notes app today.",
"Try it 2day.",
"#tabula #windows",
] {
assert!(unsourced(s), "{s:?} must be rejected");
}
}
#[test]
fn every_sentence_is_checked_separately() {
let c = canon();
let rep = claims::check("Tabula keeps notes local [tabula#F1]. It runs on Linux. Try it today.", &c);
assert_eq!(rep.problems, vec![Problem::Unsourced { sentence: "It runs on Linux.".into() }]);
// Lines are sentences too.
let rep = claims::check("Tabula 1.2 [release#F1]\nFaster search", &c);
assert_eq!(rep.problems, vec![Problem::Unsourced { sentence: "Faster search".into() }]);
}
#[test]
fn decimals_and_urls_do_not_split_sentences() {
let c = canon();
assert_eq!(claims::sentences("Tabula 1.2 is out. Try it."), vec!["Tabula 1.2 is out.", "Try it."]);
assert_eq!(
claims::sentences("See https://aula.marek-novak.cz/tabula/?a=1. Thanks!"),
vec!["See https://aula.marek-novak.cz/tabula/?a=1.", "Thanks!"]
);
assert_eq!(claims::sentences("A. [tabula#F1] B"), vec!["A. [tabula#F1]", "B"]);
assert!(claims::check("Tabula 1.2 is out. [release#F1]", &c).ok());
}
#[test]
fn bad_refs_are_rejected() {
let c = canon();
let rep = claims::check("Tabula keeps notes local. [tabula#F99]", &c);
assert_eq!(rep.problems, vec![Problem::MissingFact { r: r("tabula", 99) }]);
let rep = claims::check("Notes, done. [notapp#F1]", &c);
assert_eq!(rep.problems, vec![Problem::UnknownApp { r: r("notapp", 1) }]);
let rep = claims::check("It syncs everywhere. [tabula#F2]", &c);
assert_eq!(rep.problems, vec![Problem::Unconfirmed { r: r("tabula", 2) }]);
// A bad ref fails even on a plain sentence.
let rep = claims::check("Try it today. [tabula#F99]", &c);
assert_eq!(rep.problems, vec![Problem::MissingFact { r: r("tabula", 99) }]);
// One good ref does not excuse a bad one.
let rep = claims::check("Local notes. [tabula#F1][tabula#F2]", &c);
assert_eq!(rep.problems, vec![Problem::Unconfirmed { r: r("tabula", 2) }]);
}
#[test]
fn malformed_refs_are_rejected() {
let c = canon();
for bad in [
"[F1]",
"[tabula#f1]",
"[Tabula#F1]",
"[tabula #F1]",
"[tabula#F01]",
"[tabula#F0]",
"[tabula#F10000]",
"[tabula#1]",
"[tabula#F1",
"[#F1]",
"[tabula#]",
"[tabula_x#F1]",
"tabula#F1",
"[tabula#F1 ]",
] {
let text = format!("Tabula keeps notes on your own computer. {bad}");
let rep = claims::check(&text, &c);
assert!(
rep.problems.iter().any(|p| matches!(p, Problem::MalformedRef { .. })),
"{bad:?}: {:?}",
rep.problems
);
assert!(!rep.ok());
}
}
#[test]
fn urls_must_come_from_the_canon() {
let c = canon();
assert!(claims::check("Get it here: https://aula.marek-novak.cz/tabula/", &c).ok());
assert!(claims::check("Get it here: https://aula.marek-novak.cz/tabula", &c).ok());
assert!(claims::check("Read more: https://aula.marek-novak.cz/tabula/windows.", &c).ok());
assert!(claims::check("Read more: (https://aula.marek-novak.cz/tabula/windows)", &c).ok());
for (text, url) in [
("Get it here: https://evil.example/tabula", "https://evil.example/tabula"),
("Get it here: http://aula.marek-novak.cz/tabula/", "http://aula.marek-novak.cz/tabula/"),
("Get it here: https://aula.marek-novak.cz/tabula/x", "https://aula.marek-novak.cz/tabula/x"),
("Get it here: www.evil.example", "www.evil.example"),
("Get it here: evil.com", "evil.com"),
("Get it here: evil.example/download", "evil.example/download"),
("Get it here: ftp://evil.example", "ftp://evil.example"),
] {
let rep = claims::check(text, &c);
assert!(
rep.problems.contains(&Problem::UrlNotInCanon { url: url.into() }),
"{text:?}: {:?}",
rep.problems
);
}
// A URL in a sourced sentence is still checked.
let rep = claims::check("It runs on Windows, see https://evil.example/ [tabula#F3]", &c);
assert_eq!(rep.problems, vec![Problem::UrlNotInCanon { url: "https://evil.example/".into() }]);
// A bare form of an allowed URL is fine.
assert!(claims::check("Get it here: aula.marek-novak.cz/tabula/", &c).ok());
}
#[test]
fn hidden_characters_are_rejected() {
let c = canon();
let rep = claims::check("Try it today.\u{202e}", &c);
assert_eq!(rep.problems, vec![Problem::HiddenCharacter { codepoint: 0x202e }]);
let rep = claims::check("Try it\0 today.", &c);
assert!(rep.problems.contains(&Problem::HiddenCharacter { codepoint: 0 }));
// CRLF and tabs are ordinary whitespace.
assert!(claims::check("Try it today.\r\nThanks!\t", &c).ok());
}
#[test]
fn reasons_are_plain_english() {
let c = canon();
let rep = claims::check(
"It runs on Linux. Local. [tabula#F99] Sync. [x#F1] Sync. [tabula#F2] [F3] https://evil.example/",
&c,
);
let reasons: Vec<String> = rep.problems.iter().map(Problem::reason).collect();
assert!(reasons.iter().any(|s| s.contains("It runs on Linux.") && s.contains("no source")), "{reasons:?}");
assert!(reasons.iter().any(|s| s.contains("tabula#F99") && s.contains("does not exist")), "{reasons:?}");
assert!(reasons.iter().any(|s| s.contains("unknown app") && s.contains("x")), "{reasons:?}");
assert!(reasons.iter().any(|s| s.contains("unconfirmed fact") && s.contains("tabula#F2")), "{reasons:?}");
assert!(reasons.iter().any(|s| s.contains("[F3]")), "{reasons:?}");
assert!(reasons.iter().any(|s| s.contains("https://evil.example/") && s.contains("not in the canon")), "{reasons:?}");
assert_eq!(
Problem::HiddenCharacter { codepoint: 0x202e }.reason(),
"Hidden or direction-changing character U+202E."
);
}
#[test]
fn problems_are_not_repeated() {
let c = canon();
let rep = claims::check("A. [tabula#F99] B. [tabula#F99]", &c);
assert_eq!(rep.problems, vec![Problem::MissingFact { r: r("tabula", 99) }]);
}
#[test]
fn strip_refs_for_display() {
assert_eq!(
claims::strip_refs("Tabula keeps notes local [tabula#F1]. One click.[tabula#F7][tabula#F1] Done [release#F1]"),
"Tabula keeps notes local. One click. Done"
);
assert_eq!(claims::strip_refs("Tabula [tabula#F1] keeps notes."), "Tabula keeps notes.");
assert_eq!(claims::strip_refs("A.[tabula#F1]B"), "A. B");
assert_eq!(claims::strip_refs("Line one [tabula#F1]\nLine two"), "Line one\nLine two");
assert_eq!(claims::strip_refs("Keep [beta] and [Tabula#F1]."), "Keep [beta] and [Tabula#F1].");
assert_eq!(claims::strip_refs(""), "");
assert_eq!(claims::strip_refs("Žluťoučký [tabula#F1]kůň"), "Žluťoučký kůň");
}
#[test]
fn stripped_text_of_a_passing_text_has_no_refs() {
let c = canon();
let text = "Local notes [tabula#F1]. Try it today.";
assert!(claims::check(text, &c).ok());
let stripped = claims::strip_refs(text);
assert!(claims::check(&stripped, &c).refs.is_empty());
}
+158
View File
@@ -0,0 +1,158 @@
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
use std::collections::BTreeMap;
use scaena_core::hooks::{self, Genome, HookError, Opening};
const HOOKS: &str = "# Hook templates
Prose is ignored.
- [H1] Tired of {pain}? {app} fixes it.
- [H2] {number} reasons {audience} love {app}.
- [H3] Try {feature} in {clicks}.
- [H4] {app} now runs on {platform}.
- [H5] Stop losing notes.
";
fn values(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
}
#[test]
fn parses_templates_with_slots_in_order() {
let hs = hooks::parse(HOOKS).unwrap();
assert_eq!(hs.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(), vec!["H1", "H2", "H3", "H4", "H5"]);
assert_eq!(hs[0].text, "Tired of {pain}? {app} fixes it.");
assert_eq!(hs[0].slots, vec!["pain", "app"]);
assert_eq!(hs[1].slots, vec!["number", "audience", "app"]);
assert!(hs[4].slots.is_empty());
}
#[test]
fn slots_are_unique() {
let hs = hooks::parse("- [H1] {app} and {app} and {feature}\n").unwrap();
assert_eq!(hs[0].slots, vec!["app", "feature"]);
}
#[test]
fn every_fixed_slot_is_allowed() {
let line = format!("- [H1] {}\n", hooks::SLOTS.map(|s| format!("{{{s}}}")).join(" "));
let hs = hooks::parse(&line).unwrap();
assert_eq!(hs[0].slots, hooks::SLOTS.to_vec());
}
#[test]
fn unknown_slots_are_errors() {
for (bad, slot) in [("{price}", "price"), ("{App}", "App"), ("{}", ""), ("{ app }", " app "), ("{url}", "url")] {
let md = format!("# x\n- [H1] Hello {bad}\n");
assert_eq!(
hooks::parse(&md),
Err(HookError::UnknownSlot { line: 2, slot: slot.into() }),
"{bad:?}"
);
}
}
#[test]
fn unbalanced_braces_are_errors() {
for bad in ["{app", "app}", "{{app}}", "{a{pp}", "}{"] {
let md = format!("- [H1] Hi {bad}\n");
assert_eq!(hooks::parse(&md), Err(HookError::UnbalancedBrace { line: 1 }), "{bad:?}");
}
}
#[test]
fn malformed_duplicate_and_empty_lines() {
for bad in ["- [H] x", "- [Hx] x", "- [H1]x", "- [H1 x", "- [h1] x", " - [H1] x", "- [H1] x"] {
assert_eq!(hooks::parse(&format!("{bad}\n")), Err(HookError::Malformed { line: 1 }), "{bad:?}");
}
for bad in ["- [H0] x", "- [H01] x", "- [H10000] x"] {
assert_eq!(hooks::parse(&format!("{bad}\n")), Err(HookError::IdOutOfRange { line: 1 }), "{bad:?}");
}
assert_eq!(
hooks::parse("- [H1] a\n- [H1] b\n"),
Err(HookError::Duplicate { line: 2, id: "H1".into() })
);
assert_eq!(hooks::parse("- [H1] \n"), Err(HookError::Empty { line: 1 }));
assert_eq!(hooks::parse("- [H1]\n"), Err(HookError::Malformed { line: 1 }));
}
#[test]
fn hostile_input() {
let big = format!("- [H1] {}\n", "a".repeat(hooks::MAX_FILE_BYTES));
assert!(matches!(hooks::parse(&big), Err(HookError::TooLarge { .. })));
assert_eq!(
hooks::parse("- [H1] a\u{202e}b\n"),
Err(HookError::ForbiddenCharacter { line: 1, codepoint: 0x202e })
);
assert_eq!(hooks::parse("x\n- [H1] a\0b\n"), Err(HookError::ForbiddenCharacter { line: 2, codepoint: 0 }));
let crlf = HOOKS.replace('\n', "\r\n");
assert_eq!(hooks::parse(&crlf).unwrap(), hooks::parse(HOOKS).unwrap());
let bom = format!("\u{feff}{HOOKS}");
assert_eq!(hooks::parse(&bom).unwrap(), hooks::parse(HOOKS).unwrap());
assert_eq!(hooks::parse("").unwrap(), vec![]);
}
#[test]
fn fill_replaces_every_slot() {
let hs = hooks::parse(HOOKS).unwrap();
let v = values(&[("pain", "lost notes"), ("app", "Tabula"), ("unused", "x")]);
assert_eq!(hs[0].fill(&v).unwrap(), "Tired of lost notes? Tabula fixes it.");
assert_eq!(hs[4].fill(&BTreeMap::new()).unwrap(), "Stop losing notes.");
}
#[test]
fn fill_missing_value_is_an_error() {
let hs = hooks::parse(HOOKS).unwrap();
let v = values(&[("app", "Tabula")]);
assert_eq!(hs[0].fill(&v), Err(HookError::MissingValue { slot: "pain".into() }));
}
#[test]
fn fill_does_not_re_expand_braces_in_values() {
let hs = hooks::parse(HOOKS).unwrap();
let v = values(&[("pain", "{app}"), ("app", "{pain} {x}")]);
assert_eq!(hs[0].fill(&v).unwrap(), "Tired of {app}? {pain} {x} fixes it.");
}
#[test]
fn genome_from_text() {
let hs = hooks::parse(HOOKS).unwrap();
assert_eq!(
hs[0].genome,
Genome { opening: Opening::Question, words: 6, has_number: false, lead_verb: None }
);
assert_eq!(
hs[1].genome,
Genome { opening: Opening::Number, words: 5, has_number: true, lead_verb: None }
);
assert_eq!(
hs[2].genome,
Genome { opening: Opening::Command, words: 4, has_number: false, lead_verb: Some("try".into()) }
);
assert_eq!(
hs[3].genome,
Genome { opening: Opening::Statement, words: 5, has_number: false, lead_verb: None }
);
assert_eq!(hs[4].genome.opening, Opening::Command);
assert_eq!(hs[4].genome.lead_verb.as_deref(), Some("stop"));
}
#[test]
fn genome_of_filled_text() {
let g = Genome::of("3 clicks to a new note.");
assert_eq!(g.opening, Opening::Number);
assert!(g.has_number);
assert_eq!(g.words, 6);
let g = Genome::of("Why do notes need an account?");
assert_eq!(g.opening, Opening::Question);
let g = Genome::of("Your notes, on your computer. Ever wondered why?");
assert_eq!(g.opening, Opening::Statement);
let g = Genome::of("");
assert_eq!(g, Genome { opening: Opening::Statement, words: 0, has_number: false, lead_verb: None });
let g = Genome::of("Meet Tabula 2.");
assert_eq!(g.opening, Opening::Command);
assert!(g.has_number);
}
+221
View File
@@ -0,0 +1,221 @@
// 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();
prop_assert!(!filled.contains("{feature}"));
}
}
}
#[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());
}
}