Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of floating point arrays using google test and google mock

I am new to Google's test products and trying them out with some signal processing code. I am trying to assert that to floating point arrays are equal to within some bounds, using google mock as suggested by the answer to this question. I would like to know the recommended method for adding some error tolerance to an expression like the following . . .

EXPECT_THAT(  impulse, testing::ElementsAreArray( std::vector<float>({
    0, 0, 0, 1, 1, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
}) )  );

I want the test to pass if the element-wise values in the arrays are within 10-8 of one another.

like image 483
learnvst Avatar asked Mar 17 '23 21:03

learnvst


2 Answers

The following works for me:

using ::testing::Pointwise;
using ::testing::FloatNear;

auto const max_abs_error = 1 / 1024.f;
ASSERT_THAT(
    test,
    Pointwise(FloatNear(max_abs_error), ref));

Where test and ref are of type std::vector<float>.

like image 149
Daniel Fischer Avatar answered Apr 14 '23 01:04

Daniel Fischer


One approach is to use the googletest rather than googlemock macros, which results in a more compact assert:

#define EXPECT_FLOATS_NEARLY_EQ(expected, actual, thresh) \
        EXPECT_EQ(expected.size(), actual.size()) << "Array sizes differ.";\
        for (size_t idx = 0; idx < std::min(expected.size(), actual.size()); ++idx) \
        { \
            EXPECT_NEAR(expected[idx], actual[idx], thresh) << "at index: " << idx;\
        }

// define expected_array as in the other answer
EXPECT_FLOATS_NEARLY_EQ(impulse, expected_array, 0.001);
like image 45
the_mandrill Avatar answered Apr 14 '23 02:04

the_mandrill