pub(crate) mod utils;
use std::{fs, ops::Range, path::PathBuf};
pub struct SnapshotTest {
pub(crate) name: String,
pub(crate) path: PathBuf,
}
pub type Changes = Vec<Range<usize>>;
impl SnapshotTest {
pub fn new(name: &str, path: PathBuf) -> Self {
Self {
name: name.into(),
path,
}
}
pub fn setup_dir(&self) {
if fs::metadata("snapshots").is_err() {
fs::create_dir("snapshots").unwrap_or_else(|_| {
panic!("Could not create directory for snapshots");
});
}
}
pub fn create_snapshot(&self) {
let snapshot_path: PathBuf = format!("snapshots/{}.snap", &self.name).into();
let provided_file = fs::read_to_string(&self.path).unwrap_or_else(|_| {
panic!("Could not read file at path: {:?}", &self.path);
});
let content_snapshot = Self::try_create_snapshot(&snapshot_path, &provided_file);
match content_snapshot {
Some(content_snapshot) => {
Self::compare_snapshots(&snapshot_path, &provided_file, &content_snapshot);
}
None => return,
}
}
fn compare_snapshots(snapshot_path: &PathBuf, provided_file: &str, content_snapshot: &str) -> () {
if provided_file != content_snapshot {
fs::write(&snapshot_path, provided_file).unwrap_or_else(|_| {
panic!("Could not write snapshot to file");
});
utils::stdout_changes();
}
}
fn try_create_snapshot(path: &PathBuf, content_file: &str) -> Option<String> {
if path.exists() {
Some(fs::read_to_string(&path).unwrap_or_else(|_| {
panic!("Could not read snapshot file");
}))
} else {
fs::write(path, content_file).unwrap_or_else(|_| {
panic!("Could not write snapshot to file");
});
None
}
}
}