From 9f88e7c3b9c6ca8859827c702774c0db275b61a3 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 15 Apr 2024 11:19:38 +0200 Subject: [PATCH] fix: avoid div with zero in assert_approx_eq (#2101) (#2113) * 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 23b11309eb87cb3b9dc07685c3c738e392f2f5b8) Co-authored-by: Michael Young <2496187+Miyou@users.noreply.github.com> --- packages/std/src/testing/assertions.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/std/src/testing/assertions.rs b/packages/std/src/testing/assertions.rs index fa3ab6c7fa..d6ffecff0d 100644 --- a/packages/std/src/testing/assertions.rs +++ b/packages/std/src/testing/assertions.rs @@ -54,6 +54,13 @@ pub fn assert_approx_eq_impl>( ) { 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); @@ -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]