Skip to main content

korek_testkit/
lib.rs

1//! Shared validation vectors (`vectors/rules.json`): for each case, a type,
2//! a `validate` block, and values every target must accept or reject. The
3//! same table runs against the loader (as examples), the generated Rust
4//! (this crate's tests), the generated Zod (`ts/vectors.test.ts`) and,
5//! through [`run`], any third-party generator.
6
7use core::fmt::Write as _;
8
9pub mod synthetic;
10
11use serde::Deserialize;
12
13/// One vector.
14#[derive(Debug, Clone, Deserialize)]
15pub struct Case {
16    pub name: String,
17    /// A korek type expression.
18    #[serde(rename = "type")]
19    pub ty: String,
20    /// The body of a `validate { … }` block.
21    pub validate: String,
22    pub valid: Vec<serde_json::Value>,
23    pub invalid: Vec<serde_json::Value>,
24}
25
26#[derive(Deserialize)]
27struct File {
28    cases: Vec<Case>,
29}
30
31/// The vectors file.
32pub const VECTORS: &str = include_str!("../vectors/rules.json");
33
34/// Every case.
35///
36/// # Panics
37/// If the bundled vectors file is malformed (a test catches that).
38pub fn cases() -> Vec<Case> {
39    serde_json::from_str::<File>(VECTORS)
40        .map_or_else(|e| panic!("vectors/rules.json: {e}"), |f| f.cases)
41}
42
43/// `min_len` → `VMinLen`: the struct holding a case's field `v`.
44pub fn struct_name(case: &str) -> String {
45    let pascal: String = case
46        .split('_')
47        .map(|w| {
48            let mut c = w.chars();
49            c.next()
50                .map(|f| f.to_ascii_uppercase().to_string() + c.as_str())
51                .unwrap_or_default()
52        })
53        .collect();
54    format!("V{pascal}")
55}
56
57/// A korek schema with one struct per case (`struct VMinLen { field v … }`).
58pub fn schema() -> String {
59    let mut s = String::from("package \"vectors.v1\"\n");
60    for c in cases() {
61        let _ = write!(
62            s,
63            "\nstruct {} {{\n  field v {:?} {{ validate {{ {} }} }}\n}}\n",
64            struct_name(&c.name),
65            c.ty,
66            c.validate
67        );
68    }
69    s
70}
71
72/// A mismatch: a value accepted that should fail, or the reverse.
73#[derive(Debug, Clone, PartialEq)]
74pub struct Mismatch {
75    pub case: String,
76    pub value: serde_json::Value,
77    pub expected_valid: bool,
78}
79
80/// Runs every vector through `accepts(case, value)` (whether the target
81/// accepts `{"v": value}` for the case's struct) and returns mismatches.
82pub fn run(mut accepts: impl FnMut(&Case, &serde_json::Value) -> bool) -> Vec<Mismatch> {
83    let mut out = Vec::new();
84    for c in cases() {
85        for (values, expected_valid) in [(&c.valid, true), (&c.invalid, false)] {
86            for v in values {
87                if accepts(&c, v) != expected_valid {
88                    out.push(Mismatch {
89                        case: c.name.clone(),
90                        value: v.clone(),
91                        expected_valid,
92                    });
93                }
94            }
95        }
96    }
97    out
98}