From 6fd9006291c98d911ca946bdc5e87633d200797a Mon Sep 17 00:00:00 2001 From: Johan Larsson Date: Thu, 30 Nov 2023 20:48:14 +0100 Subject: [PATCH] tests: add custom test helper --- tests/helpers.hpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++ tests/test.cpp | 20 ++++++++--------- 2 files changed, 65 insertions(+), 10 deletions(-) create mode 100644 tests/helpers.hpp diff --git a/tests/helpers.hpp b/tests/helpers.hpp new file mode 100644 index 0000000..9909b5f --- /dev/null +++ b/tests/helpers.hpp @@ -0,0 +1,55 @@ +#include +#include + +template +std::vector +asStdVec(const T& x) +{ + std::vector vec(x.data(), x.data() + x.size()); + + return vec; +} + +template +struct VectorApproxEqualMatcher : Catch::Matchers::MatcherGenericBase +{ + VectorApproxEqualMatcher(const Range& range, const double eps) + : range{ range } + , eps{ eps } + { + } + + template + bool match(OtherRange const& other) const + { + + if (range.size() != other.size()) { + return false; + } + + for (int i = 0; i < range.size(); ++i) { + if (std::abs(range[i] - other[i]) > eps) { + return false; + } + } + + return true; + } + + std::string describe() const override + { + return "Approximately equal to: " + Catch::rangeToString(asStdVec(range)); + } + +private: + const Range& range; + const double eps; +}; + +template +auto +VectorApproxEqual(const Range& range, const double eps = 1e-6) + -> VectorApproxEqualMatcher +{ + return VectorApproxEqualMatcher{ range, eps }; +} diff --git a/tests/test.cpp b/tests/test.cpp index b5d8786..faa2a77 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -1,10 +1,12 @@ +#include "helpers.hpp" #include #include +#include #include -#include +#include #include -TEST_CASE("Simple low-dimensional design", "[gaussian, dense]") +TEST_CASE("Simple low-dimensional design", "[gaussian, dense, ols]") { using namespace Catch::Matchers; @@ -27,10 +29,9 @@ TEST_CASE("Simple low-dimensional design", "[gaussian, dense]") auto no_intercept_no_std = slope::slope(x, y, alpha, lambda, "gaussian", false, false); - REQUIRE_THAT(no_intercept_no_std.betas.coeff(0, 0), - WithinAbsMatcher(1, 0.001)); - REQUIRE_THAT(no_intercept_no_std.betas.coeff(1, 0), - WithinAbsMatcher(1, 0.001)); + Eigen::VectorXd coef = no_intercept_no_std.betas.col(0); + + REQUIRE_THAT(coef, VectorApproxEqual(beta, 1e-4)); } TEST_CASE("X is identity", "[gaussian, dense]") @@ -49,8 +50,7 @@ TEST_CASE("X is identity", "[gaussian, dense]") Eigen::VectorXd betas = res.betas.col(0); - REQUIRE_THAT(betas(0), WithinAbsMatcher(4.0, 0.001)); - REQUIRE_THAT(betas(1), WithinAbsMatcher(3.0, 0.001)); - REQUIRE_THAT(betas(2), WithinAbsMatcher(2.0, 0.001)); - REQUIRE_THAT(betas(3), WithinAbsMatcher(1.0, 0.001)); + std::array expected = { 4.0, 3.0, 2.0, 1.0 }; + + REQUIRE_THAT(betas, VectorApproxEqual(expected)); }