use std::cell::RefCell;
use std::fmt;
use std::path::Path;
use std::rc::Rc;
use crate::expect::{
equal_value, equal_value_with, error_expect, format_value, is_error_expect, lone_surrogate_at,
lone_surrogate_message, parse_expect,
};
use crate::spec::{load_spec, load_spec_dir, Column, Row, SpecFile, SpecOptions};
use crate::value::Value;
use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
pub code: String,
pub row: Option<usize>,
pub col: Option<usize>,
pub message: String,
}
impl Failure {
pub fn new(code: impl Into<String>) -> Self {
let code = code.into();
Failure {
message: code.clone(),
code,
row: None,
col: None,
}
}
pub fn message(message: impl Into<String>) -> Self {
Failure {
code: String::new(),
row: None,
col: None,
message: message.into(),
}
}
pub fn at(mut self, row: usize, col: usize) -> Self {
self.row = Some(row);
self.col = Some(col);
self
}
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = message.into();
self
}
}
impl fmt::Display for Failure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.message.is_empty() {
formatter.write_str(&self.code)
} else {
formatter.write_str(&self.message)
}
}
}
impl std::error::Error for Failure {}
type ParseFn = dyn Fn(&str, &Row) -> std::result::Result<Value, Failure>;
type ParseHook = Rc<ParseFn>;
type MatchErrorHook = Rc<dyn Fn(&Failure, &str, &Row) -> bool>;
pub(crate) type ParseExpectedFn = dyn Fn(&str, &Row) -> Result<Value>;
type ParseExpectedHook = Rc<ParseExpectedFn>;
pub(crate) type NormalizeFn = dyn Fn(Value) -> Value;
type NormalizeHook = Rc<NormalizeFn>;
#[derive(Clone)]
pub struct Runner {
parse: ParseHook,
match_error: Option<MatchErrorHook>,
parse_expected: Option<ParseExpectedHook>,
normalize: Option<NormalizeHook>,
input: Column,
expected: Column,
load: SpecOptions,
}
impl Runner {
pub fn new(parse: impl Fn(&str) -> std::result::Result<Value, Failure> + 'static) -> Self {
Self::new_with_row(move |input, _row| parse(input))
}
pub fn new_with_row(
parse: impl Fn(&str, &Row) -> std::result::Result<Value, Failure> + 'static,
) -> Self {
Runner {
parse: Rc::new(parse),
match_error: None,
parse_expected: None,
normalize: None,
input: Column::Position(0),
expected: Column::Position(1),
load: SpecOptions::default(),
}
}
pub fn match_error(mut self, hook: impl Fn(&Failure, &str, &Row) -> bool + 'static) -> Self {
self.match_error = Some(Rc::new(hook));
self
}
pub fn parse_expected(mut self, hook: impl Fn(&str, &Row) -> Result<Value> + 'static) -> Self {
self.parse_expected = Some(Rc::new(hook));
self
}
pub fn normalize(mut self, hook: impl Fn(Value) -> Value + 'static) -> Self {
self.normalize = Some(Rc::new(hook));
self
}
pub fn input(mut self, column: impl Into<Column>) -> Self {
self.input = column.into();
self
}
pub fn expected(mut self, column: impl Into<Column>) -> Self {
self.expected = column.into();
self
}
pub fn load(mut self, options: SpecOptions) -> Self {
self.load = options;
self
}
pub fn load_options(&self) -> &SpecOptions {
&self.load
}
pub fn input_column(&self) -> &Column {
&self.input
}
pub(crate) fn parse_expected_hook(&self) -> Option<&ParseExpectedFn> {
self.parse_expected.as_deref()
}
pub(crate) fn normalize_hook(&self) -> Option<&NormalizeFn> {
self.normalize.as_deref()
}
pub(crate) fn reading(&self, column: Column) -> Runner {
let mut runner = self.clone();
runner.expected = column;
runner
}
pub(crate) fn parsing_once(&self) -> Runner {
let inner = Rc::clone(&self.parse);
let once: Rc<RefCell<Option<std::result::Result<Value, Failure>>>> =
Rc::new(RefCell::new(None));
let mut runner = self.clone();
runner.parse = Rc::new(move |input, row| {
let mut slot = once.borrow_mut();
if slot.is_none() {
*slot = Some(inner(input, row));
}
slot.as_ref().expect("filled above").clone()
});
runner
}
pub fn check_spec(&self, spec: &SpecFile) -> Result<()> {
let Some(probe) = spec.rows.first() else {
return Err(Error(format!("{}: no cases", spec.file)));
};
probe
.resolve(&self.input)
.map_err(|error| Error(format!("{}: input column: {error}", spec.file)))?;
probe
.resolve(&self.expected)
.map_err(|error| Error(format!("{}: expected column: {error}", spec.file)))?;
Ok(())
}
pub fn check_row(&self, row: &Row, input: &str, expected: &str) -> Result<()> {
let at = row.location();
if is_error_expect(expected) {
let want = error_expect(expected).map_err(|error| Error(format!("{at}: {error}")))?;
let failure = match (self.parse)(input, row) {
Ok(got) => {
return Err(Error(format!(
"{at}: parse({input:?}) should fail with {expected}, but returned {}",
format_value(&got)
)));
}
Err(failure) => failure,
};
if !want.code.is_empty() {
match &self.match_error {
Some(matches) => {
if !matches(&failure, &want.code, row) {
return Err(Error(format!(
"{at}: parse({input:?}) failed, but the error does not match {:?}\n error: {failure}",
want.code
)));
}
}
None => {
if failure.code != want.code {
return Err(Error(format!(
"{at}: parse({input:?}) failed with code {:?}, expected {:?}\n error: {failure}",
failure.code, want.code
)));
}
}
}
}
if let (Some(want_row), Some(want_col)) = (want.row, want.col) {
let reported = match (failure.row, failure.col) {
(Some(row), Some(col)) => Some((row, col)),
_ => None,
};
if reported != Some((want_row, want_col)) {
let where_ = reported.map_or("no position".to_string(), |(row, col)| {
format!("{row}:{col}")
});
return Err(Error(format!(
"{at}: parse({input:?}) failed at {where_}, expected {want_row}:{want_col}\n error: {failure}"
)));
}
}
return Ok(());
}
if self.parse_expected.is_none() {
if let Some(index) = lone_surrogate_at(expected) {
return Err(Error(format!(
"{at}: {}",
lone_surrogate_message(expected, index)
)));
}
}
let want = match &self.parse_expected {
Some(read) => read(expected, row),
None => parse_expect(expected),
}
.map_err(|error| Error(format!("{at}: {error}")))?;
let got = (self.parse)(input, row)
.map_err(|failure| Error(format!("{at}: parse({input:?}) failed: {failure}")))?;
let equal = match &self.normalize {
Some(normalize) => equal_value_with(&got, &want, normalize.as_ref()),
None => equal_value(&got, &want),
};
if !equal {
return Err(Error(format!(
"{at}: parse({input:?})\n got: {}\n expected: {}",
format_value(&got),
format_value(&want)
)));
}
Ok(())
}
pub fn run_spec(&self, spec: &SpecFile) -> Result<Vec<String>> {
self.check_spec(spec)?;
let probe = &spec.rows[0];
let input_col = probe.resolve(&self.input)?;
let expected_col = probe.resolve(&self.expected)?;
Ok(spec
.rows
.iter()
.filter_map(|row| {
let input = row.unesc(input_col);
let expected = row.col(expected_col);
self.check_row(row, &input, expected)
.err()
.map(|error| error.0)
})
.collect())
}
pub fn run_file(&self, path: impl AsRef<Path>) -> Result<Vec<String>> {
self.run_spec(&load_spec(path, &self.load)?)
}
pub fn run_dir(&self, dir: impl AsRef<Path>) -> Result<Vec<String>> {
let mut failures = Vec::new();
for spec in load_spec_dir(dir, &self.load)? {
failures.extend(self.run_spec(&spec)?);
}
Ok(failures)
}
pub fn spec(&self, spec: &SpecFile) {
report(self.run_spec(spec));
}
pub fn file(&self, path: impl AsRef<Path>) {
report(self.run_file(path));
}
pub fn dir(&self, dir: impl AsRef<Path>) {
report(self.run_dir(dir));
}
}
pub fn report(outcome: Result<Vec<String>>) {
match outcome {
Err(error) => panic!("{error}"),
Ok(failures) if failures.is_empty() => {}
Ok(failures) => panic!(
"{} fixture row(s) failed:\n{}",
failures.len(),
failures.join("\n")
),
}
}