diff --git a/src/encoders/float.rs b/src/encoders/float.rs index cf515dc21c..442083badc 100644 --- a/src/encoders/float.rs +++ b/src/encoders/float.rs @@ -491,6 +491,7 @@ pub fn decode_all(src: &[u8], dst: &mut Vec) -> Result<(), Box> #[allow(clippy::unreadable_literal)] #[allow(clippy::excessive_precision)] // TODO: Audit test values for truncation mod tests { + use crate::tests::approximately_equal; #[test] fn encode_all_no_values() { @@ -537,7 +538,7 @@ mod tests { if v.is_nan() || v.is_infinite() { assert_eq!(src[i].to_bits(), v.to_bits()); } else { - assert_eq!(src[i], *v); + assert!(approximately_equal(src[i], *v)); } } } diff --git a/src/lib.rs b/src/lib.rs index 77fdbfa170..8610eb5afe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,3 +30,14 @@ impl error::Error for Error { None } } + +#[cfg(test)] +pub mod tests { + use std::f64; + + /// A test helper function for asserting floating point numbers are within the machine epsilon + /// because strict comparison of floating point numbers is incorrect + pub fn approximately_equal(f1: f64, f2: f64) -> bool { + (f1 - f2).abs() < f64::EPSILON + } +} diff --git a/src/line_parser/mod.rs b/src/line_parser/mod.rs index b0d0fab4ed..cfde8d9bcc 100644 --- a/src/line_parser/mod.rs +++ b/src/line_parser/mod.rs @@ -259,6 +259,7 @@ fn read_value( #[cfg(test)] mod test { use super::*; + use crate::tests::approximately_equal; #[test] fn parse_single_field() { @@ -273,13 +274,13 @@ mod test { let vals = parse(input); assert_eq!(vals[0].series(), "foo\tasdf"); assert_eq!(vals[0].time(), 546); - assert_eq!(vals[0].f64_value().unwrap(), 44.0); + assert!(approximately_equal(vals[0].f64_value().unwrap(), 44.0)); let input = "foo asdf=3.14 123"; let vals = parse(input); assert_eq!(vals[0].series(), "foo\tasdf"); assert_eq!(vals[0].time(), 123); - assert_eq!(vals[0].f64_value().unwrap(), 3.14); + assert!(approximately_equal(vals[0].f64_value().unwrap(), 3.14)); } #[test] @@ -300,11 +301,11 @@ mod test { let vals = parse(input); assert_eq!(vals[0].series(), "foo\tasdf"); assert_eq!(vals[0].time(), 1234); - assert_eq!(vals[0].f64_value().unwrap(), 23.1); + assert!(approximately_equal(vals[0].f64_value().unwrap(), 23.1)); assert_eq!(vals[1].series(), "foo\tbar"); assert_eq!(vals[1].time(), 1234); - assert_eq!(vals[1].f64_value().unwrap(), 5.0); + assert!(approximately_equal(vals[1].f64_value().unwrap(), 5.0)); } #[test] @@ -314,7 +315,7 @@ mod test { let vals = parse(input); assert_eq!(vals[0].series(), "foo\tasdf"); assert_eq!(vals[0].time(), 1234); - assert_eq!(vals[0].f64_value().unwrap(), 23.1); + assert!(approximately_equal(vals[0].f64_value().unwrap(), 23.1)); assert_eq!(vals[1].series(), "foo\tbar"); assert_eq!(vals[1].time(), 1234);