5namespace CppSpec::Matchers {
6template <
typename A,
typename E>
9template <
typename A,
typename E>
16 BeWithinHelper(
Expectation<A>& expectation, E tolerance) : expectation(expectation), tolerance(tolerance) {}
20 void set_message(
const std::string& msg) { this->msg = msg; }
21 std::string get_message() {
return this->msg; }
24template <
typename A,
typename E>
25class BeWithin :
public MatcherBase<A, E> {
30 BeWithin(
Expectation<A>& expectation, E tolerance, E value, std::string_view unit)
31 : MatcherBase<A, E>(expectation, value), tolerance{tolerance}, unit{unit} {}
33 bool match()
override;
38 std::string verb()
override {
return "be within"; }
41template <
typename A,
typename E>
44 matcher.set_message(msg);
49template <
typename A,
typename E>
50BeWithin<A, E> BeWithinHelper<A, E>::percent_of(E expected) {
51 auto matcher = BeWithin<A, E>(expectation, tolerance, expected,
"%");
52 matcher.set_message(msg);
57template <
typename A,
typename E>
58bool BeWithin<A, E>::match() {
59 const auto actual =
static_cast<long double>(this->actual());
60 const auto expected =
static_cast<long double>(this->expected());
62 const auto tolerance = unit ==
"%" ? std::abs(expected) *
static_cast<long double>(this->tolerance) / 100
63 : static_cast<long double>(this->tolerance);
64 return std::abs(actual - expected) <= tolerance;
67template <
typename A,
typename E>
69 return std::format(
"expected {} to {}", this->actual(),
description());
72template <
typename A,
typename E>
74 return std::format(
"expected {} not to {}", this->actual(),
description());
77template <
typename A,
typename E>
79 return std::format(
"be within {}{} of {}", this->tolerance, this->unit, this->expected());
Wraps the target of an expectation.
Definition expectation.hpp:48
Definition be_within.hpp:25
std::string description() override
Get the description of the Matcher.
Definition be_within.hpp:78
std::string failure_message() override
Get message to give on match failure.
Definition be_within.hpp:68
std::string failure_message_when_negated() override
Get message to give on match failure when negated.
Definition be_within.hpp:73
Definition have_error.hpp:9
Contains the base class for all Matchers.