Skip to content

Commit

Permalink
Added rounded_redaction (#350)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko committed Feb 16, 2023
1 parent d84e3f3 commit 7c00b0b
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Expand Up @@ -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)]
Expand Down
21 changes: 21 additions & 0 deletions src/redaction.rs
Expand Up @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions 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
}
22 changes: 22 additions & 0 deletions tests/test_redaction.rs
Expand Up @@ -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),
}
);
}

0 comments on commit 7c00b0b

Please sign in to comment.