Skip to content

Commit

Permalink
Merge pull request #248 from epage/rust-snap
Browse files Browse the repository at this point in the history
fix(snap)!: Clean up `file!` macro
  • Loading branch information
epage authored Feb 14, 2024
2 parents 40d7985 + 5f09c05 commit 64c55cd
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 53 deletions.
16 changes: 8 additions & 8 deletions crates/snapbox/src/assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ use crate::Action;
///
/// ```rust,no_run
/// # use snapbox::Assert;
/// # use snapbox::expect_file;
/// # use snapbox::file;
/// let actual = "something";
/// Assert::new().matches(expect_file!["output.txt"], actual);
/// Assert::new().matches(file!["output.txt"], actual);
/// ```
#[derive(Clone, Debug)]
pub struct Assert {
Expand Down Expand Up @@ -46,12 +46,12 @@ impl Assert {
/// Assert::new().eq(expected, actual);
/// ```
///
/// Can combine this with [`expect_file!`][crate::expect_file]
/// Can combine this with [`file!`][crate::file]
/// ```rust,no_run
/// # use snapbox::Assert;
/// # use snapbox::expect_file;
/// # use snapbox::file;
/// let actual = "something";
/// Assert::new().eq(expect_file!["output.txt"], actual);
/// Assert::new().eq(file!["output.txt"], actual);
/// ```
#[track_caller]
pub fn eq(&self, expected: impl Into<crate::Data>, actual: impl Into<crate::Data>) {
Expand Down Expand Up @@ -92,12 +92,12 @@ impl Assert {
/// Assert::new().matches(expected, actual);
/// ```
///
/// Can combine this with [`expect_file!`][crate::expect_file]
/// Can combine this with [`file!`][crate::file]
/// ```rust,no_run
/// # use snapbox::Assert;
/// # use snapbox::expect_file;
/// # use snapbox::file;
/// let actual = "something";
/// Assert::new().matches(expect_file!["output.txt"], actual);
/// Assert::new().matches(file!["output.txt"], actual);
/// ```
#[track_caller]
pub fn matches(&self, pattern: impl Into<crate::Data>, actual: impl Into<crate::Data>) {
Expand Down
24 changes: 12 additions & 12 deletions crates/snapbox/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,17 +599,17 @@ impl OutputAssert {
/// .stdout_eq("hello");
/// ```
///
/// Can combine this with [`expect_file!`][crate::expect_file]
/// Can combine this with [`file!`][crate::file]
/// ```rust,no_run
/// use snapbox::cmd::Command;
/// use snapbox::cmd::cargo_bin;
/// use snapbox::expect_file;
/// use snapbox::file;
///
/// let assert = Command::new(cargo_bin("snap-fixture"))
/// .env("stdout", "hello")
/// .env("stderr", "world")
/// .assert()
/// .stdout_eq(expect_file!["stdout.log"]);
/// .stdout_eq(file!["stdout.log"]);
/// ```
#[track_caller]
pub fn stdout_eq(self, expected: impl Into<crate::Data>) -> Self {
Expand Down Expand Up @@ -639,17 +639,17 @@ impl OutputAssert {
/// .stdout_matches("he[..]o");
/// ```
///
/// Can combine this with [`expect_file!`][crate::expect_file]
/// Can combine this with [`file!`][crate::file]
/// ```rust,no_run
/// use snapbox::cmd::Command;
/// use snapbox::cmd::cargo_bin;
/// use snapbox::expect_file;
/// use snapbox::file;
///
/// let assert = Command::new(cargo_bin("snap-fixture"))
/// .env("stdout", "hello")
/// .env("stderr", "world")
/// .assert()
/// .stdout_matches(expect_file!["stdout.log"]);
/// .stdout_matches(file!["stdout.log"]);
/// ```
#[track_caller]
pub fn stdout_matches(self, expected: impl Into<crate::Data>) -> Self {
Expand Down Expand Up @@ -679,17 +679,17 @@ impl OutputAssert {
/// .stderr_eq("world");
/// ```
///
/// Can combine this with [`expect_file!`][crate::expect_file]
/// Can combine this with [`file!`][crate::file]
/// ```rust,no_run
/// use snapbox::cmd::Command;
/// use snapbox::cmd::cargo_bin;
/// use snapbox::expect_file;
/// use snapbox::file;
///
/// let assert = Command::new(cargo_bin("snap-fixture"))
/// .env("stdout", "hello")
/// .env("stderr", "world")
/// .assert()
/// .stderr_eq(expect_file!["stderr.log"]);
/// .stderr_eq(file!["stderr.log"]);
/// ```
#[track_caller]
pub fn stderr_eq(self, expected: impl Into<crate::Data>) -> Self {
Expand Down Expand Up @@ -719,17 +719,17 @@ impl OutputAssert {
/// .stderr_matches("wo[..]d");
/// ```
///
/// Can combine this with [`expect_file!`][crate::expect_file]
/// Can combine this with [`file!`][crate::file]
/// ```rust,no_run
/// use snapbox::cmd::Command;
/// use snapbox::cmd::cargo_bin;
/// use snapbox::expect_file;
/// use snapbox::file;
///
/// let assert = Command::new(cargo_bin("snap-fixture"))
/// .env("stdout", "hello")
/// .env("stderr", "world")
/// .assert()
/// .stderr_matches(expect_file!["stderr.log"]);
/// .stderr_matches(file!["stderr.log"]);
/// ```
#[track_caller]
pub fn stderr_matches(self, expected: impl Into<crate::Data>) -> Self {
Expand Down
69 changes: 50 additions & 19 deletions crates/snapbox/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,40 @@
/// This is relative to the source file the macro is run from
///
/// ```
/// # use snapbox::expect_file;
/// expect_file!["./test_data/bar.html"];
/// expect_file![];
/// # #[cfg(feature = "json")] {
/// # use snapbox::file;
/// file!["./test_data/bar.json"];
/// file!["./test_data/bar.json": Text]; // do textual rather than structural comparisons
/// file![_];
/// file![_: Json]; // ensure its treated as json since a type can't be inferred
/// # }
/// ```
#[macro_export]
macro_rules! expect_file {
[$path:expr] => {{
macro_rules! file {
[_] => {{
let stem = ::std::path::Path::new(::std::file!()).file_stem().unwrap();
let rel_path = ::std::format!("snapshots/{}-{}.txt", stem.to_str().unwrap(), line!());
let mut path = $crate::current_dir!();
path.push(rel_path);
$crate::Data::read_from(&path, None)
}};
[_ : $type:ident] => {{
let stem = ::std::path::Path::new(::std::file!()).file_stem().unwrap();
let ext = $crate::DataFormat:: $type.ext();
let rel_path = ::std::format!("snapshots/{}-{}.{ext}", stem.to_str().unwrap(), line!());
let mut path = $crate::current_dir!();
path.push(rel_path);
$crate::Data::read_from(&path, Some($crate::DataFormat:: $type))
}};
[$path:literal] => {{
let mut path = $crate::current_dir!();
path.push($path);
$crate::Data::read_from(&path, None)
}};
[] => {{
let path = std::path::Path::new(file!()).file_stem().unwrap();
let path = format!("snapshots/{}-{}.txt", path.to_str().unwrap(), line!());
$crate::expect_file![path]
[$path:literal : $type:ident] => {{
let mut path = $crate::current_dir!();
path.push($path);
$crate::Data::read_from(&path, Some($crate::DataFormat:: $type))
}};
}

Expand All @@ -39,16 +58,6 @@ enum DataInner {
Json(serde_json::Value),
}

#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Default)]
pub enum DataFormat {
Error,
Binary,
#[default]
Text,
#[cfg(feature = "json")]
Json,
}

impl Data {
/// Mark the data as binary (no post-processing)
pub fn binary(raw: impl Into<Vec<u8>>) -> Self {
Expand Down Expand Up @@ -338,6 +347,28 @@ impl<'s> From<&'s str> for Data {
}
}

#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Default)]
pub enum DataFormat {
Error,
Binary,
#[default]
Text,
#[cfg(feature = "json")]
Json,
}

impl DataFormat {
pub fn ext(self) -> &'static str {
match self {
Self::Error => "txt",
Self::Binary => "bin",
Self::Text => "txt",
#[cfg(feature = "json")]
Self::Json => "json",
}
}
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataSource {
inner: DataSourceInner,
Expand Down
14 changes: 7 additions & 7 deletions crates/snapbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
//! let actual = "...";
//! snapbox::Assert::new()
//! .action_env("SNAPSHOTS")
//! .matches(snapbox::expect_file!["help_output_is_clean.txt"], actual);
//! .matches(snapbox::file!["help_output_is_clean.txt"], actual);
//! ```
//!
//! [`harness::Harness`]
Expand Down Expand Up @@ -132,12 +132,12 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
/// assert_eq(expected, output);
/// ```
///
/// Can combine this with [`expect_file!`]
/// Can combine this with [`file!`]
/// ```rust,no_run
/// # use snapbox::assert_eq;
/// # use snapbox::expect_file;
/// # use snapbox::file;
/// let actual = "something";
/// assert_eq(expect_file!["output.txt"], actual);
/// assert_eq(file!["output.txt"], actual);
/// ```
#[track_caller]
pub fn assert_eq(expected: impl Into<crate::Data>, actual: impl Into<crate::Data>) {
Expand All @@ -162,12 +162,12 @@ pub fn assert_eq(expected: impl Into<crate::Data>, actual: impl Into<crate::Data
/// assert_matches(expected, output);
/// ```
///
/// Can combine this with [`expect_file!`]
/// Can combine this with [`file!`]
/// ```rust,no_run
/// # use snapbox::assert_matches;
/// # use snapbox::expect_file;
/// # use snapbox::file;
/// let actual = "something";
/// assert_matches(expect_file!["output.txt"], actual);
/// assert_matches(file!["output.txt"], actual);
/// ```
#[track_caller]
pub fn assert_matches(pattern: impl Into<crate::Data>, actual: impl Into<crate::Data>) {
Expand Down
22 changes: 16 additions & 6 deletions crates/snapbox/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,27 @@
#[macro_export]
macro_rules! current_dir {
() => {{
let root = if let Some(rustc_root) = option_env!("CARGO_RUSTC_CURRENT_DIR") {
std::path::Path::new(rustc_root)
let root = $crate::path::cargo_rustc_current_dir!();
let file = ::std::file!();
let rel_path = ::std::path::Path::new(file).parent().unwrap();
root.join(rel_path)
}};
}

/// Find the base directory for [`std::file!`]
#[doc(hidden)] // forced to be visible in intended location
#[macro_export]
macro_rules! cargo_rustc_current_dir {
() => {{
if let Some(rustc_root) = ::std::option_env!("CARGO_RUSTC_CURRENT_DIR") {
::std::path::Path::new(rustc_root)
} else {
let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let manifest_dir = ::std::path::Path::new(::std::env!("CARGO_MANIFEST_DIR"));
manifest_dir
.ancestors()
.filter(|it| it.join("Cargo.toml").exists())
.last()
.unwrap()
};
let rel_path = std::path::Path::new(file!()).parent().unwrap();
root.join(rel_path)
}
}};
}
2 changes: 2 additions & 0 deletions crates/snapbox/src/path.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Initialize working directories and assert on how they've changed
#[doc(inline)]
pub use crate::cargo_rustc_current_dir;
#[doc(inline)]
pub use crate::current_dir;

Expand Down
2 changes: 1 addition & 1 deletion tests/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ fn dump_schema() {
snapbox::cmd::Command::new(bin_path)
.assert()
.success()
.stdout_eq(snapbox::expect_file!["../schema.json"]);
.stdout_eq(snapbox::file!["../schema.json"]);
}

0 comments on commit 64c55cd

Please sign in to comment.