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);
48template <
typename A,
typename E>
49BeWithin<A, E> BeWithinHelper<A, E>::percent_of(E expected) {
50 auto matcher = BeWithin<A, E>(expectation, tolerance, expected,
"%");
51 matcher.set_message(msg);
55template <
typename A,
typename E>
56bool BeWithin<A, E>::match() {
57 if (!this->expected()) {
60 return std::abs(this->actual() - this->
expected()) <= this->tolerance;
63template <
typename A,
typename E>
65 return std::format(
"expected {} to {}", this->actual(),
description());
68template <
typename A,
typename E>
70 return std::format(
"expected {} not to {}", this->actual(),
description());
73template <
typename A,
typename E>
75 return std::format(
"be within {}{} of {}", this->tolerance, this->unit, this->expected());
Wraps the target of an expectation.
Definition expectation.hpp:47
Definition be_within.hpp:25
std::string description() override
Get the description of the Matcher.
Definition be_within.hpp:74
std::string failure_message() override
Get message to give on match failure.
Definition be_within.hpp:64
std::string failure_message_when_negated() override
Get message to give on match failure when negated.
Definition be_within.hpp:69
Definition have_error.hpp:9
Contains the base class for all Matchers.