Skip to content

Commit

Permalink
fix: avoid div with zero in assert_approx_eq (#2101)
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
  • Loading branch information
Miyou authored Apr 15, 2024
1 parent 5148df2 commit 23b1130
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/core/src/testing/assertions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,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 @@ -128,6 +135,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 23b1130

Please sign in to comment.