Files
CustosPublic/crates/custos-gen/tests/mandatory.rs
T

262 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The mandatory generator tests (CLAUDE.md).
use custos_gen::{
ClassRule, EFF_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions, WordKind,
memorable, memorable_entropy, nickname, nickname_parts, normalize_name, pin, random, strict,
};
use regex::Regex;
use std::collections::HashSet;
const SAMPLES: usize = 10_000;
#[test]
fn eff_list_is_complete_and_plain() {
assert_eq!(EFF_WORDS.len(), 7_776);
let unique: HashSet<_> = EFF_WORDS.iter().collect();
assert_eq!(unique.len(), 7_776, "a word repeats after removing hyphens");
assert!(EFF_WORDS.iter().all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase())));
}
#[test]
fn memorable_default_shape() {
let o = MemorableOptions::default();
assert_eq!((o.words, o.digit_after_word, o.capitalize, o.separator), (4, true, true, Separator::Hyphen));
let re = Regex::new(r"^[A-Z][a-z]+[0-9](-[A-Z][a-z]+[0-9]){3}$").unwrap();
for _ in 0..1_000 {
let g = memorable(&o);
assert!(re.is_match(g.value.expose()), "{}", g.value.expose());
}
}
#[test]
fn memorable_shape_at_every_slider_value_and_option() {
let seps = [
(Separator::Hyphen, "-"),
(Separator::Space, " "),
(Separator::Period, r"\."),
(Separator::Comma, ","),
(Separator::Underscore, "_"),
(Separator::Digit, "[0-9]"),
(Separator::DigitOrSymbol, r"[0-9!@#$%^&*\-_=+?]"),
];
for words in 3..=10u8 {
for (sep, sep_re) in seps {
for (digit, cap) in [(true, true), (false, true), (true, false), (false, false)] {
let o = MemorableOptions { words, digit_after_word: digit, capitalize: cap, separator: sep };
let word =
format!("{}{}", if cap { "[A-Z][a-z]+" } else { "[a-z]+" }, if digit { "[0-9]" } else { "" });
let re = Regex::new(&format!("^{word}({sep_re}{word}){{{}}}$", words - 1)).unwrap();
for _ in 0..20 {
let g = memorable(&o);
assert!(re.is_match(g.value.expose()), "{o:?}: {}", g.value.expose());
}
}
}
}
}
#[test]
fn memorable_entropy_counts_only_random_choices() {
let per_word = 7_776f64.log2() + 10f64.log2();
for words in 3..=10u8 {
let o = MemorableOptions { words, ..Default::default() };
let e = memorable_entropy(&o);
assert!((e - words as f64 * per_word).abs() < 1e-9, "{words}: {e}");
assert!((memorable(&o).entropy_bits - e).abs() < 1e-9);
// Capitalising every word is not a random choice: it adds nothing.
let lower = MemorableOptions { capitalize: false, ..o };
assert!((memorable_entropy(&lower) - e).abs() < 1e-9);
}
let four = memorable_entropy(&MemorableOptions::default());
assert!((64.0..66.0).contains(&four), "4 words with digits is about 65 bits: {four}");
let no_digits = MemorableOptions { digit_after_word: false, ..Default::default() };
assert!((memorable_entropy(&no_digits) - 4.0 * 7_776f64.log2()).abs() < 1e-9);
// A random-digit separator is a random choice per gap.
let digit_sep = MemorableOptions { separator: Separator::Digit, ..Default::default() };
assert!((memorable_entropy(&digit_sep) - (four + 3.0 * 10f64.log2())).abs() < 1e-9);
}
#[test]
fn nickname_default_template_with_diacritics() {
let o = NicknameOptions::default();
assert_eq!(o.template, "{Name}.{Word}.{Number}");
assert_eq!(o.kinds, vec![WordKind::Noun]);
assert_eq!(o.digits, 2);
let re = Regex::new(r"^CeskaSporitelna\.[A-Z][a-z]+\.[0-9]{2}$").unwrap();
let nouns: HashSet<&str> = custos_gen::words(WordKind::Noun).iter().copied().collect();
for _ in 0..1_000 {
let n = nickname("Česká spořitelna", &o).unwrap();
let s = n.value.expose();
assert!(re.is_match(s), "{s}");
let word = s.split('.').nth(1).unwrap().to_lowercase();
assert!(nouns.contains(word.as_str()), "{word} is not from the noun list");
}
let gh = nickname("GitHub", &o).unwrap();
assert!(Regex::new(r"^GitHub\.[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(gh.value.expose()));
}
#[test]
fn nickname_word_comes_from_the_selected_kinds() {
for kinds in [vec![WordKind::Adjective], vec![WordKind::Verb], vec![WordKind::Adjective, WordKind::Verb]] {
let allowed: HashSet<&str> = kinds.iter().flat_map(|k| custos_gen::words(*k).iter().copied()).collect();
let o = NicknameOptions { template: "{Word}".into(), kinds: kinds.clone(), ..Default::default() };
for _ in 0..500 {
let w = nickname("x", &o).unwrap().value.expose().to_lowercase();
assert!(allowed.contains(w.as_str()), "{w} not in {kinds:?}");
}
}
}
#[test]
fn nickname_without_title_drops_name_and_its_separator() {
let d = NicknameOptions::default();
let re = Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap();
for title in ["", " ", "!!!"] {
let s = nickname(title, &d).unwrap().value.expose().to_owned();
assert!(re.is_match(&s), "{title:?} -> {s}");
}
let o = NicknameOptions { template: "{Word}_{Name}{Number}".into(), ..Default::default() };
let s = nickname("", &o).unwrap().value.expose().to_owned();
assert!(Regex::new(r"^[A-Z][a-z]+[0-9]{2}$").unwrap().is_match(&s), "{s}");
let s = nickname("Proton Mail", &o).unwrap().value.expose().to_owned();
assert!(Regex::new(r"^[A-Z][a-z]+_ProtonMail[0-9]{2}$").unwrap().is_match(&s), "{s}");
}
#[test]
fn nickname_options_and_entropy() {
for digits in 1..=4u8 {
let o = NicknameOptions { template: "{Number}".into(), digits, ..Default::default() };
let n = nickname("x", &o).unwrap();
assert_eq!(n.value.expose().len(), digits as usize);
assert!((n.entropy_bits - digits as f64 * 10f64.log2()).abs() < 1e-9);
}
let d = nickname("GitHub", &NicknameOptions::default()).unwrap();
let nouns = custos_gen::words(WordKind::Noun).len() as f64;
assert!((d.entropy_bits - (nouns.log2() + 2.0 * 10f64.log2())).abs() < 1e-9, "the name adds nothing");
let leet = NicknameOptions { leet: true, ..Default::default() };
let l = nickname("GitHub", &leet).unwrap();
assert!((l.entropy_bits - d.entropy_bits).abs() < 1e-9, "leetspeak on a known pattern adds nothing");
assert!(nickname("x", &NicknameOptions { template: "{Bogus}".into(), ..Default::default() }).is_err());
assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err());
}
#[test]
fn nickname_parts_keep_word_and_number_while_the_title_changes() {
let o = NicknameOptions::default();
let parts = nickname_parts(&o).unwrap();
let typed: Vec<String> = ["", "G", "Gi", "GitHub"].iter().map(|t| parts.render(t, &o.template).unwrap()).collect();
let tail = typed[0].clone(); // "Lantern.47": no title, so {Name} and its "." are left out
assert!(Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(&tail), "{tail}");
assert_eq!(typed[1], format!("G.{tail}"));
assert_eq!(typed[3], format!("GitHub.{tail}"));
assert!(parts.render("x", "{Word}{Word}").is_err(), "a template with more tokens than parts");
}
#[test]
fn name_normalisation() {
assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna");
assert_eq!(normalize_name("GitHub"), "GitHub");
assert_eq!(normalize_name("proton mail"), "ProtonMail");
assert_eq!(normalize_name("Žluťoučký kůň úpěl ďábelské ódy"), "ZlutouckyKunUpelDabe");
assert_eq!(normalize_name(" "), "");
assert_eq!(normalize_name("Straße 42"), "Strasse42");
assert!(normalize_name("A very long name that goes on and on").len() <= 20);
}
#[test]
fn word_lists_are_plain_and_unique() {
for k in [WordKind::Adjective, WordKind::Noun, WordKind::Verb] {
let w = custos_gen::words(k);
assert!(w.len() >= 150, "{k:?}: {}", w.len());
let unique: HashSet<_> = w.iter().collect();
assert_eq!(unique.len(), w.len(), "{k:?} has duplicates");
assert!(w.iter().all(|s| s.len() >= 3 && s.bytes().all(|b| b.is_ascii_lowercase())), "{k:?}");
}
}
#[test]
fn strict_site_template_is_never_violated() {
let o = StrictOptions {
length: 12,
lower: ClassRule::Require,
upper: ClassRule::Require,
digits: ClassRule::Require,
symbols: ClassRule::Require,
allowed_symbols: "!#$".into(),
};
let allowed: HashSet<char> = ('a'..='z').chain('A'..='Z').chain('0'..='9').chain("!#$".chars()).collect();
for _ in 0..SAMPLES {
let g = strict(&o).unwrap();
let s = g.value.expose();
assert_eq!(s.chars().count(), 12, "{s}");
assert!(s.chars().all(|c| allowed.contains(&c)), "{s}");
assert!(s.chars().any(|c| c.is_ascii_lowercase()), "{s}");
assert!(s.chars().any(|c| c.is_ascii_uppercase()), "{s}");
assert!(s.chars().any(|c| c.is_ascii_digit()), "{s}");
assert!(s.chars().any(|c| "!#$".contains(c)), "{s}");
}
// Excluded classes never appear.
let digits_only = StrictOptions {
length: 6,
lower: ClassRule::Exclude,
upper: ClassRule::Exclude,
digits: ClassRule::Require,
symbols: ClassRule::Exclude,
allowed_symbols: String::new(),
};
for _ in 0..SAMPLES {
assert!(strict(&digits_only).unwrap().value.expose().bytes().all(|b| b.is_ascii_digit()));
}
// More required classes than characters cannot be satisfied.
assert!(strict(&StrictOptions { length: 3, ..o.clone() }).is_err());
// Entropy counts only strings that satisfy the rules: less than length × log2(alphabet).
let e = strict(&o).unwrap().entropy_bits;
assert!(e < 12.0 * 65f64.log2() && e > 12.0 * 65f64.log2() - 3.0, "{e}");
}
#[test]
fn random_and_pin() {
let o = RandomOptions::default();
for _ in 0..1_000 {
let g = random(&o).unwrap();
assert_eq!(g.value.expose().chars().count(), o.length as usize);
}
let no_look = RandomOptions { exclude_lookalikes: true, ..o.clone() };
for _ in 0..SAMPLES / 10 {
let s = random(&no_look).unwrap().value.expose().to_owned();
assert!(!s.chars().any(|c| "Il1O0o|".contains(c)), "{s}");
}
let g =
random(&RandomOptions { length: 20, upper: false, lower: true, digits: false, symbols: false, ..o }).unwrap();
assert!((g.entropy_bits - 20.0 * 26f64.log2()).abs() < 1e-9);
let p = pin(6);
assert!(p.value.expose().len() == 6 && p.value.expose().bytes().all(|b| b.is_ascii_digit()));
assert!((p.entropy_bits - 6.0 * 10f64.log2()).abs() < 1e-9);
}
/// Nicknames (≈ 30 000 combinations by design: they are names, not secrets) and short PINs are
/// excluded: their spaces are small enough that repeats in 10 000 draws are expected.
#[test]
fn no_repeats_in_ten_thousand_samples() {
let mut seen = HashSet::new();
for _ in 0..SAMPLES {
assert!(seen.insert(memorable(&MemorableOptions::default()).value.expose().to_owned()));
}
let mut seen = HashSet::new();
for _ in 0..SAMPLES {
assert!(seen.insert(random(&RandomOptions::default()).unwrap().value.expose().to_owned()));
}
let strict_o = StrictOptions::default();
let mut seen = HashSet::new();
for _ in 0..SAMPLES {
assert!(seen.insert(strict(&strict_o).unwrap().value.expose().to_owned()));
}
}
#[test]
fn generated_values_are_redacted_in_debug() {
let g = memorable(&MemorableOptions::default());
let out = format!("{g:?}");
assert!(!out.contains(g.value.expose()) && out.contains("[redacted]"), "{out}");
}