Debian Codegraph @

3rdparty/catch2/docs/matchers.md

raw symbols SCIP
1 <a id="top"></a>
2 # Matchers
3
4 **Contents**<br>
5 [Using Matchers](#using-matchers)<br>
6 [Built-in matchers](#built-in-matchers)<br>
7 [Writing custom matchers (old style)](#writing-custom-matchers-old-style)<br>
8 [Writing custom matchers (new style)](#writing-custom-matchers-new-style)<br>
9
10 Matchers, as popularized by the [Hamcrest](https://en.wikipedia.org/wiki/Hamcrest)
11 framework are an alternative way to write assertions, useful for tests
12 where you work with complex types or need to assert more complex
13 properties. Matchers are easily composable and users can write their
14 own and combine them with the Catch2-provided matchers seamlessly.
15
16
17 ## Using Matchers
18
19 Matchers are most commonly used in tandem with the `REQUIRE_THAT` or
20 `CHECK_THAT` macros. The `REQUIRE_THAT` macro takes two arguments,
21 the first one is the input (object/value) to test, the second argument
22 is the matcher itself.
23
24 For example, to assert that a string ends with the "as a service"
25 substring, you can write the following assertion
26
27 ```cpp
28 using Catch::Matchers::EndsWith;
29
30 REQUIRE_THAT( getSomeString(), EndsWith("as a service") );
31 ```
32
33 Individual matchers can also be combined using the C++ logical
34 operators, that is `&&`, `||`, and `!`, like so:
35
36 ```cpp
37 using Catch::Matchers::EndsWith;
38 using Catch::Matchers::ContainsSubstring;
39
40 REQUIRE_THAT( getSomeString(),
41 EndsWith("as a service") && ContainsSubstring("web scale"));
42 ```
43
44 The example above asserts that the string returned from `getSomeString`
45 _both_ ends with the suffix "as a service" _and_ contains the string
46 "web scale" somewhere.
47
48
49 Both of the string matchers used in the examples above live in the
50 `catch_matchers_string.hpp` header, so to compile the code above also
51 requires `#include <catch2/matchers/catch_matchers_string.hpp>`.
52
53 **IMPORTANT**: The combining operators do not take ownership of the
54 matcher objects being combined. This means that if you store combined
55 matcher object, you have to ensure that the matchers being combined
56 outlive its last use. What this means is that the following code leads
57 to a use-after-free (UAF):
58
59 ```cpp
60 #include <catch2/catch_test_macros.hpp>
61 #include <catch2/matchers/catch_matchers_string.hpp>
62
63 TEST_CASE("Bugs, bugs, bugs", "[Bug]"){
64 std::string str = "Bugs as a service";
65
66 auto match_expression = Catch::Matchers::EndsWith( "as a service" ) ||
67 (Catch::Matchers::StartsWith( "Big data" ) && !Catch::Matchers::ContainsSubstring( "web scale" ) );
68 REQUIRE_THAT(str, match_expression);
69 }
70 ```
71
72
73 ## Built-in matchers
74
75 Every matcher provided by Catch2 is split into 2 parts, a factory
76 function that lives in the `Catch::Matchers` namespace, and the actual
77 matcher type that is in some deeper namespace and should not be used by
78 the user. In the examples above, we used `Catch::Matchers::Contains`.
79 This is the factory function for the
80 `Catch::Matchers::StdString::ContainsMatcher` type that does the actual
81 matching.
82
83 Out of the box, Catch2 provides the following matchers:
84
85
86 ### `std::string` matchers
87
88 Catch2 provides 5 different matchers that work with `std::string`,
89 * `StartsWith(std::string str, CaseSensitive)`,
90 * `EndsWith(std::string str, CaseSensitive)`,
91 * `ContainsSubstring(std::string str, CaseSensitive)`,
92 * `Equals(std::string str, CaseSensitive)`, and
93 * `Matches(std::string str, CaseSensitive)`.
94
95 The first three should be fairly self-explanatory, they succeed if
96 the argument starts with `str`, ends with `str`, or contains `str`
97 somewhere inside it.
98
99 The `Equals` matcher matches a string if (and only if) the argument
100 string is equal to `str`.
101
102 Finally, the `Matches` matcher performs an ECMAScript regex match using
103 `str` against the argument string. It is important to know that
104 the match is performed against the string as a whole, meaning that
105 the regex `"abc"` will not match input string `"abcd"`. To match
106 `"abcd"`, you need to use e.g. `"abc.*"` as your regex.
107
108 The second argument sets whether the matching should be case-sensitive
109 or not. By default, it is case-sensitive.
110
111 > `std::string` matchers live in `catch2/matchers/catch_matchers_string.hpp`
112
113
114 ### Vector matchers
115
116 _Vector matchers have been deprecated in favour of the generic
117 range matchers with the same functionality._
118
119 Catch2 provides 5 built-in matchers that work on `std::vector`.
120
121 These are
122
123 * `Contains` which checks whether a specified vector is present in the result
124 * `VectorContains` which checks whether a specified element is present in the result
125 * `Equals` which checks whether the result is exactly equal (order matters) to a specific vector
126 * `UnorderedEquals` which checks whether the result is equal to a specific vector under a permutation
127 * `Approx` which checks whether the result is "approx-equal" (order matters, but comparison is done via `Approx`) to a specific vector
128 > Approx matcher was [introduced](https://github.com/catchorg/Catch2/issues/1499) in Catch2 2.7.2.
129
130 An example usage:
131 ```cpp
132 std::vector<int> some_vec{ 1, 2, 3 };
133 REQUIRE_THAT(some_vec, Catch::Matchers::UnorderedEquals(std::vector<int>{ 3, 2, 1 }));
134 ```
135
136 This assertions will pass, because the elements given to the matchers
137 are a permutation of the ones in `some_vec`.
138
139 > vector matchers live in `catch2/matchers/catch_matchers_vector.hpp`
140
141
142 ### Floating point matchers
143
144 Catch2 provides 4 matchers that target floating point numbers. These
145 are:
146
147 * `WithinAbs(double target, double margin)`,
148 * `WithinULP(FloatingPoint target, uint64_t maxUlpDiff)`, and
149 * `WithinRel(FloatingPoint target, FloatingPoint eps)`.
150 * `IsNaN()`
151
152 > `WithinRel` matcher was introduced in Catch2 2.10.0
153
154 > `IsNaN` matcher was introduced in Catch2 3.3.2.
155
156 The first three serve to compare two floating pointe numbers. For more
157 details about how they work, read [the docs on comparing floating point
158 numbers](comparing-floating-point-numbers.md#floating-point-matchers).
159
160 `IsNaN` then does exactly what it says on the tin. It matches the input
161 if it is a NaN (Not a Number). The advantage of using it over just plain
162 `REQUIRE(std::isnan(x))`, is that if the check fails, with `REQUIRE` you
163 won't see the value of `x`, but with `REQUIRE_THAT(x, IsNaN())`, you will.
164
165
166 ### Miscellaneous matchers
167
168 Catch2 also provides some matchers and matcher utilities that do not
169 quite fit into other categories.
170
171 The first one of them is the `Predicate(Callable pred, std::string description)`
172 matcher. It creates a matcher object that calls `pred` for the provided
173 argument. The `description` argument allows users to set what the
174 resulting matcher should self-describe as if required.
175
176 Do note that you will need to explicitly specify the type of the
177 argument, like in this example:
178
179 ```cpp
180 REQUIRE_THAT("Hello olleH",
181 Predicate<std::string>(
182 [] (std::string const& str) -> bool { return str.front() == str.back(); },
183 "First and last character should be equal")
184 );
185 ```
186
187 > the predicate matcher lives in `catch2/matchers/catch_matchers_predicate.hpp`
188
189
190 The other miscellaneous matcher utility is exception matching.
191
192
193 #### Matching exceptions
194
195 Catch2 provides a utility macro for asserting that an expression
196 throws exception of specific type, and that the exception has desired
197 properties. The macro is `REQUIRE_THROWS_MATCHES(expr, ExceptionType, Matcher)`.
198
199 > `REQUIRE_THROWS_MATCHES` macro lives in `catch2/matchers/catch_matchers.hpp`
200
201
202 Catch2 currently provides two matchers for exceptions.
203 These are:
204 * `Message(std::string message)`.
205 * `MessageMatches(Matcher matcher)`.
206
207 > `MessageMatches` was [introduced](https://github.com/catchorg/Catch2/pull/2570) in Catch2 3.3.0
208
209 `Message` checks that the exception's
210 message, as returned from `what` is exactly equal to `message`.
211
212 `MessageMatches` applies the provided matcher on the exception's
213 message, as returned from `what`. This is useful in conjunctions with the `std::string` matchers (e.g. `StartsWith`)
214
215 Example use:
216 ```cpp
217 REQUIRE_THROWS_MATCHES(throwsDerivedException(), DerivedException, Message("DerivedException::what"));
218 REQUIRE_THROWS_MATCHES(throwsDerivedException(), DerivedException, MessageMatches(StartsWith("DerivedException")));
219 ```
220
221 Note that `DerivedException` in the example above has to derive from
222 `std::exception` for the example to work.
223
224 > the exception message matcher lives in `catch2/matchers/catch_matchers_exception.hpp`
225
226
227 ### Generic range Matchers
228
229 > Generic range matchers were introduced in Catch2 3.0.1
230
231 Catch2 also provides some matchers that use the new style matchers
232 definitions to handle generic range-like types. These are:
233
234 * `IsEmpty()`
235 * `SizeIs(size_t target_size)`
236 * `SizeIs(Matcher size_matcher)`
237 * `Contains(T&& target_element, Comparator = std::equal_to<>{})`
238 * `Contains(Matcher element_matcher)`
239 * `AllMatch(Matcher element_matcher)`
240 * `AnyMatch(Matcher element_matcher)`
241 * `NoneMatch(Matcher element_matcher)`
242 * `AllTrue()`, `AnyTrue()`, `NoneTrue()`
243 * `RangeEquals(TargetRangeLike&&, Comparator = std::equal_to<>{})`
244 * `UnorderedRangeEquals(TargetRangeLike&&, Comparator = std::equal_to<>{})`
245
246 > `IsEmpty`, `SizeIs`, `Contains` were introduced in Catch2 3.0.1
247
248 > `All/Any/NoneMatch` were introduced in Catch2 3.0.1
249
250 > `All/Any/NoneTrue` were introduced in Catch2 3.1.0
251
252 > `RangeEquals` and `UnorderedRangeEquals` matchers were [introduced](https://github.com/catchorg/Catch2/pull/2377) in Catch2 3.3.0
253
254 `IsEmpty` should be self-explanatory. It successfully matches objects
255 that are empty according to either `std::empty`, or ADL-found `empty`
256 free function.
257
258 `SizeIs` checks range's size. If constructed with `size_t` arg, the
259 matchers accepts ranges whose size is exactly equal to the arg. If
260 constructed from another matcher, then the resulting matcher accepts
261 ranges whose size is accepted by the provided matcher.
262
263 `Contains` accepts ranges that contain specific element. There are
264 again two variants, one that accepts the desired element directly,
265 in which case a range is accepted if any of its elements is equal to
266 the target element. The other variant is constructed from a matcher,
267 in which case a range is accepted if any of its elements is accepted
268 by the provided matcher.
269
270 `AllMatch`, `NoneMatch`, and `AnyMatch` match ranges for which either
271 all, none, or any of the contained elements matches the given matcher,
272 respectively.
273
274 `AllTrue`, `NoneTrue`, and `AnyTrue` match ranges for which either
275 all, none, or any of the contained elements are `true`, respectively.
276 It works for ranges of `bool`s and ranges of elements (explicitly)
277 convertible to `bool`.
278
279 `RangeEquals` compares the range that the matcher is constructed with
280 (the "target range") against the range to be tested, element-wise. The
281 match succeeds if all elements from the two ranges compare equal (using
282 `operator==` by default). The ranges do not need to be the same type,
283 and the element types do not need to be the same, as long as they are
284 comparable. (e.g. you may compare `std::vector<int>` to `std::array<char>`).
285
286 `UnorderedRangeEquals` is similar to `RangeEquals`, but the order
287 does not matter. For example "1, 2, 3" would match "3, 2, 1", but not
288 "1, 1, 2, 3" As with `RangeEquals`, `UnorderedRangeEquals` compares
289 the individual elements using using `operator==` by default.
290
291 Both `RangeEquals` and `UnorderedRangeEquals` optionally accept a
292 predicate which can be used to compare the containers element-wise.
293
294 To check a container elementwise against a given matcher, use
295 `AllMatch`.
296
297
298 ## Writing custom matchers (old style)
299
300 The old style of writing matchers has been introduced back in Catch
301 Classic. To create an old-style matcher, you have to create your own
302 type that derives from `Catch::Matchers::MatcherBase<ArgT>`, where
303 `ArgT` is the type your matcher works for. Your type has to override
304 two methods, `bool match(ArgT const&) const`,
305 and `std::string describe() const`.
306
307 As the name suggests, `match` decides whether the provided argument
308 is matched (accepted) by the matcher. `describe` then provides a
309 human-oriented description of what the matcher does.
310
311 We also recommend that you create factory function, just like Catch2
312 does, but that is mostly useful for template argument deduction for
313 templated matchers (assuming you do not have CTAD available).
314
315 To combine these into an example, let's say that you want to write
316 a matcher that decides whether the provided argument is a number
317 within certain range. We will call it `IsBetweenMatcher<T>`:
318
319 ```c++
320 #include <catch2/catch_test_macros.hpp>
321 #include <catch2/matchers/catch_matchers.hpp>
322 // ...
323
324
325 template <typename T>
326 class IsBetweenMatcher : public Catch::Matchers::MatcherBase<T> {
327 T m_begin, m_end;
328 public:
329 IsBetweenMatcher(T begin, T end) : m_begin(begin), m_end(end) {}
330
331 bool match(T const& in) const override {
332 return in >= m_begin && in <= m_end;
333 }
334
335 std::string describe() const override {
336 std::ostringstream ss;
337 ss << "is between " << m_begin << " and " << m_end;
338 return ss.str();
339 }
340 };
341
342 template <typename T>
343 IsBetweenMatcher<T> IsBetween(T begin, T end) {
344 return { begin, end };
345 }
346
347 // ...
348
349 TEST_CASE("Numbers are within range") {
350 // infers `double` for the argument type of the matcher
351 CHECK_THAT(3., IsBetween(1., 10.));
352 // infers `int` for the argument type of the matcher
353 CHECK_THAT(100, IsBetween(1, 10));
354 }
355 ```
356
357 Obviously, the code above can be improved somewhat, for example you
358 might want to `static_assert` over the fact that `T` is an arithmetic
359 type... or generalize the matcher to cover any type for which the user
360 can provide a comparison function object.
361
362 Note that while any matcher written using the old style can also be
363 written using the new style, combining old style matchers should
364 generally compile faster. Also note that you can combine old and new
365 style matchers arbitrarily.
366
367 > `MatcherBase` lives in `catch2/matchers/catch_matchers.hpp`
368
369
370 ## Writing custom matchers (new style)
371
372 > New style matchers were introduced in Catch2 3.0.1
373
374 To create a new-style matcher, you have to create your own type that
375 derives from `Catch::Matchers::MatcherGenericBase`. Your type has to
376 also provide two methods, `bool match( ... ) const` and overridden
377 `std::string describe() const`.
378
379 Unlike with old-style matchers, there are no requirements on how
380 the `match` member function takes its argument. This means that the
381 argument can be taken by value or by mutating reference, but also that
382 the matcher's `match` member function can be templated.
383
384 This allows you to write more complex matcher, such as a matcher that
385 can compare one range-like (something that responds to `begin` and
386 `end`) object to another, like in the following example:
387
388 ```cpp
389 #include <catch2/catch_test_macros.hpp>
390 #include <catch2/matchers/catch_matchers_templated.hpp>
391 // ...
392
393 template<typename Range>
394 struct EqualsRangeMatcher : Catch::Matchers::MatcherGenericBase {
395 EqualsRangeMatcher(Range const& range):
396 range{ range }
397 {}
398
399 template<typename OtherRange>
400 bool match(OtherRange const& other) const {
401 using std::begin; using std::end;
402
403 return std::equal(begin(range), end(range), begin(other), end(other));
404 }
405
406 std::string describe() const override {
407 return "Equals: " + Catch::rangeToString(range);
408 }
409
410 private:
411 Range const& range;
412 };
413
414 template<typename Range>
415 auto EqualsRange(const Range& range) -> EqualsRangeMatcher<Range> {
416 return EqualsRangeMatcher<Range>{range};
417 }
418
419 TEST_CASE("Combining templated matchers", "[matchers][templated]") {
420 std::array<int, 3> container{{ 1,2,3 }};
421
422 std::array<int, 3> a{{ 1,2,3 }};
423 std::vector<int> b{ 0,1,2 };
424 std::list<int> c{ 4,5,6 };
425
426 REQUIRE_THAT(container, EqualsRange(a) || EqualsRange(b) || EqualsRange(c));
427 }
428 ```
429
430 Do note that while you can rewrite any matcher from the old style to
431 a new style matcher, combining new style matchers is more expensive
432 in terms of compilation time. Also note that you can combine old style
433 and new style matchers arbitrarily.
434
435 > `MatcherGenericBase` lives in `catch2/matchers/catch_matchers_templated.hpp`
436
437
438 ---
439
440 [Home](Readme.md#top)