Skip to content

Commit

Permalink
fix(assert)!: Organize all Assert logic together
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Apr 23, 2024
1 parent 5a4da90 commit 125d7c4
Show file tree
Hide file tree
Showing 11 changed files with 65 additions and 55 deletions.
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
19 changes: 13 additions & 6 deletions crates/snapbox/src/assert.rs → crates/snapbox/src/assert/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
mod action;
mod error;

#[cfg(feature = "color")]
use anstream::panic;
#[cfg(feature = "color")]
Expand All @@ -6,9 +9,13 @@ use anstream::stderr;
use std::io::stderr;

use crate::filters::{Filter as _, FilterNewlines, FilterPaths, FilterRedactions};
use crate::Action;
use crate::IntoData;

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
///
/// Useful for one-off assertions with the snapshot stored in a file
Expand Down Expand Up @@ -75,7 +82,7 @@ impl Assert {
expected: crate::Data,
actual: crate::Data,
actual_name: Option<&dyn std::fmt::Display>,
) -> Result<(), crate::Error> {
) -> Result<()> {
if expected.source().is_none() && actual.source().is_some() {
panic!("received `(actual, expected)`, expected `(expected, actual)`");
}
Expand Down Expand Up @@ -122,7 +129,7 @@ impl Assert {
expected: crate::Data,
actual: crate::Data,
actual_name: Option<&dyn std::fmt::Display>,
) -> Result<(), crate::Error> {
) -> Result<()> {
let result = self.try_verify(&expected, &actual, actual_name);
let Err(err) = result else {
return Ok(());
Expand All @@ -149,7 +156,7 @@ impl Assert {
} else {
crate::report::Styled::new(String::new(), Default::default())
};
Err(crate::Error::new(format_args!("{err}{message}")))
Err(Error::new(format_args!("{err}{message}")))
}
Action::Overwrite => {
use std::io::Write;
Expand All @@ -159,7 +166,7 @@ impl Assert {
actual.write_to(source).unwrap();
Ok(())
} else {
Err(crate::Error::new(format_args!("{err}")))
Err(Error::new(format_args!("{err}")))
}
}
}
Expand All @@ -170,7 +177,7 @@ impl Assert {
expected: &crate::Data,
actual: &crate::Data,
actual_name: Option<&dyn std::fmt::Display>,
) -> crate::Result<()> {
) -> Result<()> {
if expected != actual {
let mut buf = String::new();
crate::report::write_diff(
Expand Down
34 changes: 18 additions & 16 deletions crates/snapbox/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,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 @@ -34,7 +34,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 @@ -456,7 +456,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 @@ -871,20 +871,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> {
) -> Result<std::path::PathBuf, crate::assert::Error> {
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 @@ -893,7 +893,7 @@ pub(crate) mod examples {
}
}

Err(crate::Error::new(format!(
Err(crate::assert::Error::new(format!(
"Unknown error building example {}",
target_name
)))
Expand All @@ -914,8 +914,8 @@ pub(crate) mod 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,
impl Iterator<Item = (String, Result<std::path::PathBuf, crate::assert::Error>)>,
crate::assert::Error,
> {
crate::debug!("Compiling examples");
let mut examples = std::collections::BTreeMap::new();
Expand All @@ -926,12 +926,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 @@ -945,7 +945,9 @@ 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<
Result<(&'m str, Result<std::path::PathBuf, crate::assert::Error>), crate::assert::Error>,
> {
match message {
escargot::format::Message::CompilerMessage(msg) => {
let level = msg.message.level;
Expand All @@ -959,10 +961,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
14 changes: 7 additions & 7 deletions crates/snapbox/src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ impl Data {
Self::with_inner(DataInner::JsonLines(serde_json::Value::Array(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 @@ -322,7 +322,7 @@ impl Data {
pub fn try_read_from(
path: &std::path::Path,
data_format: Option<DataFormat>,
) -> Result<Self, crate::Error> {
) -> Result<Self, crate::assert::Error> {
let data =
std::fs::read(path).map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
let data = Self::binary(data);
Expand All @@ -346,7 +346,7 @@ impl Data {
}

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

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

fn try_is(self, format: DataFormat) -> Result<Self, crate::Error> {
fn try_is(self, format: DataFormat) -> Result<Self, crate::assert::Error> {
let original = self.format();
let source = self.source;
let filters = self.filters;
Expand Down Expand Up @@ -650,7 +650,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
8 changes: 4 additions & 4 deletions crates/snapbox/src/filters/redactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl Redactions {
&mut self,
placeholder: &'static str,
value: impl Into<RedactedValue>,
) -> Result<(), crate::Error> {
) -> Result<(), crate::assert::Error> {
let placeholder = validate_placeholder(placeholder)?;
let value = value.into();
if let Some(inner) = value.inner {
Expand All @@ -66,14 +66,14 @@ impl Redactions {
pub fn extend(
&mut self,
vars: impl IntoIterator<Item = (&'static str, impl Into<RedactedValue>)>,
) -> Result<(), crate::Error> {
) -> Result<(), crate::assert::Error> {
for (placeholder, value) in vars {
self.insert(placeholder, value)?;
}
Ok(())
}

pub fn remove(&mut self, placeholder: &'static str) -> Result<(), crate::Error> {
pub fn remove(&mut self, placeholder: &'static str) -> Result<(), crate::assert::Error> {
let placeholder = validate_placeholder(placeholder)?;
self.vars.remove(placeholder);
Ok(())
Expand Down Expand Up @@ -291,7 +291,7 @@ fn replace_many<'a>(
}
}

fn validate_placeholder(placeholder: &'static str) -> Result<&'static str, crate::Error> {
fn validate_placeholder(placeholder: &'static str) -> Result<&'static str, crate::assert::Error> {
if !placeholder.starts_with('[') || !placeholder.ends_with(']') {
return Err(format!("Key `{}` is not enclosed in []", placeholder).into());
}
Expand Down
4 changes: 2 additions & 2 deletions crates/snapbox/src/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
//! }
//! ```
use crate::Action;
use crate::assert::Action;
use crate::Data;

use libtest_mimic::Trial;
Expand Down Expand Up @@ -81,7 +81,7 @@ where
overrides: None,
setup,
test,
config: crate::Assert::new().action_env(crate::DEFAULT_ACTION_ENV),
config: crate::Assert::new().action_env(crate::assert::DEFAULT_ACTION_ENV),
test_output: Default::default(),
test_error: Default::default(),
}
Expand Down
15 changes: 4 additions & 11 deletions crates/snapbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,9 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

mod action;
mod assert;
mod error;
mod macros;

pub mod assert;
pub mod cmd;
pub mod data;
pub mod filters;
Expand All @@ -109,20 +107,15 @@ pub mod utils;
#[cfg(feature = "harness")]
pub mod harness;

pub use action::Action;
pub use action::DEFAULT_ACTION_ENV;
pub use assert::Assert;
pub use data::Data;
pub use data::IntoData;
#[cfg(feature = "json")]
pub use data::IntoJson;
pub use data::ToDebug;
pub use error::Error;
pub use filters::Redactions;
pub use snapbox_macros::debug;

pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Easier access to common traits
pub mod prelude {
pub use crate::IntoData;
Expand Down Expand Up @@ -159,7 +152,7 @@ pub mod prelude {
#[track_caller]
pub fn assert_eq(expected: impl IntoData, actual: impl IntoData) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.action_env(assert::DEFAULT_ACTION_ENV)
.eq(expected, actual);
}

Expand All @@ -179,7 +172,7 @@ pub fn assert_subset_eq(
actual_root: impl Into<std::path::PathBuf>,
) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.action_env(assert::DEFAULT_ACTION_ENV)
.subset_eq(expected_root, actual_root);
}

Expand All @@ -206,6 +199,6 @@ pub fn assert_subset_matches(
actual_root: impl Into<std::path::PathBuf>,
) {
Assert::new()
.action_env(DEFAULT_ACTION_ENV)
.action_env(assert::DEFAULT_ACTION_ENV)
.subset_matches(pattern_root, actual_root);
}
Loading

0 comments on commit 125d7c4

Please sign in to comment.