use std::fmt;
use std::path::{Path, PathBuf};
use techy::serialize::SerialValue;
use crate::dump::json::{from_json, to_json_pretty};
pub const UPDATE_GOLDEN: &str = "UPDATE_GOLDEN";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GoldenMode {
#[default]
Compare,
Update,
}
impl GoldenMode {
pub fn from_env() -> GoldenMode {
GoldenMode::from_setting(std::env::var(UPDATE_GOLDEN).ok().as_deref())
}
pub fn from_setting(value: Option<&str>) -> GoldenMode {
match value {
Some("1") => GoldenMode::Update,
_ => GoldenMode::Compare,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GoldenError {
Missing {
path: PathBuf,
actual: String,
},
Mismatch {
path: PathBuf,
expected: String,
actual: String,
},
Unreadable {
path: PathBuf,
detail: String,
},
Unwritable {
path: PathBuf,
detail: String,
},
Unrenderable {
path: PathBuf,
detail: String,
},
}
impl fmt::Display for GoldenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GoldenError::Missing { path, actual } => write!(
f,
"the golden file {} does not exist\n\
(run the test with {UPDATE_GOLDEN}=1 to create it)\n\
--- actual ---\n{actual}",
path.display()
),
GoldenError::Mismatch { path, expected, actual } => write!(
f,
"the actual output differs from the golden file {}\n\
(run the test with {UPDATE_GOLDEN}=1 to rewrite the file)\n\
--- expected ---\n{expected}\n--- actual ---\n{actual}",
path.display()
),
GoldenError::Unreadable { path, detail } => {
write!(f, "the golden file {} cannot be read: {detail}", path.display())
}
GoldenError::Unwritable { path, detail } => {
write!(f, "the golden file {} cannot be written: {detail}", path.display())
}
GoldenError::Unrenderable { path, detail } => {
write!(
f,
"the actual value compared with the golden file {} cannot be written \
as JSON: {detail}",
path.display()
)
}
}
}
}
impl std::error::Error for GoldenError {}
fn write_golden(path: &Path, content: &str) -> Result<(), GoldenError> {
let unwritable = |error: std::io::Error| GoldenError::Unwritable {
path: path.to_path_buf(),
detail: error.to_string(),
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(unwritable)?;
}
std::fs::write(path, content).map_err(unwritable)
}
fn read_golden(path: &Path) -> Result<Option<String>, GoldenError> {
match std::fs::read_to_string(path) {
Ok(content) => Ok(Some(content)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => {
Err(GoldenError::Unreadable { path: path.to_path_buf(), detail: error.to_string() })
}
}
}
pub fn check_text_golden(path: &Path, actual: &str, mode: GoldenMode) -> Result<(), GoldenError> {
if mode == GoldenMode::Update {
return write_golden(path, actual);
}
match read_golden(path)? {
None => {
Err(GoldenError::Missing { path: path.to_path_buf(), actual: String::from(actual) })
}
Some(expected) if expected == actual => Ok(()),
Some(expected) => Err(GoldenError::Mismatch {
path: path.to_path_buf(),
expected,
actual: String::from(actual),
}),
}
}
pub fn check_json_golden(
path: &Path,
value: &SerialValue,
mode: GoldenMode,
) -> Result<(), GoldenError> {
let render = |value: &SerialValue| {
to_json_pretty(value).map(|text| text + "\n").map_err(|error| GoldenError::Unrenderable {
path: path.to_path_buf(),
detail: error.to_string(),
})
};
let actual = render(value)?;
if mode == GoldenMode::Update {
return write_golden(path, &actual);
}
let Some(text) = read_golden(path)? else {
return Err(GoldenError::Missing { path: path.to_path_buf(), actual });
};
let expected = from_json(&text).map_err(|error| GoldenError::Unreadable {
path: path.to_path_buf(),
detail: format!("its content is not the JSON form of a serialized value: {error}"),
})?;
if &expected == value {
return Ok(());
}
Err(GoldenError::Mismatch { path: path.to_path_buf(), expected: render(&expected)?, actual })
}
pub fn assert_text_golden(path: impl AsRef<Path>, actual: &str) {
if let Err(error) = check_text_golden(path.as_ref(), actual, GoldenMode::from_env()) {
panic!("{error}");
}
}
pub fn assert_json_golden(path: impl AsRef<Path>, value: &SerialValue) {
if let Err(error) = check_json_golden(path.as_ref(), value, GoldenMode::from_env()) {
panic!("{error}");
}
}