Skip to content

Commit

Permalink
Merge pull request #310 from epage/renames
Browse files Browse the repository at this point in the history
fix(snap): Clarify naming
  • Loading branch information
epage committed May 15, 2024
2 parents f4ce057 + 4a7f86e commit 291c874
Show file tree
Hide file tree
Showing 27 changed files with 1,505 additions and 1,362 deletions.
6 changes: 4 additions & 2 deletions crates/snapbox/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ default = ["color-auto", "diff"]
harness = ["dep:libtest-mimic", "dep:ignore"]
## Smarter binary file detection
detect-encoding = ["dep:content_inspector"]
## Snapshotting of paths
path = ["dep:tempfile", "dep:walkdir", "dep:dunce", "detect-encoding", "dep:filetime"]
## Snapshotting of directories
dir = ["dep:tempfile", "dep:walkdir", "dep:dunce", "detect-encoding", "dep:filetime"]
## Deprecated since 0.5.11, replaced with `dir`
path = ["dir"]
## Snapshotting of commands
cmd = ["dep:os_pipe", "dep:wait-timeout", "dep:libc", "dep:windows-sys"]
## Building of examples for snapshotting
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
pub type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Clone, Debug)]
pub struct Error {
inner: String,
Expand Down
35 changes: 21 additions & 14 deletions crates/snapbox/src/assert.rs → crates/snapbox/src/assert/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
mod action;
mod error;

#[cfg(feature = "color")]
use anstream::panic;
#[cfg(feature = "color")]
use anstream::stderr;
#[cfg(not(feature = "color"))]
use std::io::stderr;

use crate::data::{NormalizeMatches, NormalizeNewlines, NormalizePaths};
use crate::Action;
use crate::filter::{Filter as _, FilterNewlines, FilterPaths, FilterRedactions};

pub use action::Action;
pub use action::DEFAULT_ACTION_ENV;
pub use error::Error;
pub use error::Result;

/// Snapshot assertion against a file's contents
///
Expand All @@ -25,7 +32,7 @@ pub struct Assert {
action: Action,
action_var: Option<String>,
normalize_paths: bool,
substitutions: crate::Substitutions,
substitutions: crate::Redactions,
pub(crate) palette: crate::report::Palette,
}

Expand Down Expand Up @@ -131,11 +138,11 @@ impl Assert {
expected: crate::Data,
mut actual: crate::Data,
) -> (crate::Data, crate::Data) {
let expected = expected.normalize(NormalizeNewlines);
let expected = FilterNewlines.filter(expected);
// On `expected` being an error, make a best guess
let format = expected.intended_format();

actual = actual.coerce_to(format).normalize(NormalizeNewlines);
actual = FilterNewlines.filter(actual.coerce_to(format));

(expected, actual)
}
Expand All @@ -145,19 +152,19 @@ impl Assert {
expected: crate::Data,
mut actual: crate::Data,
) -> (crate::Data, crate::Data) {
let expected = expected.normalize(NormalizeNewlines);
let expected = FilterNewlines.filter(expected);
// On `expected` being an error, make a best guess
let format = expected.intended_format();
actual = actual.coerce_to(format);

if self.normalize_paths {
actual = actual.normalize(NormalizePaths);
actual = FilterPaths.filter(actual);
}
// Always normalize new lines
actual = actual.normalize(NormalizeNewlines);
actual = FilterNewlines.filter(actual);

// If expected is not an error normalize matches
actual = actual.normalize(NormalizeMatches::new(&self.substitutions, &expected));
actual = FilterRedactions::new(&self.substitutions, &expected).filter(actual);

(expected, actual)
}
Expand Down Expand Up @@ -213,7 +220,7 @@ impl Assert {
expected: &crate::Data,
actual: &crate::Data,
actual_name: Option<&dyn std::fmt::Display>,
) -> crate::Result<()> {
) -> crate::assert::Result<()> {
if expected != actual {
let mut buf = String::new();
crate::report::write_diff(
Expand All @@ -233,7 +240,7 @@ impl Assert {
}

/// # Directory Assertions
#[cfg(feature = "path")]
#[cfg(feature = "dir")]
impl Assert {
#[track_caller]
pub fn subset_eq(
Expand Down Expand Up @@ -418,8 +425,8 @@ impl Assert {
self
}

/// Override the default [`Substitutions`][crate::Substitutions]
pub fn substitutions(mut self, substitutions: crate::Substitutions) -> Self {
/// Override the default [`Redactions`][crate::Redactions]
pub fn substitutions(mut self, substitutions: crate::Redactions) -> Self {
self.substitutions = substitutions;
self
}
Expand All @@ -442,6 +449,6 @@ impl Default for Assert {
substitutions: Default::default(),
palette: crate::report::Palette::color(),
}
.substitutions(crate::Substitutions::with_exe())
.substitutions(crate::Redactions::with_exe())
}
}
33 changes: 16 additions & 17 deletions crates/snapbox/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl Command {
stdin: None,
timeout: None,
_stderr_to_stdout: false,
config: crate::Assert::new().action_env(crate::DEFAULT_ACTION_ENV),
config: crate::Assert::new().action_env(crate::assert::DEFAULT_ACTION_ENV),
}
}

Expand All @@ -32,7 +32,7 @@ impl Command {
stdin: None,
timeout: None,
_stderr_to_stdout: false,
config: crate::Assert::new().action_env(crate::DEFAULT_ACTION_ENV),
config: crate::Assert::new().action_env(crate::assert::DEFAULT_ACTION_ENV),
}
}

Expand Down Expand Up @@ -454,7 +454,7 @@ impl OutputAssert {
pub fn new(output: std::process::Output) -> Self {
Self {
output,
config: crate::Assert::new().action_env(crate::DEFAULT_ACTION_ENV),
config: crate::Assert::new().action_env(crate::assert::DEFAULT_ACTION_ENV),
}
}

Expand Down Expand Up @@ -929,20 +929,20 @@ pub(crate) mod examples {
pub fn compile_example<'a>(
target_name: &str,
args: impl IntoIterator<Item = &'a str>,
) -> Result<std::path::PathBuf, crate::Error> {
) -> crate::assert::Result<std::path::PathBuf> {
crate::debug!("Compiling example {}", target_name);
let messages = escargot::CargoBuild::new()
.current_target()
.current_release()
.example(target_name)
.args(args)
.exec()
.map_err(|e| crate::Error::new(e.to_string()))?;
.map_err(|e| crate::assert::Error::new(e.to_string()))?;
for message in messages {
let message = message.map_err(|e| crate::Error::new(e.to_string()))?;
let message = message.map_err(|e| crate::assert::Error::new(e.to_string()))?;
let message = message
.decode()
.map_err(|e| crate::Error::new(e.to_string()))?;
.map_err(|e| crate::assert::Error::new(e.to_string()))?;
crate::debug!("Message: {:?}", message);
if let Some(bin) = decode_example_message(&message) {
let (name, bin) = bin?;
Expand All @@ -951,7 +951,7 @@ pub(crate) mod examples {
}
}

Err(crate::Error::new(format!(
Err(crate::assert::Error::new(format!(
"Unknown error building example {}",
target_name
)))
Expand All @@ -971,9 +971,8 @@ pub(crate) mod examples {
#[cfg(feature = "examples")]
pub fn compile_examples<'a>(
args: impl IntoIterator<Item = &'a str>,
) -> Result<
impl Iterator<Item = (String, Result<std::path::PathBuf, crate::Error>)>,
crate::Error,
) -> crate::assert::Result<
impl Iterator<Item = (String, crate::assert::Result<std::path::PathBuf>)>,
> {
crate::debug!("Compiling examples");
let mut examples = std::collections::BTreeMap::new();
Expand All @@ -984,12 +983,12 @@ pub(crate) mod examples {
.examples()
.args(args)
.exec()
.map_err(|e| crate::Error::new(e.to_string()))?;
.map_err(|e| crate::assert::Error::new(e.to_string()))?;
for message in messages {
let message = message.map_err(|e| crate::Error::new(e.to_string()))?;
let message = message.map_err(|e| crate::assert::Error::new(e.to_string()))?;
let message = message
.decode()
.map_err(|e| crate::Error::new(e.to_string()))?;
.map_err(|e| crate::assert::Error::new(e.to_string()))?;
crate::debug!("Message: {:?}", message);
if let Some(bin) = decode_example_message(&message) {
let (name, bin) = bin?;
Expand All @@ -1003,7 +1002,7 @@ pub(crate) mod examples {
#[allow(clippy::type_complexity)]
fn decode_example_message<'m>(
message: &'m escargot::format::Message,
) -> Option<Result<(&'m str, Result<std::path::PathBuf, crate::Error>), crate::Error>> {
) -> Option<crate::assert::Result<(&'m str, crate::assert::Result<std::path::PathBuf>)>> {
match message {
escargot::format::Message::CompilerMessage(msg) => {
let level = msg.message.level;
Expand All @@ -1017,10 +1016,10 @@ pub(crate) mod examples {
.unwrap_or_else(|| msg.message.message.as_ref())
.to_owned();
if is_example_target(&msg.target) {
let bin = Err(crate::Error::new(output));
let bin = Err(crate::assert::Error::new(output));
Some(Ok((msg.target.name.as_ref(), bin)))
} else {
Some(Err(crate::Error::new(output)))
Some(Err(crate::assert::Error::new(output)))
}
} else {
None
Expand Down
30 changes: 17 additions & 13 deletions crates/snapbox/src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ mod tests;

pub use format::DataFormat;
pub use normalize::Normalize;
#[allow(deprecated)]
pub use normalize::NormalizeMatches;
#[allow(deprecated)]
pub use normalize::NormalizeNewlines;
#[allow(deprecated)]
pub use normalize::NormalizePaths;
pub use source::DataSource;
pub use source::Inline;
Expand Down Expand Up @@ -69,12 +72,12 @@ macro_rules! file {
$crate::Data::read_from(&path, Some($crate::data::DataFormat:: $type))
}};
[$path:literal] => {{
let mut path = $crate::current_dir!();
let mut path = $crate::utils::current_dir!();
path.push($path);
$crate::Data::read_from(&path, None)
}};
[$path:literal : $type:ident] => {{
let mut path = $crate::current_dir!();
let mut path = $crate::utils::current_dir!();
path.push($path);
$crate::Data::read_from(&path, Some($crate::data::DataFormat:: $type))
}};
Expand All @@ -98,7 +101,7 @@ macro_rules! str {
[$data:literal] => { $crate::str![[$data]] };
[[$data:literal]] => {{
let position = $crate::data::Position {
file: $crate::path::current_rs!(),
file: $crate::utils::current_rs!(),
line: line!(),
column: column!(),
};
Expand All @@ -118,8 +121,8 @@ macro_rules! str {
/// This provides conveniences for tracking the intended format (binary vs text).
#[derive(Clone, Debug)]
pub struct Data {
inner: DataInner,
source: Option<DataSource>,
pub(crate) inner: DataInner,
pub(crate) source: Option<DataSource>,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -155,7 +158,7 @@ impl Data {
Self::with_inner(DataInner::Json(raw.into()))
}

fn error(raw: impl Into<crate::Error>, intended: DataFormat) -> Self {
fn error(raw: impl Into<crate::assert::Error>, intended: DataFormat) -> Self {
Self::with_inner(DataInner::Error(DataError {
error: raw.into(),
intended,
Expand Down Expand Up @@ -201,7 +204,7 @@ impl Data {
pub fn try_read_from(
path: &std::path::Path,
data_format: Option<DataFormat>,
) -> Result<Self, crate::Error> {
) -> crate::assert::Result<Self> {
let data =
std::fs::read(path).map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
let data = Self::binary(data);
Expand All @@ -225,7 +228,7 @@ impl Data {
}

/// Overwrite a snapshot
pub fn write_to(&self, source: &DataSource) -> Result<(), crate::Error> {
pub fn write_to(&self, source: &DataSource) -> crate::assert::Result<()> {
match &source.inner {
source::DataSourceInner::Path(p) => self.write_to_path(p),
source::DataSourceInner::Inline(p) => runtime::get()
Expand All @@ -235,7 +238,7 @@ impl Data {
}

/// Overwrite a snapshot
pub fn write_to_path(&self, path: &std::path::Path) -> Result<(), crate::Error> {
pub fn write_to_path(&self, path: &std::path::Path) -> crate::assert::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
format!("Failed to create parent dir for {}: {}", path.display(), e)
Expand All @@ -249,8 +252,9 @@ impl Data {
/// Post-process text
///
/// See [utils][crate::utils]
#[deprecated(since = "0.5.11", note = "Replaced with `Normalize::normalize`")]
pub fn normalize(self, op: impl Normalize) -> Self {
op.normalize(self)
op.filter(self)
}

/// Return the underlying `String`
Expand All @@ -268,7 +272,7 @@ impl Data {
}
}

pub fn to_bytes(&self) -> Result<Vec<u8>, crate::Error> {
pub fn to_bytes(&self) -> crate::assert::Result<Vec<u8>> {
match &self.inner {
DataInner::Error(err) => Err(err.error.clone()),
DataInner::Binary(data) => Ok(data.clone()),
Expand All @@ -292,7 +296,7 @@ impl Data {
}
}

fn try_is(self, format: DataFormat) -> Result<Self, crate::Error> {
fn try_is(self, format: DataFormat) -> crate::assert::Result<Self> {
let original = self.format();
let source = self.source;
let inner = match (self.inner, format) {
Expand Down Expand Up @@ -487,7 +491,7 @@ impl PartialEq for Data {

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct DataError {
error: crate::Error,
error: crate::assert::Error,
intended: DataFormat,
}

Expand Down

0 comments on commit 291c874

Please sign in to comment.