tabnas_support/runner.rs
1// Copyright (c) 2026 tabnas, MIT License
2
3// The table-driven runner: fixture rows in, failures out.
4//
5// Loading a fixture is only half of what every repo was duplicating. The
6// other half is the loop: read the input column, parse it, branch on
7// whether the expected column names a value or an error, compare, and
8// report with enough context to find the row. That loop is the same
9// everywhere, and `ts/src/runner.ts` and `go/runner.go` run the identical
10// one against `node:test` and `testing.T`.
11//
12// Rust's test harness has no subtests, so this runner reports every
13// failing row of a fixture at once, each line carrying `<file>:<line>`,
14// rather than one case per row. That is the one shape difference, and it
15// is recorded in `doc/reference.md`.
16
17use std::cell::RefCell;
18use std::fmt;
19use std::path::Path;
20use std::rc::Rc;
21
22use crate::expect::{
23 equal_value, equal_value_with, error_expect, format_value, is_error_expect, lone_surrogate_at,
24 lone_surrogate_message, parse_expect,
25};
26use crate::spec::{load_spec, load_spec_dir, Column, Row, SpecFile, SpecOptions};
27use crate::value::Value;
28use crate::{Error, Result};
29
30/// A parse that failed, as the runner sees it: the code the fixture pins,
31/// the position it may pin, and the message a failure report quotes.
32///
33/// This crate cannot name the engine's error type (it takes no
34/// dependencies), so a suite converts at the boundary, which is a single
35/// closure: `.map_err(|e| Failure::new(e.code).at(e.row, e.col))`. That
36/// stands in for the `errorCode` and `errorPos` hooks of the other two
37/// runtimes, whose runners read those fields off the thrown error by
38/// shape.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Failure {
41 /// The error code, or `""` when the failure has none.
42 pub code: String,
43 /// The 1-based source position, when the error reports one.
44 pub row: Option<usize>,
45 pub col: Option<usize>,
46 /// The rendered error, quoted in failure reports.
47 pub message: String,
48}
49
50impl Failure {
51 /// A failure carrying a code and no position.
52 pub fn new(code: impl Into<String>) -> Self {
53 let code = code.into();
54 Failure {
55 message: code.clone(),
56 code,
57 row: None,
58 col: None,
59 }
60 }
61
62 /// A failure with no code at all, only a message: what a parser whose
63 /// errors are told apart by their text alone produces.
64 pub fn message(message: impl Into<String>) -> Self {
65 Failure {
66 code: String::new(),
67 row: None,
68 col: None,
69 message: message.into(),
70 }
71 }
72
73 /// Record the 1-based source position the error reports.
74 pub fn at(mut self, row: usize, col: usize) -> Self {
75 self.row = Some(row);
76 self.col = Some(col);
77 self
78 }
79
80 /// Replace the message a report quotes.
81 pub fn with_message(mut self, message: impl Into<String>) -> Self {
82 self.message = message.into();
83 self
84 }
85}
86
87impl fmt::Display for Failure {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 if self.message.is_empty() {
90 formatter.write_str(&self.code)
91 } else {
92 formatter.write_str(&self.message)
93 }
94 }
95}
96
97impl std::error::Error for Failure {}
98
99type ParseFn = dyn Fn(&str, &Row) -> std::result::Result<Value, Failure>;
100type ParseHook = Rc<ParseFn>;
101type MatchErrorHook = Rc<dyn Fn(&Failure, &str, &Row) -> bool>;
102pub(crate) type ParseExpectedFn = dyn Fn(&str, &Row) -> Result<Value>;
103type ParseExpectedHook = Rc<ParseExpectedFn>;
104pub(crate) type NormalizeFn = dyn Fn(Value) -> Value;
105type NormalizeHook = Rc<NormalizeFn>;
106
107/// Drives fixture rows through one parser. Reuse it across files.
108///
109/// Built with [`Runner::new`] (a parse hook taking the input) or
110/// [`Runner::new_with_row`] (one taking the row as well, for a fixture
111/// whose other columns take part in the parse, an `opts` column of plugin
112/// options being the common one), then adjusted with the builder methods.
113#[derive(Clone)]
114pub struct Runner {
115 parse: ParseHook,
116 match_error: Option<MatchErrorHook>,
117 parse_expected: Option<ParseExpectedHook>,
118 normalize: Option<NormalizeHook>,
119 input: Column,
120 expected: Column,
121 load: SpecOptions,
122}
123
124impl Runner {
125 /// A runner over a parse hook that sees only the input.
126 pub fn new(parse: impl Fn(&str) -> std::result::Result<Value, Failure> + 'static) -> Self {
127 Self::new_with_row(move |input, _row| parse(input))
128 }
129
130 /// A runner over a parse hook that sees the row as well.
131 pub fn new_with_row(
132 parse: impl Fn(&str, &Row) -> std::result::Result<Value, Failure> + 'static,
133 ) -> Self {
134 Runner {
135 parse: Rc::new(parse),
136 match_error: None,
137 parse_expected: None,
138 normalize: None,
139 input: Column::Position(0),
140 expected: Column::Position(1),
141 load: SpecOptions::default(),
142 }
143 }
144
145 /// Decide whether a failure satisfies an `ERROR:<want>` row, when
146 /// comparing a code cannot. It replaces the code comparison entirely.
147 ///
148 /// A code is the contract this crate prefers, but some grammars have
149 /// no stable code to pin: a parser whose failures are distinguished
150 /// only by their message, or a fixture that names a position rather
151 /// than a kind. Those fixtures would otherwise have to weaken to a
152 /// bare `ERROR`, which asserts nothing more than "it failed".
153 ///
154 /// A bare `ERROR` cell still means "any error", and does not reach
155 /// here. Nor does a trailing `@<row>:<col>`: `want` is the code with
156 /// any position expectation already stripped.
157 pub fn match_error(mut self, hook: impl Fn(&Failure, &str, &Row) -> bool + 'static) -> Self {
158 self.match_error = Some(Rc::new(hook));
159 self
160 }
161
162 /// Read the expected cell, when the fixture's vocabulary is wider than
163 /// JSON (JSON5's `NaN` and `Infinity`, or the `UNDEFINED` several repos
164 /// use for "no value at all"). It replaces [`parse_expect`], and is
165 /// reached only for a value row. Call `parse_expect` for the cells the
166 /// hook does not claim, so the ordinary rows keep the ordinary rules.
167 pub fn parse_expected(mut self, hook: impl Fn(&str, &Row) -> Result<Value> + 'static) -> Self {
168 self.parse_expected = Some(Rc::new(hook));
169 self
170 }
171
172 /// Rewrite values before comparison; see [`equal_value_with`].
173 pub fn normalize(mut self, hook: impl Fn(Value) -> Value + 'static) -> Self {
174 self.normalize = Some(Rc::new(hook));
175 self
176 }
177
178 /// The column holding the parser input, by position or header name.
179 /// Default: position 0.
180 pub fn input(mut self, column: impl Into<Column>) -> Self {
181 self.input = column.into();
182 self
183 }
184
185 /// The column holding the expected result. Default: position 1.
186 pub fn expected(mut self, column: impl Into<Column>) -> Self {
187 self.expected = column.into();
188 self
189 }
190
191 /// Fixture-file loading options, passed through to the loader.
192 pub fn load(mut self, options: SpecOptions) -> Self {
193 self.load = options;
194 self
195 }
196
197 /// The loading options in force.
198 pub fn load_options(&self) -> &SpecOptions {
199 &self.load
200 }
201
202 /// The input column selector in force.
203 pub fn input_column(&self) -> &Column {
204 &self.input
205 }
206
207 pub(crate) fn parse_expected_hook(&self) -> Option<&ParseExpectedFn> {
208 self.parse_expected.as_deref()
209 }
210
211 pub(crate) fn normalize_hook(&self) -> Option<&NormalizeFn> {
212 self.normalize.as_deref()
213 }
214
215 /// A copy of this runner whose expected column is `column`.
216 pub(crate) fn reading(&self, column: Column) -> Runner {
217 let mut runner = self.clone();
218 runner.expected = column;
219 runner
220 }
221
222 /// A copy of this runner whose parse hook answers from ONE evaluation
223 /// however many times it is asked. The register needs it: every
224 /// comparison a row needs goes through the ordinary runner, but a
225 /// parse hook that carries state could answer differently on a second
226 /// call and turn a genuine regression into a reported "closed
227 /// divergence", the opposite conclusion.
228 pub(crate) fn parsing_once(&self) -> Runner {
229 let inner = Rc::clone(&self.parse);
230 let once: Rc<RefCell<Option<std::result::Result<Value, Failure>>>> =
231 Rc::new(RefCell::new(None));
232 let mut runner = self.clone();
233 runner.parse = Rc::new(move |input, row| {
234 let mut slot = once.borrow_mut();
235 if slot.is_none() {
236 *slot = Some(inner(input, row));
237 }
238 slot.as_ref().expect("filled above").clone()
239 });
240 runner
241 }
242
243 /// Why a fixture cannot be run, or `Ok` when it can. [`Runner::spec`]
244 /// calls it and fails; it is public so the guard itself can be
245 /// asserted.
246 ///
247 /// A fixture that loads but holds no rows is the case that matters: it
248 /// is a silent pass, and a silent pass is indistinguishable from
249 /// coverage that was never there.
250 pub fn check_spec(&self, spec: &SpecFile) -> Result<()> {
251 let Some(probe) = spec.rows.first() else {
252 return Err(Error(format!("{}: no cases", spec.file)));
253 };
254 probe
255 .resolve(&self.input)
256 .map_err(|error| Error(format!("{}: input column: {error}", spec.file)))?;
257 probe
258 .resolve(&self.expected)
259 .map_err(|error| Error(format!("{}: expected column: {error}", spec.file)))?;
260 Ok(())
261 }
262
263 /// Run one row and return the failure rather than reporting it, for a
264 /// suite that does its own reporting.
265 pub fn check_row(&self, row: &Row, input: &str, expected: &str) -> Result<()> {
266 let at = row.location();
267
268 if is_error_expect(expected) {
269 let want = error_expect(expected).map_err(|error| Error(format!("{at}: {error}")))?;
270
271 let failure = match (self.parse)(input, row) {
272 Ok(got) => {
273 return Err(Error(format!(
274 "{at}: parse({input:?}) should fail with {expected}, but returned {}",
275 format_value(&got)
276 )));
277 }
278 Err(failure) => failure,
279 };
280
281 if !want.code.is_empty() {
282 match &self.match_error {
283 Some(matches) => {
284 if !matches(&failure, &want.code, row) {
285 return Err(Error(format!(
286 "{at}: parse({input:?}) failed, but the error does not match {:?}\n error: {failure}",
287 want.code
288 )));
289 }
290 }
291 None => {
292 if failure.code != want.code {
293 return Err(Error(format!(
294 "{at}: parse({input:?}) failed with code {:?}, expected {:?}\n error: {failure}",
295 failure.code, want.code
296 )));
297 }
298 }
299 }
300 }
301
302 if let (Some(want_row), Some(want_col)) = (want.row, want.col) {
303 // An error that names no position is a mismatch, not a
304 // pass. The whole point of the channel is that an error
305 // which cannot say where it happened has not met an
306 // expectation that says where it must.
307 let reported = match (failure.row, failure.col) {
308 (Some(row), Some(col)) => Some((row, col)),
309 _ => None,
310 };
311 if reported != Some((want_row, want_col)) {
312 let where_ = reported.map_or("no position".to_string(), |(row, col)| {
313 format!("{row}:{col}")
314 });
315 return Err(Error(format!(
316 "{at}: parse({input:?}) failed at {where_}, expected {want_row}:{want_col}\n error: {failure}"
317 )));
318 }
319 }
320
321 return Ok(());
322 }
323
324 // Refuse a shared cell that the runtimes would decode differently.
325 // `lone_surrogate_at` says why; the short version is that this is
326 // the one thing a shared expected column cannot express, and that
327 // it fails SILENTLY. Only on the DEFAULT path: a wider vocabulary
328 // need not read `\uXXXX` as an escape at all, and a hook whose
329 // syntax does should call `lone_surrogate_at` itself.
330 if self.parse_expected.is_none() {
331 if let Some(index) = lone_surrogate_at(expected) {
332 return Err(Error(format!(
333 "{at}: {}",
334 lone_surrogate_message(expected, index)
335 )));
336 }
337 }
338
339 let want = match &self.parse_expected {
340 Some(read) => read(expected, row),
341 None => parse_expect(expected),
342 }
343 .map_err(|error| Error(format!("{at}: {error}")))?;
344
345 // A value row that failed is a failure like any other, and it
346 // needs the same `<file>:<line>` prefix: an unadorned parser error
347 // says nothing about which fixture row provoked it.
348 let got = (self.parse)(input, row)
349 .map_err(|failure| Error(format!("{at}: parse({input:?}) failed: {failure}")))?;
350
351 let equal = match &self.normalize {
352 Some(normalize) => equal_value_with(&got, &want, normalize.as_ref()),
353 None => equal_value(&got, &want),
354 };
355 if !equal {
356 return Err(Error(format!(
357 "{at}: parse({input:?})\n got: {}\n expected: {}",
358 format_value(&got),
359 format_value(&want)
360 )));
361 }
362
363 Ok(())
364 }
365
366 /// Run every row of an already-loaded fixture. `Err` when the fixture
367 /// cannot be run at all; otherwise the failures, one per failing row,
368 /// empty when every row passed.
369 pub fn run_spec(&self, spec: &SpecFile) -> Result<Vec<String>> {
370 self.check_spec(spec)?;
371 let probe = &spec.rows[0];
372 let input_col = probe.resolve(&self.input)?;
373 let expected_col = probe.resolve(&self.expected)?;
374
375 Ok(spec
376 .rows
377 .iter()
378 .filter_map(|row| {
379 let input = row.unesc(input_col);
380 let expected = row.col(expected_col);
381 self.check_row(row, &input, expected)
382 .err()
383 .map(|error| error.0)
384 })
385 .collect())
386 }
387
388 /// Load one fixture file by path and run it; see [`Runner::run_spec`].
389 pub fn run_file(&self, path: impl AsRef<Path>) -> Result<Vec<String>> {
390 self.run_spec(&load_spec(path, &self.load)?)
391 }
392
393 /// Load and run every `*.tsv` in a directory; see [`Runner::run_spec`].
394 /// An empty directory is an error: a runner that finds nothing to run
395 /// must not report green.
396 pub fn run_dir(&self, dir: impl AsRef<Path>) -> Result<Vec<String>> {
397 let mut failures = Vec::new();
398 for spec in load_spec_dir(dir, &self.load)? {
399 failures.extend(self.run_spec(&spec)?);
400 }
401 Ok(failures)
402 }
403
404 /// Run an already-loaded fixture, panicking with every failing row at
405 /// once when any fails or the fixture cannot be run.
406 pub fn spec(&self, spec: &SpecFile) {
407 report(self.run_spec(spec));
408 }
409
410 /// Load one fixture file by path and run it, panicking on failure.
411 pub fn file(&self, path: impl AsRef<Path>) {
412 report(self.run_file(path));
413 }
414
415 /// Load and run every `*.tsv` in a directory, panicking on failure.
416 pub fn dir(&self, dir: impl AsRef<Path>) {
417 report(self.run_dir(dir));
418 }
419}
420
421/// Panic with every failure at once, naming file and line, rather than
422/// stopping at the first; do nothing when there is nothing to report.
423pub fn report(outcome: Result<Vec<String>>) {
424 match outcome {
425 Err(error) => panic!("{error}"),
426 Ok(failures) if failures.is_empty() => {}
427 Ok(failures) => panic!(
428 "{} fixture row(s) failed:\n{}",
429 failures.len(),
430 failures.join("\n")
431 ),
432 }
433}