Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(snap)!: Clean up API #250

Merged
merged 3 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/snapbox/src/assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ impl Assert {
// On `expected` being an error, make a best guess
let format = expected.format();

actual = actual.try_coerce(format).normalize(NormalizeNewlines);
actual = actual.coerce_to(format).normalize(NormalizeNewlines);

(expected, actual)
}
Expand All @@ -142,7 +142,7 @@ impl Assert {
let expected = expected.normalize(NormalizeNewlines);
// On `expected` being an error, make a best guess
let format = expected.format();
actual = actual.try_coerce(format);
actual = actual.coerce_to(format);

if self.normalize_paths {
actual = actual.normalize(NormalizePaths);
Expand Down
75 changes: 33 additions & 42 deletions crates/snapbox/src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ macro_rules! file {
}};
[_ : $type:ident] => {{
let stem = ::std::path::Path::new(::std::file!()).file_stem().unwrap();
let ext = $crate::DataFormat:: $type.ext();
let ext = $crate::data::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))
$crate::Data::read_from(&path, Some($crate::data::DataFormat:: $type))
}};
[$path:literal] => {{
let mut path = $crate::current_dir!();
Expand All @@ -49,7 +49,7 @@ macro_rules! file {
[$path:literal : $type:ident] => {{
let mut path = $crate::current_dir!();
path.push($path);
$crate::Data::read_from(&path, Some($crate::DataFormat:: $type))
$crate::Data::read_from(&path, Some($crate::data::DataFormat:: $type))
}};
}

Expand All @@ -74,45 +74,37 @@ enum DataInner {
impl Data {
/// Mark the data as binary (no post-processing)
pub fn binary(raw: impl Into<Vec<u8>>) -> Self {
Self {
inner: DataInner::Binary(raw.into()),
source: None,
}
DataInner::Binary(raw.into()).into()
}

/// Mark the data as text (post-processing)
pub fn text(raw: impl Into<String>) -> Self {
Self {
inner: DataInner::Text(raw.into()),
source: None,
}
DataInner::Text(raw.into()).into()
}

#[cfg(feature = "json")]
pub fn json(raw: impl Into<serde_json::Value>) -> Self {
Self {
inner: DataInner::Json(raw.into()),
source: None,
}
DataInner::Json(raw.into()).into()
}

fn error(raw: impl Into<crate::Error>) -> Self {
Self {
inner: DataInner::Error(raw.into()),
source: None,
}
DataInner::Error(raw.into()).into()
}

/// Empty test data
pub fn new() -> Self {
Self::text("")
}

fn with_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
self.source = Some(DataSource::path(path));
fn with_source(mut self, source: impl Into<DataSource>) -> Self {
self.source = Some(source.into());
self
}

fn with_path(self, path: impl Into<std::path::PathBuf>) -> Self {
self.with_source(path.into())
}

/// Load test data from a file
pub fn read_from(path: &std::path::Path, data_format: Option<DataFormat>) -> Self {
match Self::try_read_from(path, data_format) {
Expand Down Expand Up @@ -156,8 +148,8 @@ impl Data {
.unwrap_or_default()
{
#[cfg(feature = "json")]
"json" => data.try_coerce(DataFormat::Json),
_ => data.try_coerce(DataFormat::Text),
"json" => data.coerce_to(DataFormat::Json),
_ => data.coerce_to(DataFormat::Text),
}
}
};
Expand Down Expand Up @@ -220,13 +212,10 @@ impl Data {
}
}

pub fn try_coerce(self, format: DataFormat) -> Self {
pub fn coerce_to(self, format: DataFormat) -> Self {
let mut data = match (self.inner, format) {
(DataInner::Error(inner), _) => Self::error(inner),
(inner, DataFormat::Error) => Self {
inner,
source: None,
},
(inner, DataFormat::Error) => inner.into(),
(DataInner::Binary(inner), DataFormat::Binary) => Self::binary(inner),
(DataInner::Text(inner), DataFormat::Text) => Self::text(inner),
#[cfg(feature = "json")]
Expand All @@ -237,11 +226,11 @@ impl Data {
} else {
match String::from_utf8(inner) {
Ok(str) => {
let coerced = Self::text(str).try_coerce(format);
let coerced = Self::text(str).coerce_to(format);
// if the Text cannot be coerced into the correct format
// reset it back to Binary
if coerced.format() != format {
coerced.try_coerce(DataFormat::Binary)
coerced.coerce_to(DataFormat::Binary)
} else {
coerced
}
Expand All @@ -260,21 +249,14 @@ impl Data {
Err(_) => Self::text(inner),
}
}
(inner, DataFormat::Binary) => Self::binary(
Self {
inner,
source: None,
}
.to_bytes()
.expect("error case handled"),
),
(inner, DataFormat::Binary) => {
let remake: Self = inner.into();
Self::binary(remake.to_bytes().expect("error case handled"))
}
// This variant is already covered unless structured data is enabled
#[cfg(feature = "structured-data")]
(inner, DataFormat::Text) => {
let remake = Self {
inner,
source: None,
};
let remake: Self = inner.into();
if let Some(str) = remake.render() {
Self::text(str)
} else {
Expand All @@ -298,6 +280,15 @@ impl Data {
}
}

impl From<DataInner> for Data {
fn from(inner: DataInner) -> Self {
Data {
inner,
source: None,
}
}
}

impl std::fmt::Display for Data {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.inner {
Expand Down
12 changes: 12 additions & 0 deletions crates/snapbox/src/data/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ impl DataSource {
}
}

impl From<&'_ std::path::Path> for DataSource {
fn from(value: &'_ std::path::Path) -> Self {
Self::path(value)
}
}

impl From<std::path::PathBuf> for DataSource {
fn from(value: std::path::PathBuf) -> Self {
Self::path(value)
}
}

impl std::fmt::Display for DataSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.inner {
Expand Down
26 changes: 13 additions & 13 deletions crates/snapbox/src/data/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ fn json_to_bytes_render() {
fn binary_to_text() {
let binary = String::from("test").into_bytes();
let d = Data::binary(binary);
let text = d.try_coerce(DataFormat::Text);
let text = d.coerce_to(DataFormat::Text);
assert_eq!(DataFormat::Text, text.format())
}

#[test]
fn binary_to_text_not_utf8() {
let binary = b"\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00".to_vec();
let d = Data::binary(binary);
let d = d.try_coerce(DataFormat::Text);
let d = d.coerce_to(DataFormat::Text);
assert_ne!(DataFormat::Text, d.format());
assert_eq!(DataFormat::Binary, d.format());
}
Expand All @@ -47,7 +47,7 @@ fn binary_to_json() {
let value = json!({"name": "John\\Doe\r\n"});
let binary = serde_json::to_vec_pretty(&value).unwrap();
let d = Data::binary(binary);
let json = d.try_coerce(DataFormat::Json);
let json = d.coerce_to(DataFormat::Json);
assert_eq!(DataFormat::Json, json.format());
}

Expand All @@ -56,7 +56,7 @@ fn binary_to_json() {
fn binary_to_json_not_utf8() {
let binary = b"\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00".to_vec();
let d = Data::binary(binary);
let d = d.try_coerce(DataFormat::Json);
let d = d.coerce_to(DataFormat::Json);
assert_ne!(DataFormat::Json, d.format());
assert_eq!(DataFormat::Binary, d.format());
}
Expand All @@ -66,7 +66,7 @@ fn binary_to_json_not_utf8() {
fn binary_to_json_not_json() {
let binary = String::from("test").into_bytes();
let d = Data::binary(binary);
let d = d.try_coerce(DataFormat::Json);
let d = d.coerce_to(DataFormat::Json);
assert_ne!(DataFormat::Json, d.format());
assert_eq!(DataFormat::Binary, d.format());
}
Expand All @@ -75,7 +75,7 @@ fn binary_to_json_not_json() {
fn text_to_binary() {
let text = String::from("test");
let d = Data::text(text);
let binary = d.try_coerce(DataFormat::Binary);
let binary = d.coerce_to(DataFormat::Binary);
assert_eq!(DataFormat::Binary, binary.format());
}

Expand All @@ -85,7 +85,7 @@ fn text_to_json() {
let value = json!({"name": "John\\Doe\r\n"});
let text = serde_json::to_string_pretty(&value).unwrap();
let d = Data::text(text);
let json = d.try_coerce(DataFormat::Json);
let json = d.coerce_to(DataFormat::Json);
assert_eq!(DataFormat::Json, json.format());
}

Expand All @@ -94,7 +94,7 @@ fn text_to_json() {
fn text_to_json_not_json() {
let text = String::from("test");
let d = Data::text(text);
let json = d.try_coerce(DataFormat::Json);
let json = d.coerce_to(DataFormat::Json);
assert_eq!(DataFormat::Text, json.format());
}

Expand All @@ -103,7 +103,7 @@ fn text_to_json_not_json() {
fn json_to_binary() {
let value = json!({"name": "John\\Doe\r\n"});
let d = Data::json(value);
let binary = d.try_coerce(DataFormat::Binary);
let binary = d.coerce_to(DataFormat::Binary);
assert_eq!(DataFormat::Binary, binary.format());
}

Expand All @@ -112,7 +112,7 @@ fn json_to_binary() {
fn json_to_text() {
let value = json!({"name": "John\\Doe\r\n"});
let d = Data::json(value);
let text = d.try_coerce(DataFormat::Text);
let text = d.coerce_to(DataFormat::Text);
assert_eq!(DataFormat::Text, text.format());
}

Expand All @@ -124,7 +124,7 @@ fn json_to_text() {
fn text_to_bin_coerce_equals_to_bytes() {
let text = String::from("test");
let d = Data::text(text);
let binary = d.clone().try_coerce(DataFormat::Binary);
let binary = d.clone().coerce_to(DataFormat::Binary);
assert_eq!(Data::binary(d.to_bytes().unwrap()), binary);
}

Expand All @@ -133,7 +133,7 @@ fn text_to_bin_coerce_equals_to_bytes() {
fn json_to_bin_coerce_equals_to_bytes() {
let json = json!({"name": "John\\Doe\r\n"});
let d = Data::json(json);
let binary = d.clone().try_coerce(DataFormat::Binary);
let binary = d.clone().coerce_to(DataFormat::Binary);
assert_eq!(Data::binary(d.to_bytes().unwrap()), binary);
}

Expand All @@ -142,7 +142,7 @@ fn json_to_bin_coerce_equals_to_bytes() {
fn json_to_text_coerce_equals_render() {
let json = json!({"name": "John\\Doe\r\n"});
let d = Data::json(json);
let text = d.clone().try_coerce(DataFormat::Text);
let text = d.clone().coerce_to(DataFormat::Text);
assert_eq!(Data::text(d.render().unwrap()), text);
}

Expand Down
5 changes: 1 addition & 4 deletions crates/snapbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@

mod action;
mod assert;
mod data;
mod error;
mod macros;
mod substitutions;

pub mod cmd;
pub mod data;
pub mod path;
pub mod report;
pub mod utils;
Expand All @@ -112,9 +112,6 @@ pub use action::Action;
pub use action::DEFAULT_ACTION_ENV;
pub use assert::Assert;
pub use data::Data;
pub use data::DataFormat;
pub use data::DataSource;
pub use data::{Normalize, NormalizeMatches, NormalizeNewlines, NormalizePaths};
pub use error::Error;
pub use snapbox_macros::debug;
pub use substitutions::Substitutions;
Expand Down
4 changes: 2 additions & 2 deletions crates/snapbox/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ impl PathDiff {
crate::Data::read_from(&expected_path, None).normalize(NormalizeNewlines);

actual = actual
.try_coerce(expected.format())
.coerce_to(expected.format())
.normalize(NormalizeNewlines);

if expected != actual {
Expand Down Expand Up @@ -266,7 +266,7 @@ impl PathDiff {
crate::Data::read_from(&expected_path, None).normalize(NormalizeNewlines);

actual = actual
.try_coerce(expected.format())
.coerce_to(expected.format())
.normalize(NormalizePaths)
.normalize(NormalizeNewlines)
.normalize(NormalizeMatches::new(substitutions, &expected));
Expand Down
14 changes: 8 additions & 6 deletions src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use std::eprintln;
use std::io::stderr;

use rayon::prelude::*;
use snapbox::data::{DataFormat, NormalizeNewlines, NormalizePaths};
use snapbox::path::FileType;
use snapbox::{DataFormat, NormalizeNewlines, NormalizePaths};

#[derive(Debug)]
pub(crate) struct Runner {
Expand Down Expand Up @@ -441,10 +441,12 @@ impl Case {
}

if let Some(expected_content) = expected_content {
stream.content = stream.content.normalize(snapbox::NormalizeMatches::new(
substitutions,
expected_content,
));
stream.content = stream
.content
.normalize(snapbox::data::NormalizeMatches::new(
substitutions,
expected_content,
));

if stream.content != *expected_content {
stream.status = StreamStatus::Expected(expected_content.clone());
Expand Down Expand Up @@ -734,7 +736,7 @@ struct Stream {

impl Stream {
fn make_text(mut self) -> Self {
let content = self.content.try_coerce(DataFormat::Text);
let content = self.content.coerce_to(DataFormat::Text);
if content.format() != DataFormat::Text {
self.status = StreamStatus::Failure("Unable to convert underlying Data to Text".into());
}
Expand Down
Loading
Loading