diff --git a/CHANGELOG.md b/CHANGELOG.md index ededa6b0..a0fc0b6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to insta and cargo-insta are documented here. - Added a way to disable diffing in review. (#348) - Added three argument version of `glob!` to set a different base path. (#347) +- Added `rounded_redaction` to truncate floating point values. ## 1.27.0 diff --git a/src/lib.rs b/src/lib.rs index afc28701..3aa14d9d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -304,7 +304,7 @@ pub mod _cargo_insta_support { // useful for redactions #[cfg(feature = "redactions")] -pub use crate::redaction::{dynamic_redaction, sorted_redaction}; +pub use crate::redaction::{dynamic_redaction, rounded_redaction, sorted_redaction}; // these are here to make the macros work #[doc(hidden)] diff --git a/src/redaction.rs b/src/redaction.rs index b6563e00..525b3294 100644 --- a/src/redaction.rs +++ b/src/redaction.rs @@ -166,6 +166,27 @@ pub fn sorted_redaction() -> Redaction { dynamic_redaction(sort) } +/// Creates a redaction that rounds floating point numbers to a given +/// number of decimal places. +/// +/// ```rust +/// # use insta::{Settings, rounded_redaction}; +/// # let mut settings = Settings::new(); +/// settings.add_redaction(".sum", rounded_redaction(2)); +/// ``` +#[cfg_attr(docsrs, doc(cfg(feature = "redactions")))] +pub fn rounded_redaction(decimals: usize) -> Redaction { + dynamic_redaction(move |value: Content, _path: ContentPath| -> Content { + let f = match value.resolve_inner() { + Content::F32(f) => *f as f64, + Content::F64(f) => *f, + _ => return value, + }; + let x = 10f64.powf(decimals as f64); + Content::F64((f * x).round() / x) + }) +} + impl Redaction { /// Performs the redaction of the value at the given path. fn redact(&self, value: Content, path: &[PathItem]) -> Content { diff --git a/tests/snapshots/test_redaction__rounded_redaction.snap b/tests/snapshots/test_redaction__rounded_redaction.snap new file mode 100644 index 00000000..e51ea062 --- /dev/null +++ b/tests/snapshots/test_redaction__rounded_redaction.snap @@ -0,0 +1,8 @@ +--- +source: tests/test_redaction.rs +expression: "&MyPoint { x: 1.0 / 3.0, y: 6.0 / 3.0 }" +--- +{ + "x": 0.3333, + "y": 2.0 +} diff --git a/tests/test_redaction.rs b/tests/test_redaction.rs index 4e4ec92e..106026f5 100644 --- a/tests/test_redaction.rs +++ b/tests/test_redaction.rs @@ -414,3 +414,25 @@ fn test_ordering_newtype_set() { } ); } + +#[cfg(feature = "json")] +#[test] +fn test_rounded_redaction() { + #[derive(Debug, Serialize)] + pub struct MyPoint { + x: f64, + y: f64, + } + + assert_json_snapshot!( + "rounded_redaction", + &MyPoint { + x: 1.0 / 3.0, + y: 6.0 / 3.0, + }, + { + ".x" => insta::rounded_redaction(4), + ".y" => insta::rounded_redaction(4), + } + ); +}