Skip to content

Commit

Permalink
Merge pull request #251 from epage/rust-snap
Browse files Browse the repository at this point in the history
feat(snap): Allow inline snapshotting
  • Loading branch information
epage authored Feb 14, 2024
2 parents 0865e04 + da308b1 commit 6736b8b
Show file tree
Hide file tree
Showing 9 changed files with 663 additions and 5 deletions.
6 changes: 6 additions & 0 deletions crates/snapbox/src/assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ impl Assert {

#[track_caller]
fn eq_inner(&self, expected: crate::Data, actual: crate::Data) {
if expected.source().is_none() && actual.source().is_some() {
panic!("received `(actual, expected)`, expected `(expected, actual)`");
}
match self.action {
Action::Skip => {
return;
Expand Down Expand Up @@ -108,6 +111,9 @@ impl Assert {

#[track_caller]
fn matches_inner(&self, pattern: crate::Data, actual: crate::Data) {
if pattern.source().is_none() && actual.source().is_some() {
panic!("received `(actual, expected)`, expected `(expected, actual)`");
}
match self.action {
Action::Skip => {
return;
Expand Down
47 changes: 47 additions & 0 deletions crates/snapbox/src/data/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod format;
mod normalize;
mod runtime;
mod source;
#[cfg(test)]
mod tests;
Expand All @@ -10,6 +11,18 @@ pub use normalize::NormalizeMatches;
pub use normalize::NormalizeNewlines;
pub use normalize::NormalizePaths;
pub use source::DataSource;
pub use source::Inline;
pub use source::Position;

pub trait ToDebug {
fn to_debug(&self) -> Data;
}

impl<D: std::fmt::Debug> ToDebug for D {
fn to_debug(&self) -> Data {
Data::text(format!("{:#?}\n", self))
}
}

/// Declare an expected value for an assert from a file
///
Expand Down Expand Up @@ -53,6 +66,37 @@ macro_rules! file {
}};
}

/// Declare an expected value from within Rust source
///
/// ```
/// # use snapbox::str;
/// str![["
/// Foo { value: 92 }
/// "]];
/// str![r#"{"Foo": 92}"#];
/// ```
///
/// Leading indentation is stripped.
#[macro_export]
macro_rules! str {
[$data:literal] => { $crate::str![[$data]] };
[[$data:literal]] => {{
let position = $crate::data::Position {
file: $crate::path::current_rs!(),
line: line!(),
column: column!(),
};
let inline = $crate::data::Inline {
position,
data: $data,
indent: true,
};
inline
}};
[] => { $crate::str![[""]] };
[[]] => { $crate::str![[""]] };
}

/// Test fixture, actual output, or expected result
///
/// This provides conveniences for tracking the intended format (binary vs text).
Expand Down Expand Up @@ -165,6 +209,9 @@ impl Data {
pub fn write_to(&self, source: &DataSource) -> Result<(), crate::Error> {
match &source.inner {
source::DataSourceInner::Path(p) => self.write_to_path(p),
source::DataSourceInner::Inline(p) => runtime::get()
.write(self, p)
.map_err(|err| err.to_string().into()),
}
}

Expand Down
Loading

0 comments on commit 6736b8b

Please sign in to comment.