From 956c5cdecc594dac24f7ed7557698933a0c0518b Mon Sep 17 00:00:00 2001 From: Eduard Bopp Date: Sun, 23 Nov 2014 14:01:12 +0100 Subject: [PATCH] Implement assertion macros for ApproxEq These macros yield readable error messages as test assertions for ApproxEq types. They can be invoked as: assert_approx_eq!(a, b); assert_approx_eq_eps!(a, b, eps); Fixes #40. --- src/lib.rs | 1 + src/macros/assert.rs | 28 ++++++++++++++++++++++++++++ src/macros/mod.rs | 1 + tests/assert.rs | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 src/macros/assert.rs create mode 100644 src/macros/mod.rs create mode 100644 tests/assert.rs diff --git a/src/lib.rs b/src/lib.rs index 6cc3d907..e7aef049 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -188,6 +188,7 @@ pub use linalg::{ mod structs; mod traits; mod linalg; +mod macros; // mod lower_triangular; // mod chol; diff --git a/src/macros/assert.rs b/src/macros/assert.rs new file mode 100644 index 00000000..b74f5009 --- /dev/null +++ b/src/macros/assert.rs @@ -0,0 +1,28 @@ +/// Asserts approximate equality within a given tolerance of two values with the +/// `ApproxEq` trait. +#[macro_export] +macro_rules! assert_approx_eq_eps( + ($given: expr, $expected: expr, $eps: expr) => ({ + let eps = &($eps); + let (given_val, expected_val) = (&($given), &($expected)); + if !ApproxEq::approx_eq_eps(given_val, expected_val, eps) { + panic!("assertion failed: `left ≈ right` (left: `{}`, right: `{}`, tolerance: `{}`)", + *given_val, *expected_val, *eps + ) + } + }) +) + +/// Asserts approximate equality of two values with the `ApproxEq` trait. +#[macro_export] +macro_rules! assert_approx_eq( + ($given: expr, $expected: expr) => ({ + let (given_val, expected_val) = (&($given), &($expected)); + if !ApproxEq::approx_eq(given_val, expected_val) { + panic!("assertion failed: `left ≈ right` (left: `{}`, right: `{}`, tolerance: `{}`)", + *given_val, *expected_val, + ApproxEq::approx_epsilon(Some(*given_val)) + ) + } + }) +) diff --git a/src/macros/mod.rs b/src/macros/mod.rs new file mode 100644 index 00000000..4bb1130f --- /dev/null +++ b/src/macros/mod.rs @@ -0,0 +1 @@ +mod assert; diff --git a/tests/assert.rs b/tests/assert.rs new file mode 100644 index 00000000..3b181aa6 --- /dev/null +++ b/tests/assert.rs @@ -0,0 +1,35 @@ +//! Assertion macro tests + +#![feature(phase)] + +#[phase(plugin)] +extern crate nalgebra; +extern crate nalgebra; + +use nalgebra::{ApproxEq, Vec2}; + +#[test] +fn assert_approx_eq_f64() { + let a = 1.0f64; + let b = 1.0f64 + 1.0e-12f64; + assert_approx_eq!(a, b); +} + +#[test] +#[should_fail] +fn assert_approx_eq_vec2_f32_fail() { + let a = Vec2::new(1.0f32, 0.0); + let b = Vec2::new(1.1f32, 0.1); + assert_approx_eq!(a, b); +} + +#[test] +fn assert_approx_eq_eps_f32() { + assert_approx_eq_eps!(1.0f32, 1.1, 0.2); +} + +#[test] +#[should_fail] +fn assert_approx_eq_eps_f64_fail() { + assert_approx_eq_eps!(1.0f64, 1.1, 0.05); +}