fix: Test that floats are approximately equal within machine epsilon

As found by the float_cmp clippy lint.

There are crates that provide macros for this, but it's small enough
that I think a test helper function in-tree is fine.
pull/24376/head
Carol (Nichols || Goulding) 2020-02-17 10:47:33 -05:00
parent c6eda3a8b5
commit eabf96a0d7
3 changed files with 19 additions and 6 deletions

View File

@ -491,6 +491,7 @@ pub fn decode_all(src: &[u8], dst: &mut Vec<f64>) -> Result<(), Box<dyn Error>>
#[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));
}
}
}

View File

@ -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
}
}

View File

@ -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);