Skip to content

Commit

Permalink
fix: avoid div with zero in assert_approx_eq (#2101) (#2113)
Browse files Browse the repository at this point in the history
* fix: avoid div with zero in assert_approx_eq

* test: Add tests for assert_approx_eq with zero

* refactor: Make equal check in assert_approx_eq more explicit

(cherry picked from commit 23b1130)

Co-authored-by: Michael Young <2496187+Miyou@users.noreply.github.com>
  • Loading branch information
mergify[bot] and Miyou authored Apr 15, 2024
1 parent 41b1d16 commit 9f88e7c
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/std/src/testing/assertions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ pub fn assert_approx_eq_impl<U: Into<Uint128>>(
) {
let left = left.into();
let right = right.into();

if left == right {
// If both values are equal, we don't need to check the relative difference.
// We check this first to avoid division by zero below.
return;
}

let max_rel_diff = Decimal::from_str(max_rel_diff).unwrap();

let largest = core::cmp::max(left, right);
Expand Down Expand Up @@ -126,6 +133,11 @@ mod tests {
10_000_000_000_000_000_000_000_000_000_000_000_000_u128,
"0.10"
);
assert_approx_eq!(0_u32, 0_u32, "0.12");
assert_approx_eq!(1_u64, 0_u64, "1");
assert_approx_eq!(0_u64, 1_u64, "1");
assert_approx_eq!(5_u64, 0_u64, "1");
assert_approx_eq!(0_u64, 5_u64, "1");
}

#[test]
Expand Down

0 comments on commit 9f88e7c

Please sign in to comment.