#[allow(dead_code)]
pub fn assert_approx_eq(actual: f64, expected: f64, epsilon: f64) {
let diff = (actual - expected).abs();
assert!(
diff < epsilon,
"Float values not approximately equal:\n actual: {}\n expected: {}\n diff: {} (epsilon: {})",
actual, expected, diff, epsilon
);
}
#[allow(dead_code)]
pub fn assert_size_within(actual_bytes: u64, expected_bytes: u64, tolerance_bytes: u64) {
let diff = actual_bytes.abs_diff(expected_bytes);
assert!(
diff <= tolerance_bytes,
"Size outside tolerance:\n actual: {} bytes ({:.2} KB)\n expected: {} bytes ({:.2} KB)\n diff: {} bytes (tolerance: {} bytes)",
actual_bytes, actual_bytes as f64 / 1024.0,
expected_bytes, expected_bytes as f64 / 1024.0,
diff, tolerance_bytes
);
}
#[allow(dead_code)]
pub fn assert_percent_within(actual_percent: f64, expected_percent: f64, tolerance_percent: f64) {
assert_approx_eq(actual_percent, expected_percent, tolerance_percent);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_assert_approx_eq_pass() {
assert_approx_eq(0.75, 0.75, 0.01);
assert_approx_eq(0.75, 0.7501, 0.01);
assert_approx_eq(12.5, 12.45, 0.1);
}
#[test]
#[should_panic(expected = "Float values not approximately equal")]
fn test_assert_approx_eq_fail() {
assert_approx_eq(0.75, 0.80, 0.01);
}
#[test]
fn test_assert_size_within_pass() {
assert_size_within(1024000, 1024000, 1024);
assert_size_within(1024000, 1024512, 1024);
assert_size_within(1024512, 1024000, 1024);
}
#[test]
#[should_panic(expected = "Size outside tolerance")]
fn test_assert_size_within_fail() {
assert_size_within(1024000, 1030000, 1024);
}
#[test]
fn test_assert_percent_within_pass() {
assert_percent_within(50.0, 50.0, 1.0);
assert_percent_within(50.0, 50.5, 1.0);
}
}