Debian Codegraph @

Tests/Contrib/catch2/catch_all.hpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright Catch2 Authors
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // https://www.boost.org/LICENSE_1_0.txt)
5
6 // SPDX-License-Identifier: BSL-1.0
7
8 // Catch v3.1.1
9 // Generated: 2022-10-17 18:47:20.510385
10 // ----------------------------------------------------------
11 // This file is an amalgamation of multiple different files.
12 // You probably shouldn't edit it directly.
13 // ----------------------------------------------------------
14 #ifndef CATCH_AMALGAMATED_HPP_INCLUDED
15 #define CATCH_AMALGAMATED_HPP_INCLUDED
16
17
18 /** \file
19 * This is a convenience header for Catch2. It includes **all** of Catch2 headers.
20 *
21 * Generally the Catch2 users should use specific includes they need,
22 * but this header can be used instead for ease-of-experimentation, or
23 * just plain convenience, at the cost of (significantly) increased
24 * compilation times.
25 *
26 * When a new header is added to either the top level folder, or to the
27 * corresponding internal subfolder, it should be added here. Headers
28 * added to the various subparts (e.g. matchers, generators, etc...),
29 * should go their respective catch-all headers.
30 */
31
32 #ifndef CATCH_ALL_HPP_INCLUDED
33 #define CATCH_ALL_HPP_INCLUDED
34
35
36
37 /** \file
38 * This is a convenience header for Catch2's benchmarking. It includes
39 * **all** of Catch2 headers related to benchmarking.
40 *
41 * Generally the Catch2 users should use specific includes they need,
42 * but this header can be used instead for ease-of-experimentation, or
43 * just plain convenience, at the cost of (significantly) increased
44 * compilation times.
45 *
46 * When a new header is added to either the `benchmark` folder, or to
47 * the corresponding internal (detail) subfolder, it should be added here.
48 */
49
50 #ifndef CATCH_BENCHMARK_ALL_HPP_INCLUDED
51 #define CATCH_BENCHMARK_ALL_HPP_INCLUDED
52
53
54
55 // Adapted from donated nonius code.
56
57 #ifndef CATCH_BENCHMARK_HPP_INCLUDED
58 #define CATCH_BENCHMARK_HPP_INCLUDED
59
60
61
62 #ifndef CATCH_INTERFACES_CONFIG_HPP_INCLUDED
63 #define CATCH_INTERFACES_CONFIG_HPP_INCLUDED
64
65
66
67 #ifndef CATCH_NONCOPYABLE_HPP_INCLUDED
68 #define CATCH_NONCOPYABLE_HPP_INCLUDED
69
70 namespace Catch {
71 namespace Detail {
72
73 //! Deriving classes become noncopyable and nonmovable
74 class NonCopyable {
75 NonCopyable( NonCopyable const& ) = delete;
76 NonCopyable( NonCopyable&& ) = delete;
77 NonCopyable& operator=( NonCopyable const& ) = delete;
78 NonCopyable& operator=( NonCopyable&& ) = delete;
79
80 protected:
81 NonCopyable() noexcept = default;
82 };
83
84 } // namespace Detail
85 } // namespace Catch
86
87 #endif // CATCH_NONCOPYABLE_HPP_INCLUDED
88
89
90 #ifndef CATCH_STRINGREF_HPP_INCLUDED
91 #define CATCH_STRINGREF_HPP_INCLUDED
92
93 #include <cstddef>
94 #include <string>
95 #include <iosfwd>
96 #include <cassert>
97
98 namespace Catch {
99
100 /// A non-owning string class (similar to the forthcoming std::string_view)
101 /// Note that, because a StringRef may be a substring of another string,
102 /// it may not be null terminated.
103 class StringRef {
104 public:
105 using size_type = std::size_t;
106 using const_iterator = const char*;
107
108 private:
109 static constexpr char const* const s_empty = "";
110
111 char const* m_start = s_empty;
112 size_type m_size = 0;
113
114 public: // construction
115 constexpr StringRef() noexcept = default;
116
117 StringRef( char const* rawChars ) noexcept;
118
119 constexpr StringRef( char const* rawChars, size_type size ) noexcept
120 : m_start( rawChars ),
121 m_size( size )
122 {}
123
124 StringRef( std::string const& stdString ) noexcept
125 : m_start( stdString.c_str() ),
126 m_size( stdString.size() )
127 {}
128
129 explicit operator std::string() const {
130 return std::string(m_start, m_size);
131 }
132
133 public: // operators
134 auto operator == ( StringRef other ) const noexcept -> bool;
135 auto operator != (StringRef other) const noexcept -> bool {
136 return !(*this == other);
137 }
138
139 constexpr auto operator[] ( size_type index ) const noexcept -> char {
140 assert(index < m_size);
141 return m_start[index];
142 }
143
144 bool operator<(StringRef rhs) const noexcept;
145
146 public: // named queries
147 constexpr auto empty() const noexcept -> bool {
148 return m_size == 0;
149 }
150 constexpr auto size() const noexcept -> size_type {
151 return m_size;
152 }
153
154 // Returns a substring of [start, start + length).
155 // If start + length > size(), then the substring is [start, start + size()).
156 // If start > size(), then the substring is empty.
157 constexpr StringRef substr(size_type start, size_type length) const noexcept {
158 if (start < m_size) {
159 const auto shortened_size = m_size - start;
160 return StringRef(m_start + start, (shortened_size < length) ? shortened_size : length);
161 } else {
162 return StringRef();
163 }
164 }
165
166 // Returns the current start pointer. May not be null-terminated.
167 constexpr char const* data() const noexcept {
168 return m_start;
169 }
170
171 constexpr const_iterator begin() const { return m_start; }
172 constexpr const_iterator end() const { return m_start + m_size; }
173
174
175 friend std::string& operator += (std::string& lhs, StringRef sr);
176 friend std::ostream& operator << (std::ostream& os, StringRef sr);
177 friend std::string operator+(StringRef lhs, StringRef rhs);
178
179 /**
180 * Provides a three-way comparison with rhs
181 *
182 * Returns negative number if lhs < rhs, 0 if lhs == rhs, and a positive
183 * number if lhs > rhs
184 */
185 int compare( StringRef rhs ) const;
186 };
187
188
189 constexpr auto operator ""_sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
190 return StringRef( rawChars, size );
191 }
192 } // namespace Catch
193
194 constexpr auto operator ""_catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
195 return Catch::StringRef( rawChars, size );
196 }
197
198 #endif // CATCH_STRINGREF_HPP_INCLUDED
199
200 #include <chrono>
201 #include <iosfwd>
202 #include <string>
203 #include <vector>
204
205 namespace Catch {
206
207 enum class Verbosity {
208 Quiet = 0,
209 Normal,
210 High
211 };
212
213 struct WarnAbout { enum What {
214 Nothing = 0x00,
215 //! A test case or leaf section did not run any assertions
216 NoAssertions = 0x01,
217 //! A command line test spec matched no test cases
218 UnmatchedTestSpec = 0x02,
219 }; };
220
221 enum class ShowDurations {
222 DefaultForReporter,
223 Always,
224 Never
225 };
226 enum class TestRunOrder {
227 Declared,
228 LexicographicallySorted,
229 Randomized
230 };
231 enum class ColourMode : std::uint8_t {
232 //! Let Catch2 pick implementation based on platform detection
233 PlatformDefault,
234 //! Use ANSI colour code escapes
235 ANSI,
236 //! Use Win32 console colour API
237 Win32,
238 //! Don't use any colour
239 None
240 };
241 struct WaitForKeypress { enum When {
242 Never,
243 BeforeStart = 1,
244 BeforeExit = 2,
245 BeforeStartAndExit = BeforeStart | BeforeExit
246 }; };
247
248 class TestSpec;
249 class IStream;
250
251 class IConfig : public Detail::NonCopyable {
252 public:
253 virtual ~IConfig();
254
255 virtual bool allowThrows() const = 0;
256 virtual StringRef name() const = 0;
257 virtual bool includeSuccessfulResults() const = 0;
258 virtual bool shouldDebugBreak() const = 0;
259 virtual bool warnAboutMissingAssertions() const = 0;
260 virtual bool warnAboutUnmatchedTestSpecs() const = 0;
261 virtual bool zeroTestsCountAsSuccess() const = 0;
262 virtual int abortAfter() const = 0;
263 virtual bool showInvisibles() const = 0;
264 virtual ShowDurations showDurations() const = 0;
265 virtual double minDuration() const = 0;
266 virtual TestSpec const& testSpec() const = 0;
267 virtual bool hasTestFilters() const = 0;
268 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
269 virtual TestRunOrder runOrder() const = 0;
270 virtual uint32_t rngSeed() const = 0;
271 virtual unsigned int shardCount() const = 0;
272 virtual unsigned int shardIndex() const = 0;
273 virtual ColourMode defaultColourMode() const = 0;
274 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
275 virtual Verbosity verbosity() const = 0;
276
277 virtual bool skipBenchmarks() const = 0;
278 virtual bool benchmarkNoAnalysis() const = 0;
279 virtual unsigned int benchmarkSamples() const = 0;
280 virtual double benchmarkConfidenceInterval() const = 0;
281 virtual unsigned int benchmarkResamples() const = 0;
282 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
283 };
284 }
285
286 #endif // CATCH_INTERFACES_CONFIG_HPP_INCLUDED
287
288
289 #ifndef CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
290 #define CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
291
292 // Detect a number of compiler features - by compiler
293 // The following features are defined:
294 //
295 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
296 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
297 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
298 // ****************
299 // Note to maintainers: if new toggles are added please document them
300 // in configuration.md, too
301 // ****************
302
303 // In general each macro has a _NO_<feature name> form
304 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
305 // Many features, at point of detection, define an _INTERNAL_ macro, so they
306 // can be combined, en-mass, with the _NO_ forms later.
307
308
309
310 #ifndef CATCH_PLATFORM_HPP_INCLUDED
311 #define CATCH_PLATFORM_HPP_INCLUDED
312
313 // See e.g.:
314 // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
315 #ifdef __APPLE__
316 # include <TargetConditionals.h>
317 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
318 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
319 # define CATCH_PLATFORM_MAC
320 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
321 # define CATCH_PLATFORM_IPHONE
322 # endif
323
324 #elif defined(linux) || defined(__linux) || defined(__linux__)
325 # define CATCH_PLATFORM_LINUX
326
327 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
328 # define CATCH_PLATFORM_WINDOWS
329
330 # if defined( WINAPI_FAMILY ) && ( WINAPI_FAMILY == WINAPI_FAMILY_APP )
331 # define CATCH_PLATFORM_WINDOWS_UWP
332 # endif
333 #endif
334
335 #endif // CATCH_PLATFORM_HPP_INCLUDED
336
337 #ifdef __cplusplus
338
339 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
340 # define CATCH_CPP14_OR_GREATER
341 # endif
342
343 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
344 # define CATCH_CPP17_OR_GREATER
345 # endif
346
347 #endif
348
349 // Only GCC compiler should be used in this block, so other compilers trying to
350 // mask themselves as GCC should be ignored.
351 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
352 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
353 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
354
355 // This only works on GCC 9+. so we have to also add a global suppression of Wparentheses
356 // for older versions of GCC.
357 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
358 _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" )
359
360 # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
361 _Pragma( "GCC diagnostic ignored \"-Wunused-variable\"" )
362
363 # define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
364 _Pragma( "GCC diagnostic ignored \"-Wuseless-cast\"" )
365
366 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
367
368 #endif
369
370 #if defined(__CUDACC__) && !defined(__clang__)
371 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "nv_diagnostic push" )
372 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "nv_diagnostic pop" )
373 # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS _Pragma( "nv_diag_suppress 177" )
374 #endif
375
376 // clang-cl defines _MSC_VER as well as __clang__, which could cause the
377 // start/stop internal suppression macros to be double defined.
378 #if defined(__clang__) && !defined(_MSC_VER)
379
380 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
381 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
382
383 #endif // __clang__ && !_MSC_VER
384
385 #if defined(__clang__)
386
387 // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
388 // which results in calls to destructors being emitted for each temporary,
389 // without a matching initialization. In practice, this can result in something
390 // like `std::string::~string` being called on an uninitialized value.
391 //
392 // For example, this code will likely segfault under IBM XL:
393 // ```
394 // REQUIRE(std::string("12") + "34" == "1234")
395 // ```
396 //
397 // Similarly, NVHPC's implementation of `__builtin_constant_p` has a bug which
398 // results in calls to the immediately evaluated lambda expressions to be
399 // reported as unevaluated lambdas.
400 // https://developer.nvidia.com/nvidia_bug/3321845.
401 //
402 // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
403 # if !defined(__ibmxl__) && !defined(__CUDACC__) && !defined( __NVCOMPILER )
404 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
405 # endif
406
407
408 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
409 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
410 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
411
412 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
413 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
414
415 # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
416 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
417
418 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
419 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
420
421 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
422 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
423
424 #endif // __clang__
425
426
427 ////////////////////////////////////////////////////////////////////////////////
428 // Assume that non-Windows platforms support posix signals by default
429 #if !defined(CATCH_PLATFORM_WINDOWS)
430 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
431 #endif
432
433 ////////////////////////////////////////////////////////////////////////////////
434 // We know some environments not to support full POSIX signals
435 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
436 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
437 #endif
438
439 #ifdef __OS400__
440 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
441 #endif
442
443 ////////////////////////////////////////////////////////////////////////////////
444 // Android somehow still does not support std::to_string
445 #if defined(__ANDROID__)
446 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
447 #endif
448
449 ////////////////////////////////////////////////////////////////////////////////
450 // Not all Windows environments support SEH properly
451 #if defined(__MINGW32__)
452 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
453 #endif
454
455 ////////////////////////////////////////////////////////////////////////////////
456 // PS4
457 #if defined(__ORBIS__)
458 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
459 #endif
460
461 ////////////////////////////////////////////////////////////////////////////////
462 // Cygwin
463 #ifdef __CYGWIN__
464
465 // Required for some versions of Cygwin to declare gettimeofday
466 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
467 # define _BSD_SOURCE
468 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
469 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
470 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
471 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
472
473 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
474
475 # endif
476 #endif // __CYGWIN__
477
478 ////////////////////////////////////////////////////////////////////////////////
479 // Visual C++
480 #if defined(_MSC_VER)
481
482 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
483 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
484
485 // Universal Windows platform does not support SEH
486 // Or console colours (or console at all...)
487 # if defined(CATCH_PLATFORM_WINDOWS_UWP)
488 # define CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32
489 # else
490 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
491 # endif
492
493 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
494 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
495 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
496 # if !defined(__clang__) // Handle Clang masquerading for msvc
497 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
498 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
499 # endif // MSVC_TRADITIONAL
500 # endif // __clang__
501
502 #endif // _MSC_VER
503
504 #if defined(_REENTRANT) || defined(_MSC_VER)
505 // Enable async processing, as -pthread is specified or no additional linking is required
506 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
507 #endif // _MSC_VER
508
509 ////////////////////////////////////////////////////////////////////////////////
510 // Check if we are compiled with -fno-exceptions or equivalent
511 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
512 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
513 #endif
514
515
516 ////////////////////////////////////////////////////////////////////////////////
517 // Embarcadero C++Build
518 #if defined(__BORLANDC__)
519 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
520 #endif
521
522 ////////////////////////////////////////////////////////////////////////////////
523
524 // RTX is a special version of Windows that is real time.
525 // This means that it is detected as Windows, but does not provide
526 // the same set of capabilities as real Windows does.
527 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
528 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
529 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
530 #define CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32
531 #endif
532
533 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
534 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
535 #endif
536
537 // Various stdlib support checks that require __has_include
538 #if defined(__has_include)
539 // Check if string_view is available and usable
540 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
541 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
542 #endif
543
544 // Check if optional is available and usable
545 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
546 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
547 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
548
549 // Check if byte is available and usable
550 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
551 # include <cstddef>
552 # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
553 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
554 # endif
555 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
556
557 // Check if variant is available and usable
558 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
559 # if defined(__clang__) && (__clang_major__ < 8)
560 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
561 // fix should be in clang 8, workaround in libstdc++ 8.2
562 # include <ciso646>
563 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
564 # define CATCH_CONFIG_NO_CPP17_VARIANT
565 # else
566 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
567 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
568 # else
569 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
570 # endif // defined(__clang__) && (__clang_major__ < 8)
571 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
572 #endif // defined(__has_include)
573
574
575 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
576 # define CATCH_CONFIG_WINDOWS_SEH
577 #endif
578 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
579 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
580 # define CATCH_CONFIG_POSIX_SIGNALS
581 #endif
582
583 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
584 # define CATCH_CONFIG_CPP11_TO_STRING
585 #endif
586
587 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
588 # define CATCH_CONFIG_CPP17_OPTIONAL
589 #endif
590
591 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
592 # define CATCH_CONFIG_CPP17_STRING_VIEW
593 #endif
594
595 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
596 # define CATCH_CONFIG_CPP17_VARIANT
597 #endif
598
599 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
600 # define CATCH_CONFIG_CPP17_BYTE
601 #endif
602
603
604 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
605 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
606 #endif
607
608 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
609 # define CATCH_CONFIG_NEW_CAPTURE
610 #endif
611
612 #if !defined( CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED ) && \
613 !defined( CATCH_CONFIG_DISABLE_EXCEPTIONS ) && \
614 !defined( CATCH_CONFIG_NO_DISABLE_EXCEPTIONS )
615 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
616 #endif
617
618 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
619 # define CATCH_CONFIG_POLYFILL_ISNAN
620 #endif
621
622 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
623 # define CATCH_CONFIG_USE_ASYNC
624 #endif
625
626 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
627 # define CATCH_CONFIG_GLOBAL_NEXTAFTER
628 #endif
629
630
631 // Even if we do not think the compiler has that warning, we still have
632 // to provide a macro that can be used by the code.
633 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
634 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
635 #endif
636 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
637 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
638 #endif
639 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
640 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
641 #endif
642 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
643 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
644 #endif
645 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS)
646 # define CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS
647 #endif
648 #if !defined(CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS)
649 # define CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS
650 #endif
651 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
652 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
653 #endif
654
655 // The goal of this macro is to avoid evaluation of the arguments, but
656 // still have the compiler warn on problems inside...
657 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
658 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
659 #endif
660
661 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
662 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
663 #elif defined(__clang__) && (__clang_major__ < 5)
664 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
665 #endif
666
667 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
668 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
669 #endif
670
671 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
672 #define CATCH_TRY if ((true))
673 #define CATCH_CATCH_ALL if ((false))
674 #define CATCH_CATCH_ANON(type) if ((false))
675 #else
676 #define CATCH_TRY try
677 #define CATCH_CATCH_ALL catch (...)
678 #define CATCH_CATCH_ANON(type) catch (type)
679 #endif
680
681 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
682 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
683 #endif
684
685 #if defined( CATCH_PLATFORM_WINDOWS ) && \
686 !defined( CATCH_CONFIG_COLOUR_WIN32 ) && \
687 !defined( CATCH_CONFIG_NO_COLOUR_WIN32 ) && \
688 !defined( CATCH_INTERNAL_CONFIG_NO_COLOUR_WIN32 )
689 # define CATCH_CONFIG_COLOUR_WIN32
690 #endif
691
692 #if defined( CATCH_CONFIG_SHARED_LIBRARY ) && defined( _MSC_VER ) && \
693 !defined( CATCH_CONFIG_STATIC )
694 # ifdef Catch2_EXPORTS
695 # define CATCH_EXPORT //__declspec( dllexport ) // not needed
696 # else
697 # define CATCH_EXPORT __declspec( dllimport )
698 # endif
699 #else
700 # define CATCH_EXPORT
701 #endif
702
703 #endif // CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
704
705
706 #ifndef CATCH_CONTEXT_HPP_INCLUDED
707 #define CATCH_CONTEXT_HPP_INCLUDED
708
709
710 namespace Catch {
711
712 class IResultCapture;
713 class IConfig;
714
715 class IContext {
716 public:
717 virtual ~IContext(); // = default
718
719 virtual IResultCapture* getResultCapture() = 0;
720 virtual IConfig const* getConfig() const = 0;
721 };
722
723 class IMutableContext : public IContext {
724 public:
725 ~IMutableContext() override; // = default
726 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
727 virtual void setConfig( IConfig const* config ) = 0;
728
729 private:
730 CATCH_EXPORT static IMutableContext* currentContext;
731 friend IMutableContext& getCurrentMutableContext();
732 friend void cleanUpContext();
733 static void createContext();
734 };
735
736 inline IMutableContext& getCurrentMutableContext()
737 {
738 if( !IMutableContext::currentContext )
739 IMutableContext::createContext();
740 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
741 return *IMutableContext::currentContext;
742 }
743
744 inline IContext& getCurrentContext()
745 {
746 return getCurrentMutableContext();
747 }
748
749 void cleanUpContext();
750
751 class SimplePcg32;
752 SimplePcg32& sharedRng();
753 }
754
755 #endif // CATCH_CONTEXT_HPP_INCLUDED
756
757
758 #ifndef CATCH_INTERFACES_REPORTER_HPP_INCLUDED
759 #define CATCH_INTERFACES_REPORTER_HPP_INCLUDED
760
761
762
763 #ifndef CATCH_SECTION_INFO_HPP_INCLUDED
764 #define CATCH_SECTION_INFO_HPP_INCLUDED
765
766
767
768 #ifndef CATCH_MOVE_AND_FORWARD_HPP_INCLUDED
769 #define CATCH_MOVE_AND_FORWARD_HPP_INCLUDED
770
771 #include <type_traits>
772
773 //! Replacement for std::move with better compile time performance
774 #define CATCH_MOVE(...) static_cast<std::remove_reference_t<decltype(__VA_ARGS__)>&&>(__VA_ARGS__)
775
776 //! Replacement for std::forward with better compile time performance
777 #define CATCH_FORWARD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
778
779 #endif // CATCH_MOVE_AND_FORWARD_HPP_INCLUDED
780
781
782 #ifndef CATCH_SOURCE_LINE_INFO_HPP_INCLUDED
783 #define CATCH_SOURCE_LINE_INFO_HPP_INCLUDED
784
785 #include <cstddef>
786 #include <iosfwd>
787
788 namespace Catch {
789
790 struct SourceLineInfo {
791
792 SourceLineInfo() = delete;
793 constexpr SourceLineInfo( char const* _file, std::size_t _line ) noexcept:
794 file( _file ),
795 line( _line )
796 {}
797
798 bool operator == ( SourceLineInfo const& other ) const noexcept;
799 bool operator < ( SourceLineInfo const& other ) const noexcept;
800
801 char const* file;
802 std::size_t line;
803
804 friend std::ostream& operator << (std::ostream& os, SourceLineInfo const& info);
805 };
806 }
807
808 #define CATCH_INTERNAL_LINEINFO \
809 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
810
811 #endif // CATCH_SOURCE_LINE_INFO_HPP_INCLUDED
812
813
814 #ifndef CATCH_TOTALS_HPP_INCLUDED
815 #define CATCH_TOTALS_HPP_INCLUDED
816
817 #include <cstdint>
818
819 namespace Catch {
820
821 struct Counts {
822 Counts operator - ( Counts const& other ) const;
823 Counts& operator += ( Counts const& other );
824
825 std::uint64_t total() const;
826 bool allPassed() const;
827 bool allOk() const;
828
829 std::uint64_t passed = 0;
830 std::uint64_t failed = 0;
831 std::uint64_t failedButOk = 0;
832 };
833
834 struct Totals {
835
836 Totals operator - ( Totals const& other ) const;
837 Totals& operator += ( Totals const& other );
838
839 Totals delta( Totals const& prevTotals ) const;
840
841 Counts assertions;
842 Counts testCases;
843 };
844 }
845
846 #endif // CATCH_TOTALS_HPP_INCLUDED
847
848 #include <string>
849
850 namespace Catch {
851
852 struct SectionInfo {
853 // The last argument is ignored, so that people can write
854 // SECTION("ShortName", "Proper description that is long") and
855 // still use the `-c` flag comfortably.
856 SectionInfo( SourceLineInfo const& _lineInfo, std::string _name,
857 const char* const = nullptr ):
858 name(CATCH_MOVE(_name)),
859 lineInfo(_lineInfo)
860 {}
861
862 std::string name;
863 SourceLineInfo lineInfo;
864 };
865
866 struct SectionEndInfo {
867 SectionInfo sectionInfo;
868 Counts prevAssertions;
869 double durationInSeconds;
870 };
871
872 } // end namespace Catch
873
874 #endif // CATCH_SECTION_INFO_HPP_INCLUDED
875
876
877 #ifndef CATCH_ASSERTION_RESULT_HPP_INCLUDED
878 #define CATCH_ASSERTION_RESULT_HPP_INCLUDED
879
880
881
882 #ifndef CATCH_ASSERTION_INFO_HPP_INCLUDED
883 #define CATCH_ASSERTION_INFO_HPP_INCLUDED
884
885
886
887 #ifndef CATCH_RESULT_TYPE_HPP_INCLUDED
888 #define CATCH_RESULT_TYPE_HPP_INCLUDED
889
890 namespace Catch {
891
892 // ResultWas::OfType enum
893 struct ResultWas { enum OfType {
894 Unknown = -1,
895 Ok = 0,
896 Info = 1,
897 Warning = 2,
898
899 FailureBit = 0x10,
900
901 ExpressionFailed = FailureBit | 1,
902 ExplicitFailure = FailureBit | 2,
903
904 Exception = 0x100 | FailureBit,
905
906 ThrewException = Exception | 1,
907 DidntThrowException = Exception | 2,
908
909 FatalErrorCondition = 0x200 | FailureBit
910
911 }; };
912
913 bool isOk( ResultWas::OfType resultType );
914 bool isJustInfo( int flags );
915
916
917 // ResultDisposition::Flags enum
918 struct ResultDisposition { enum Flags {
919 Normal = 0x01,
920
921 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
922 FalseTest = 0x04, // Prefix expression with !
923 SuppressFail = 0x08 // Failures are reported but do not fail the test
924 }; };
925
926 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
927
928 bool shouldContinueOnFailure( int flags );
929 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
930 bool shouldSuppressFailure( int flags );
931
932 } // end namespace Catch
933
934 #endif // CATCH_RESULT_TYPE_HPP_INCLUDED
935
936 namespace Catch {
937
938 struct AssertionInfo {
939 // AssertionInfo() = delete;
940
941 StringRef macroName;
942 SourceLineInfo lineInfo;
943 StringRef capturedExpression;
944 ResultDisposition::Flags resultDisposition;
945 };
946
947 } // end namespace Catch
948
949 #endif // CATCH_ASSERTION_INFO_HPP_INCLUDED
950
951
952 #ifndef CATCH_LAZY_EXPR_HPP_INCLUDED
953 #define CATCH_LAZY_EXPR_HPP_INCLUDED
954
955 #include <iosfwd>
956
957 namespace Catch {
958
959 class ITransientExpression;
960
961 class LazyExpression {
962 friend class AssertionHandler;
963 friend struct AssertionStats;
964 friend class RunContext;
965
966 ITransientExpression const* m_transientExpression = nullptr;
967 bool m_isNegated;
968 public:
969 LazyExpression( bool isNegated ):
970 m_isNegated(isNegated)
971 {}
972 LazyExpression(LazyExpression const& other) = default;
973 LazyExpression& operator = ( LazyExpression const& ) = delete;
974
975 explicit operator bool() const {
976 return m_transientExpression != nullptr;
977 }
978
979 friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
980 };
981
982 } // namespace Catch
983
984 #endif // CATCH_LAZY_EXPR_HPP_INCLUDED
985
986 #include <string>
987
988 namespace Catch {
989
990 struct AssertionResultData
991 {
992 AssertionResultData() = delete;
993
994 AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
995
996 std::string message;
997 mutable std::string reconstructedExpression;
998 LazyExpression lazyExpression;
999 ResultWas::OfType resultType;
1000
1001 std::string reconstructExpression() const;
1002 };
1003
1004 class AssertionResult {
1005 public:
1006 AssertionResult() = delete;
1007 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
1008
1009 bool isOk() const;
1010 bool succeeded() const;
1011 ResultWas::OfType getResultType() const;
1012 bool hasExpression() const;
1013 bool hasMessage() const;
1014 std::string getExpression() const;
1015 std::string getExpressionInMacro() const;
1016 bool hasExpandedExpression() const;
1017 std::string getExpandedExpression() const;
1018 StringRef getMessage() const;
1019 SourceLineInfo getSourceInfo() const;
1020 StringRef getTestMacroName() const;
1021
1022 //protected:
1023 AssertionInfo m_info;
1024 AssertionResultData m_resultData;
1025 };
1026
1027 } // end namespace Catch
1028
1029 #endif // CATCH_ASSERTION_RESULT_HPP_INCLUDED
1030
1031
1032 #ifndef CATCH_MESSAGE_INFO_HPP_INCLUDED
1033 #define CATCH_MESSAGE_INFO_HPP_INCLUDED
1034
1035
1036
1037 #ifndef CATCH_INTERFACES_CAPTURE_HPP_INCLUDED
1038 #define CATCH_INTERFACES_CAPTURE_HPP_INCLUDED
1039
1040 #include <string>
1041 #include <chrono>
1042
1043
1044 namespace Catch {
1045
1046 class AssertionResult;
1047 struct AssertionInfo;
1048 struct SectionInfo;
1049 struct SectionEndInfo;
1050 struct MessageInfo;
1051 struct MessageBuilder;
1052 struct Counts;
1053 struct AssertionReaction;
1054 struct SourceLineInfo;
1055
1056 class ITransientExpression;
1057 class IGeneratorTracker;
1058
1059 struct BenchmarkInfo;
1060 template <typename Duration = std::chrono::duration<double, std::nano>>
1061 struct BenchmarkStats;
1062
1063 class IResultCapture {
1064 public:
1065 virtual ~IResultCapture();
1066
1067 virtual bool sectionStarted( SectionInfo const& sectionInfo,
1068 Counts& assertions ) = 0;
1069 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
1070 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
1071
1072 virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
1073
1074 virtual void benchmarkPreparing( StringRef name ) = 0;
1075 virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
1076 virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
1077 virtual void benchmarkFailed( StringRef error ) = 0;
1078
1079 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
1080 virtual void popScopedMessage( MessageInfo const& message ) = 0;
1081
1082 virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
1083
1084 virtual void handleFatalErrorCondition( StringRef message ) = 0;
1085
1086 virtual void handleExpr
1087 ( AssertionInfo const& info,
1088 ITransientExpression const& expr,
1089 AssertionReaction& reaction ) = 0;
1090 virtual void handleMessage
1091 ( AssertionInfo const& info,
1092 ResultWas::OfType resultType,
1093 StringRef message,
1094 AssertionReaction& reaction ) = 0;
1095 virtual void handleUnexpectedExceptionNotThrown
1096 ( AssertionInfo const& info,
1097 AssertionReaction& reaction ) = 0;
1098 virtual void handleUnexpectedInflightException
1099 ( AssertionInfo const& info,
1100 std::string const& message,
1101 AssertionReaction& reaction ) = 0;
1102 virtual void handleIncomplete
1103 ( AssertionInfo const& info ) = 0;
1104 virtual void handleNonExpr
1105 ( AssertionInfo const &info,
1106 ResultWas::OfType resultType,
1107 AssertionReaction &reaction ) = 0;
1108
1109
1110
1111 virtual bool lastAssertionPassed() = 0;
1112 virtual void assertionPassed() = 0;
1113
1114 // Deprecated, do not use:
1115 virtual std::string getCurrentTestName() const = 0;
1116 virtual const AssertionResult* getLastResult() const = 0;
1117 virtual void exceptionEarlyReported() = 0;
1118 };
1119
1120 IResultCapture& getResultCapture();
1121 }
1122
1123 #endif // CATCH_INTERFACES_CAPTURE_HPP_INCLUDED
1124
1125 #include <string>
1126
1127 namespace Catch {
1128
1129 struct MessageInfo {
1130 MessageInfo( StringRef _macroName,
1131 SourceLineInfo const& _lineInfo,
1132 ResultWas::OfType _type );
1133
1134 StringRef macroName;
1135 std::string message;
1136 SourceLineInfo lineInfo;
1137 ResultWas::OfType type;
1138 unsigned int sequence;
1139
1140 bool operator == (MessageInfo const& other) const {
1141 return sequence == other.sequence;
1142 }
1143 bool operator < (MessageInfo const& other) const {
1144 return sequence < other.sequence;
1145 }
1146 private:
1147 static unsigned int globalCount;
1148 };
1149
1150 } // end namespace Catch
1151
1152 #endif // CATCH_MESSAGE_INFO_HPP_INCLUDED
1153
1154
1155 #ifndef CATCH_UNIQUE_PTR_HPP_INCLUDED
1156 #define CATCH_UNIQUE_PTR_HPP_INCLUDED
1157
1158 #include <cassert>
1159 #include <type_traits>
1160
1161
1162 namespace Catch {
1163 namespace Detail {
1164 /**
1165 * A reimplementation of `std::unique_ptr` for improved compilation performance
1166 *
1167 * Does not support arrays nor custom deleters.
1168 */
1169 template <typename T>
1170 class unique_ptr {
1171 T* m_ptr;
1172 public:
1173 constexpr unique_ptr(std::nullptr_t = nullptr):
1174 m_ptr{}
1175 {}
1176 explicit constexpr unique_ptr(T* ptr):
1177 m_ptr(ptr)
1178 {}
1179
1180 template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
1181 unique_ptr(unique_ptr<U>&& from):
1182 m_ptr(from.release())
1183 {}
1184
1185 template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
1186 unique_ptr& operator=(unique_ptr<U>&& from) {
1187 reset(from.release());
1188
1189 return *this;
1190 }
1191
1192 unique_ptr(unique_ptr const&) = delete;
1193 unique_ptr& operator=(unique_ptr const&) = delete;
1194
1195 unique_ptr(unique_ptr&& rhs) noexcept:
1196 m_ptr(rhs.m_ptr) {
1197 rhs.m_ptr = nullptr;
1198 }
1199 unique_ptr& operator=(unique_ptr&& rhs) noexcept {
1200 reset(rhs.release());
1201
1202 return *this;
1203 }
1204
1205 ~unique_ptr() {
1206 delete m_ptr;
1207 }
1208
1209 T& operator*() {
1210 assert(m_ptr);
1211 return *m_ptr;
1212 }
1213 T const& operator*() const {
1214 assert(m_ptr);
1215 return *m_ptr;
1216 }
1217 T* operator->() noexcept {
1218 assert(m_ptr);
1219 return m_ptr;
1220 }
1221 T const* operator->() const noexcept {
1222 assert(m_ptr);
1223 return m_ptr;
1224 }
1225
1226 T* get() { return m_ptr; }
1227 T const* get() const { return m_ptr; }
1228
1229 void reset(T* ptr = nullptr) {
1230 delete m_ptr;
1231 m_ptr = ptr;
1232 }
1233
1234 T* release() {
1235 auto temp = m_ptr;
1236 m_ptr = nullptr;
1237 return temp;
1238 }
1239
1240 explicit operator bool() const {
1241 return m_ptr;
1242 }
1243
1244 friend void swap(unique_ptr& lhs, unique_ptr& rhs) {
1245 auto temp = lhs.m_ptr;
1246 lhs.m_ptr = rhs.m_ptr;
1247 rhs.m_ptr = temp;
1248 }
1249 };
1250
1251 //! Specialization to cause compile-time error for arrays
1252 template <typename T>
1253 class unique_ptr<T[]>;
1254
1255 template <typename T, typename... Args>
1256 unique_ptr<T> make_unique(Args&&... args) {
1257 return unique_ptr<T>(new T(CATCH_FORWARD(args)...));
1258 }
1259
1260
1261 } // end namespace Detail
1262 } // end namespace Catch
1263
1264 #endif // CATCH_UNIQUE_PTR_HPP_INCLUDED
1265
1266
1267 // Adapted from donated nonius code.
1268
1269 #ifndef CATCH_ESTIMATE_HPP_INCLUDED
1270 #define CATCH_ESTIMATE_HPP_INCLUDED
1271
1272 namespace Catch {
1273 namespace Benchmark {
1274 template <typename Duration>
1275 struct Estimate {
1276 Duration point;
1277 Duration lower_bound;
1278 Duration upper_bound;
1279 double confidence_interval;
1280
1281 template <typename Duration2>
1282 operator Estimate<Duration2>() const {
1283 return { point, lower_bound, upper_bound, confidence_interval };
1284 }
1285 };
1286 } // namespace Benchmark
1287 } // namespace Catch
1288
1289 #endif // CATCH_ESTIMATE_HPP_INCLUDED
1290
1291
1292 // Adapted from donated nonius code.
1293
1294 #ifndef CATCH_OUTLIER_CLASSIFICATION_HPP_INCLUDED
1295 #define CATCH_OUTLIER_CLASSIFICATION_HPP_INCLUDED
1296
1297 namespace Catch {
1298 namespace Benchmark {
1299 struct OutlierClassification {
1300 int samples_seen = 0;
1301 int low_severe = 0; // more than 3 times IQR below Q1
1302 int low_mild = 0; // 1.5 to 3 times IQR below Q1
1303 int high_mild = 0; // 1.5 to 3 times IQR above Q3
1304 int high_severe = 0; // more than 3 times IQR above Q3
1305
1306 int total() const {
1307 return low_severe + low_mild + high_mild + high_severe;
1308 }
1309 };
1310 } // namespace Benchmark
1311 } // namespace Catch
1312
1313 #endif // CATCH_OUTLIERS_CLASSIFICATION_HPP_INCLUDED
1314
1315
1316 #include <map>
1317 #include <string>
1318 #include <vector>
1319 #include <iosfwd>
1320
1321 namespace Catch {
1322
1323 struct ReporterDescription;
1324 struct ListenerDescription;
1325 struct TagInfo;
1326 struct TestCaseInfo;
1327 class TestCaseHandle;
1328 class IConfig;
1329 class IStream;
1330 enum class ColourMode : std::uint8_t;
1331
1332 struct ReporterConfig {
1333 ReporterConfig( IConfig const* _fullConfig,
1334 Detail::unique_ptr<IStream> _stream,
1335 ColourMode colourMode,
1336 std::map<std::string, std::string> customOptions );
1337
1338 ReporterConfig( ReporterConfig&& ) = default;
1339 ReporterConfig& operator=( ReporterConfig&& ) = default;
1340 ~ReporterConfig(); // = default
1341
1342 Detail::unique_ptr<IStream> takeStream() &&;
1343 IConfig const* fullConfig() const;
1344 ColourMode colourMode() const;
1345 std::map<std::string, std::string> const& customOptions() const;
1346
1347 private:
1348 Detail::unique_ptr<IStream> m_stream;
1349 IConfig const* m_fullConfig;
1350 ColourMode m_colourMode;
1351 std::map<std::string, std::string> m_customOptions;
1352 };
1353
1354 struct TestRunInfo {
1355 constexpr TestRunInfo(StringRef _name) : name(_name) {}
1356 StringRef name;
1357 };
1358
1359 struct AssertionStats {
1360 AssertionStats( AssertionResult const& _assertionResult,
1361 std::vector<MessageInfo> const& _infoMessages,
1362 Totals const& _totals );
1363
1364 AssertionStats( AssertionStats const& ) = default;
1365 AssertionStats( AssertionStats && ) = default;
1366 AssertionStats& operator = ( AssertionStats const& ) = delete;
1367 AssertionStats& operator = ( AssertionStats && ) = delete;
1368
1369 AssertionResult assertionResult;
1370 std::vector<MessageInfo> infoMessages;
1371 Totals totals;
1372 };
1373
1374 struct SectionStats {
1375 SectionStats( SectionInfo const& _sectionInfo,
1376 Counts const& _assertions,
1377 double _durationInSeconds,
1378 bool _missingAssertions );
1379
1380 SectionInfo sectionInfo;
1381 Counts assertions;
1382 double durationInSeconds;
1383 bool missingAssertions;
1384 };
1385
1386 struct TestCaseStats {
1387 TestCaseStats( TestCaseInfo const& _testInfo,
1388 Totals const& _totals,
1389 std::string const& _stdOut,
1390 std::string const& _stdErr,
1391 bool _aborting );
1392
1393 TestCaseInfo const * testInfo;
1394 Totals totals;
1395 std::string stdOut;
1396 std::string stdErr;
1397 bool aborting;
1398 };
1399
1400 struct TestRunStats {
1401 TestRunStats( TestRunInfo const& _runInfo,
1402 Totals const& _totals,
1403 bool _aborting );
1404
1405 TestRunInfo runInfo;
1406 Totals totals;
1407 bool aborting;
1408 };
1409
1410
1411 struct BenchmarkInfo {
1412 std::string name;
1413 double estimatedDuration;
1414 int iterations;
1415 unsigned int samples;
1416 unsigned int resamples;
1417 double clockResolution;
1418 double clockCost;
1419 };
1420
1421 template <class Duration>
1422 struct BenchmarkStats {
1423 BenchmarkInfo info;
1424
1425 std::vector<Duration> samples;
1426 Benchmark::Estimate<Duration> mean;
1427 Benchmark::Estimate<Duration> standardDeviation;
1428 Benchmark::OutlierClassification outliers;
1429 double outlierVariance;
1430
1431 template <typename Duration2>
1432 operator BenchmarkStats<Duration2>() const {
1433 std::vector<Duration2> samples2;
1434 samples2.reserve(samples.size());
1435 for (auto const& sample : samples) {
1436 samples2.push_back(Duration2(sample));
1437 }
1438 return {
1439 info,
1440 CATCH_MOVE(samples2),
1441 mean,
1442 standardDeviation,
1443 outliers,
1444 outlierVariance,
1445 };
1446 }
1447 };
1448
1449 //! By setting up its preferences, a reporter can modify Catch2's behaviour
1450 //! in some regards, e.g. it can request Catch2 to capture writes to
1451 //! stdout/stderr during test execution, and pass them to the reporter.
1452 struct ReporterPreferences {
1453 //! Catch2 should redirect writes to stdout and pass them to the
1454 //! reporter
1455 bool shouldRedirectStdOut = false;
1456 //! Catch2 should call `Reporter::assertionEnded` even for passing
1457 //! assertions
1458 bool shouldReportAllAssertions = false;
1459 };
1460
1461 /**
1462 * The common base for all reporters and event listeners
1463 *
1464 * Implementing classes must also implement:
1465 *
1466 * //! User-friendly description of the reporter/listener type
1467 * static std::string getDescription()
1468 *
1469 * Generally shouldn't be derived from by users of Catch2 directly,
1470 * instead they should derive from one of the utility bases that
1471 * derive from this class.
1472 */
1473 class IEventListener {
1474 protected:
1475 //! Derived classes can set up their preferences here
1476 ReporterPreferences m_preferences;
1477 //! The test run's config as filled in from CLI and defaults
1478 IConfig const* m_config;
1479
1480 public:
1481 IEventListener( IConfig const* config ): m_config( config ) {}
1482
1483 virtual ~IEventListener(); // = default;
1484
1485 // Implementing class must also provide the following static methods:
1486 // static std::string getDescription();
1487
1488 ReporterPreferences const& getPreferences() const {
1489 return m_preferences;
1490 }
1491
1492 //! Called when no test cases match provided test spec
1493 virtual void noMatchingTestCases( StringRef unmatchedSpec ) = 0;
1494 //! Called for all invalid test specs from the cli
1495 virtual void reportInvalidTestSpec( StringRef invalidArgument ) = 0;
1496
1497 /**
1498 * Called once in a testing run before tests are started
1499 *
1500 * Not called if tests won't be run (e.g. only listing will happen)
1501 */
1502 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
1503
1504 //! Called _once_ for each TEST_CASE, no matter how many times it is entered
1505 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
1506 //! Called _every time_ a TEST_CASE is entered, including repeats (due to sections)
1507 virtual void testCasePartialStarting( TestCaseInfo const& testInfo, uint64_t partNumber ) = 0;
1508 //! Called when a `SECTION` is being entered. Not called for skipped sections
1509 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
1510
1511 //! Called when user-code is being probed before the actual benchmark runs
1512 virtual void benchmarkPreparing( StringRef benchmarkName ) = 0;
1513 //! Called after probe but before the user-code is being benchmarked
1514 virtual void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) = 0;
1515 //! Called with the benchmark results if benchmark successfully finishes
1516 virtual void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) = 0;
1517 //! Called if running the benchmarks fails for any reason
1518 virtual void benchmarkFailed( StringRef benchmarkName ) = 0;
1519
1520 //! Called before assertion success/failure is evaluated
1521 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
1522
1523 //! Called after assertion was fully evaluated
1524 virtual void assertionEnded( AssertionStats const& assertionStats ) = 0;
1525
1526 //! Called after a `SECTION` has finished running
1527 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
1528 //! Called _every time_ a TEST_CASE is entered, including repeats (due to sections)
1529 virtual void testCasePartialEnded(TestCaseStats const& testCaseStats, uint64_t partNumber ) = 0;
1530 //! Called _once_ for each TEST_CASE, no matter how many times it is entered
1531 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
1532 /**
1533 * Called once after all tests in a testing run are finished
1534 *
1535 * Not called if tests weren't run (e.g. only listings happened)
1536 */
1537 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
1538
1539 //! Called with test cases that are skipped due to the test run aborting
1540 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
1541
1542 //! Called if a fatal error (signal/structured exception) occured
1543 virtual void fatalErrorEncountered( StringRef error ) = 0;
1544
1545 //! Writes out information about provided reporters using reporter-specific format
1546 virtual void listReporters(std::vector<ReporterDescription> const& descriptions) = 0;
1547 //! Writes out the provided listeners descriptions using reporter-specific format
1548 virtual void listListeners(std::vector<ListenerDescription> const& descriptions) = 0;
1549 //! Writes out information about provided tests using reporter-specific format
1550 virtual void listTests(std::vector<TestCaseHandle> const& tests) = 0;
1551 //! Writes out information about the provided tags using reporter-specific format
1552 virtual void listTags(std::vector<TagInfo> const& tags) = 0;
1553 };
1554 using IEventListenerPtr = Detail::unique_ptr<IEventListener>;
1555
1556 } // end namespace Catch
1557
1558 #endif // CATCH_INTERFACES_REPORTER_HPP_INCLUDED
1559
1560
1561 #ifndef CATCH_UNIQUE_NAME_HPP_INCLUDED
1562 #define CATCH_UNIQUE_NAME_HPP_INCLUDED
1563
1564
1565
1566
1567 /** \file
1568 * Wrapper for the CONFIG configuration option
1569 *
1570 * When generating internal unique names, there are two options. Either
1571 * we mix in the current line number, or mix in an incrementing number.
1572 * We prefer the latter, using `__COUNTER__`, but users might want to
1573 * use the former.
1574 */
1575
1576 #ifndef CATCH_CONFIG_COUNTER_HPP_INCLUDED
1577 #define CATCH_CONFIG_COUNTER_HPP_INCLUDED
1578
1579 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
1580 #define CATCH_INTERNAL_CONFIG_COUNTER
1581 #endif
1582
1583 #if defined( CATCH_INTERNAL_CONFIG_COUNTER ) && \
1584 !defined( CATCH_CONFIG_NO_COUNTER ) && \
1585 !defined( CATCH_CONFIG_COUNTER )
1586 # define CATCH_CONFIG_COUNTER
1587 #endif
1588
1589
1590 #endif // CATCH_CONFIG_COUNTER_HPP_INCLUDED
1591 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
1592 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
1593 #ifdef CATCH_CONFIG_COUNTER
1594 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
1595 #else
1596 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
1597 #endif
1598
1599 #endif // CATCH_UNIQUE_NAME_HPP_INCLUDED
1600
1601
1602 // Adapted from donated nonius code.
1603
1604 #ifndef CATCH_CHRONOMETER_HPP_INCLUDED
1605 #define CATCH_CHRONOMETER_HPP_INCLUDED
1606
1607
1608
1609 // Adapted from donated nonius code.
1610
1611 #ifndef CATCH_CLOCK_HPP_INCLUDED
1612 #define CATCH_CLOCK_HPP_INCLUDED
1613
1614 #include <chrono>
1615 #include <ratio>
1616
1617 namespace Catch {
1618 namespace Benchmark {
1619 template <typename Clock>
1620 using ClockDuration = typename Clock::duration;
1621 template <typename Clock>
1622 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
1623
1624 template <typename Clock>
1625 using TimePoint = typename Clock::time_point;
1626
1627 using default_clock = std::chrono::steady_clock;
1628
1629 template <typename Clock>
1630 struct now {
1631 TimePoint<Clock> operator()() const {
1632 return Clock::now();
1633 }
1634 };
1635
1636 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
1637 } // namespace Benchmark
1638 } // namespace Catch
1639
1640 #endif // CATCH_CLOCK_HPP_INCLUDED
1641
1642
1643 // Adapted from donated nonius code.
1644
1645 #ifndef CATCH_OPTIMIZER_HPP_INCLUDED
1646 #define CATCH_OPTIMIZER_HPP_INCLUDED
1647
1648 #if defined(_MSC_VER)
1649 # include <atomic> // atomic_thread_fence
1650 #endif
1651
1652
1653 #include <type_traits>
1654
1655 namespace Catch {
1656 namespace Benchmark {
1657 #if defined(__GNUC__) || defined(__clang__)
1658 template <typename T>
1659 inline void keep_memory(T* p) {
1660 asm volatile("" : : "g"(p) : "memory");
1661 }
1662 inline void keep_memory() {
1663 asm volatile("" : : : "memory");
1664 }
1665
1666 namespace Detail {
1667 inline void optimizer_barrier() { keep_memory(); }
1668 } // namespace Detail
1669 #elif defined(_MSC_VER)
1670
1671 #pragma optimize("", off)
1672 template <typename T>
1673 inline void keep_memory(T* p) {
1674 // thanks @milleniumbug
1675 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
1676 }
1677 // TODO equivalent keep_memory()
1678 #pragma optimize("", on)
1679
1680 namespace Detail {
1681 inline void optimizer_barrier() {
1682 std::atomic_thread_fence(std::memory_order_seq_cst);
1683 }
1684 } // namespace Detail
1685
1686 #endif
1687
1688 template <typename T>
1689 inline void deoptimize_value(T&& x) {
1690 keep_memory(&x);
1691 }
1692
1693 template <typename Fn, typename... Args>
1694 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> std::enable_if_t<!std::is_same<void, decltype(fn(args...))>::value> {
1695 deoptimize_value(CATCH_FORWARD(fn) (CATCH_FORWARD(args)...));
1696 }
1697
1698 template <typename Fn, typename... Args>
1699 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> std::enable_if_t<std::is_same<void, decltype(fn(args...))>::value> {
1700 CATCH_FORWARD(fn) (CATCH_FORWARD(args)...);
1701 }
1702 } // namespace Benchmark
1703 } // namespace Catch
1704
1705 #endif // CATCH_OPTIMIZER_HPP_INCLUDED
1706
1707
1708 // Adapted from donated nonius code.
1709
1710 #ifndef CATCH_COMPLETE_INVOKE_HPP_INCLUDED
1711 #define CATCH_COMPLETE_INVOKE_HPP_INCLUDED
1712
1713
1714
1715 #ifndef CATCH_TEST_FAILURE_EXCEPTION_HPP_INCLUDED
1716 #define CATCH_TEST_FAILURE_EXCEPTION_HPP_INCLUDED
1717
1718 namespace Catch {
1719
1720 //! Used to signal that an assertion macro failed
1721 struct TestFailureException{};
1722
1723 } // namespace Catch
1724
1725 #endif // CATCH_TEST_FAILURE_EXCEPTION_HPP_INCLUDED
1726
1727
1728 #ifndef CATCH_META_HPP_INCLUDED
1729 #define CATCH_META_HPP_INCLUDED
1730
1731 #include <type_traits>
1732
1733 namespace Catch {
1734 template<typename T>
1735 struct always_false : std::false_type {};
1736
1737 template <typename> struct true_given : std::true_type {};
1738 struct is_callable_tester {
1739 template <typename Fun, typename... Args>
1740 static true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> test(int);
1741 template <typename...>
1742 static std::false_type test(...);
1743 };
1744
1745 template <typename T>
1746 struct is_callable;
1747
1748 template <typename Fun, typename... Args>
1749 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
1750
1751
1752 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
1753 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
1754 // replaced with std::invoke_result here.
1755 template <typename Func, typename... U>
1756 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
1757 #else
1758 template <typename Func, typename... U>
1759 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::result_of_t<Func(U...)>>>;
1760 #endif
1761
1762 } // namespace Catch
1763
1764 namespace mpl_{
1765 struct na;
1766 }
1767
1768 #endif // CATCH_META_HPP_INCLUDED
1769
1770
1771 #ifndef CATCH_INTERFACES_REGISTRY_HUB_HPP_INCLUDED
1772 #define CATCH_INTERFACES_REGISTRY_HUB_HPP_INCLUDED
1773
1774
1775 #include <string>
1776
1777 namespace Catch {
1778
1779 class TestCaseHandle;
1780 struct TestCaseInfo;
1781 class ITestCaseRegistry;
1782 class IExceptionTranslatorRegistry;
1783 class IExceptionTranslator;
1784 class IReporterRegistry;
1785 class IReporterFactory;
1786 class ITagAliasRegistry;
1787 class ITestInvoker;
1788 class IMutableEnumValuesRegistry;
1789 struct SourceLineInfo;
1790
1791 class StartupExceptionRegistry;
1792 class EventListenerFactory;
1793
1794 using IReporterFactoryPtr = Detail::unique_ptr<IReporterFactory>;
1795
1796 class IRegistryHub {
1797 public:
1798 virtual ~IRegistryHub(); // = default
1799
1800 virtual IReporterRegistry const& getReporterRegistry() const = 0;
1801 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
1802 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
1803 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
1804
1805
1806 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
1807 };
1808
1809 class IMutableRegistryHub {
1810 public:
1811 virtual ~IMutableRegistryHub(); // = default
1812 virtual void registerReporter( std::string const& name, IReporterFactoryPtr factory ) = 0;
1813 virtual void registerListener( Detail::unique_ptr<EventListenerFactory> factory ) = 0;
1814 virtual void registerTest(Detail::unique_ptr<TestCaseInfo>&& testInfo, Detail::unique_ptr<ITestInvoker>&& invoker) = 0;
1815 virtual void registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator ) = 0;
1816 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
1817 virtual void registerStartupException() noexcept = 0;
1818 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
1819 };
1820
1821 IRegistryHub const& getRegistryHub();
1822 IMutableRegistryHub& getMutableRegistryHub();
1823 void cleanUp();
1824 std::string translateActiveException();
1825
1826 }
1827
1828 #endif // CATCH_INTERFACES_REGISTRY_HUB_HPP_INCLUDED
1829
1830 #include <type_traits>
1831
1832 namespace Catch {
1833 namespace Benchmark {
1834 namespace Detail {
1835 template <typename T>
1836 struct CompleteType { using type = T; };
1837 template <>
1838 struct CompleteType<void> { struct type {}; };
1839
1840 template <typename T>
1841 using CompleteType_t = typename CompleteType<T>::type;
1842
1843 template <typename Result>
1844 struct CompleteInvoker {
1845 template <typename Fun, typename... Args>
1846 static Result invoke(Fun&& fun, Args&&... args) {
1847 return CATCH_FORWARD(fun)(CATCH_FORWARD(args)...);
1848 }
1849 };
1850 template <>
1851 struct CompleteInvoker<void> {
1852 template <typename Fun, typename... Args>
1853 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
1854 CATCH_FORWARD(fun)(CATCH_FORWARD(args)...);
1855 return {};
1856 }
1857 };
1858
1859 // invoke and not return void :(
1860 template <typename Fun, typename... Args>
1861 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
1862 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(CATCH_FORWARD(fun), CATCH_FORWARD(args)...);
1863 }
1864
1865 } // namespace Detail
1866
1867 template <typename Fun>
1868 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
1869 return Detail::complete_invoke(CATCH_FORWARD(fun));
1870 }
1871 } // namespace Benchmark
1872 } // namespace Catch
1873
1874 #endif // CATCH_COMPLETE_INVOKE_HPP_INCLUDED
1875
1876 namespace Catch {
1877 namespace Benchmark {
1878 namespace Detail {
1879 struct ChronometerConcept {
1880 virtual void start() = 0;
1881 virtual void finish() = 0;
1882 virtual ~ChronometerConcept(); // = default;
1883
1884 ChronometerConcept() = default;
1885 ChronometerConcept(ChronometerConcept const&) = default;
1886 ChronometerConcept& operator=(ChronometerConcept const&) = default;
1887 };
1888 template <typename Clock>
1889 struct ChronometerModel final : public ChronometerConcept {
1890 void start() override { started = Clock::now(); }
1891 void finish() override { finished = Clock::now(); }
1892
1893 ClockDuration<Clock> elapsed() const { return finished - started; }
1894
1895 TimePoint<Clock> started;
1896 TimePoint<Clock> finished;
1897 };
1898 } // namespace Detail
1899
1900 struct Chronometer {
1901 public:
1902 template <typename Fun>
1903 void measure(Fun&& fun) { measure(CATCH_FORWARD(fun), is_callable<Fun(int)>()); }
1904
1905 int runs() const { return repeats; }
1906
1907 Chronometer(Detail::ChronometerConcept& meter, int repeats_)
1908 : impl(&meter)
1909 , repeats(repeats_) {}
1910
1911 private:
1912 template <typename Fun>
1913 void measure(Fun&& fun, std::false_type) {
1914 measure([&fun](int) { return fun(); }, std::true_type());
1915 }
1916
1917 template <typename Fun>
1918 void measure(Fun&& fun, std::true_type) {
1919 Detail::optimizer_barrier();
1920 impl->start();
1921 for (int i = 0; i < repeats; ++i) invoke_deoptimized(fun, i);
1922 impl->finish();
1923 Detail::optimizer_barrier();
1924 }
1925
1926 Detail::ChronometerConcept* impl;
1927 int repeats;
1928 };
1929 } // namespace Benchmark
1930 } // namespace Catch
1931
1932 #endif // CATCH_CHRONOMETER_HPP_INCLUDED
1933
1934
1935 // Adapted from donated nonius code.
1936
1937 #ifndef CATCH_ENVIRONMENT_HPP_INCLUDED
1938 #define CATCH_ENVIRONMENT_HPP_INCLUDED
1939
1940
1941 namespace Catch {
1942 namespace Benchmark {
1943 template <typename Duration>
1944 struct EnvironmentEstimate {
1945 Duration mean;
1946 OutlierClassification outliers;
1947
1948 template <typename Duration2>
1949 operator EnvironmentEstimate<Duration2>() const {
1950 return { mean, outliers };
1951 }
1952 };
1953 template <typename Clock>
1954 struct Environment {
1955 using clock_type = Clock;
1956 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
1957 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
1958 };
1959 } // namespace Benchmark
1960 } // namespace Catch
1961
1962 #endif // CATCH_ENVIRONMENT_HPP_INCLUDED
1963
1964
1965 // Adapted from donated nonius code.
1966
1967 #ifndef CATCH_EXECUTION_PLAN_HPP_INCLUDED
1968 #define CATCH_EXECUTION_PLAN_HPP_INCLUDED
1969
1970
1971
1972 // Adapted from donated nonius code.
1973
1974 #ifndef CATCH_BENCHMARK_FUNCTION_HPP_INCLUDED
1975 #define CATCH_BENCHMARK_FUNCTION_HPP_INCLUDED
1976
1977
1978 #include <type_traits>
1979
1980 namespace Catch {
1981 namespace Benchmark {
1982 namespace Detail {
1983 template <typename T, typename U>
1984 struct is_related
1985 : std::is_same<std::decay_t<T>, std::decay_t<U>> {};
1986
1987 /// We need to reinvent std::function because every piece of code that might add overhead
1988 /// in a measurement context needs to have consistent performance characteristics so that we
1989 /// can account for it in the measurement.
1990 /// Implementations of std::function with optimizations that aren't always applicable, like
1991 /// small buffer optimizations, are not uncommon.
1992 /// This is effectively an implementation of std::function without any such optimizations;
1993 /// it may be slow, but it is consistently slow.
1994 struct BenchmarkFunction {
1995 private:
1996 struct callable {
1997 virtual void call(Chronometer meter) const = 0;
1998 virtual Catch::Detail::unique_ptr<callable> clone() const = 0;
1999 virtual ~callable(); // = default;
2000
2001 callable() = default;
2002 callable(callable const&) = default;
2003 callable& operator=(callable const&) = default;
2004 };
2005 template <typename Fun>
2006 struct model : public callable {
2007 model(Fun&& fun_) : fun(CATCH_MOVE(fun_)) {}
2008 model(Fun const& fun_) : fun(fun_) {}
2009
2010 Catch::Detail::unique_ptr<callable> clone() const override {
2011 return Catch::Detail::make_unique<model<Fun>>( *this );
2012 }
2013
2014 void call(Chronometer meter) const override {
2015 call(meter, is_callable<Fun(Chronometer)>());
2016 }
2017 void call(Chronometer meter, std::true_type) const {
2018 fun(meter);
2019 }
2020 void call(Chronometer meter, std::false_type) const {
2021 meter.measure(fun);
2022 }
2023
2024 Fun fun;
2025 };
2026
2027 struct do_nothing { void operator()() const {} };
2028
2029 template <typename T>
2030 BenchmarkFunction(model<T>* c) : f(c) {}
2031
2032 public:
2033 BenchmarkFunction()
2034 : f(new model<do_nothing>{ {} }) {}
2035
2036 template <typename Fun,
2037 std::enable_if_t<!is_related<Fun, BenchmarkFunction>::value, int> = 0>
2038 BenchmarkFunction(Fun&& fun)
2039 : f(new model<std::decay_t<Fun>>(CATCH_FORWARD(fun))) {}
2040
2041 BenchmarkFunction( BenchmarkFunction&& that ) noexcept:
2042 f( CATCH_MOVE( that.f ) ) {}
2043
2044 BenchmarkFunction(BenchmarkFunction const& that)
2045 : f(that.f->clone()) {}
2046
2047 BenchmarkFunction&
2048 operator=( BenchmarkFunction&& that ) noexcept {
2049 f = CATCH_MOVE( that.f );
2050 return *this;
2051 }
2052
2053 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
2054 f = that.f->clone();
2055 return *this;
2056 }
2057
2058 void operator()(Chronometer meter) const { f->call(meter); }
2059
2060 private:
2061 Catch::Detail::unique_ptr<callable> f;
2062 };
2063 } // namespace Detail
2064 } // namespace Benchmark
2065 } // namespace Catch
2066
2067 #endif // CATCH_BENCHMARK_FUNCTION_HPP_INCLUDED
2068
2069
2070 // Adapted from donated nonius code.
2071
2072 #ifndef CATCH_REPEAT_HPP_INCLUDED
2073 #define CATCH_REPEAT_HPP_INCLUDED
2074
2075 #include <type_traits>
2076
2077 namespace Catch {
2078 namespace Benchmark {
2079 namespace Detail {
2080 template <typename Fun>
2081 struct repeater {
2082 void operator()(int k) const {
2083 for (int i = 0; i < k; ++i) {
2084 fun();
2085 }
2086 }
2087 Fun fun;
2088 };
2089 template <typename Fun>
2090 repeater<std::decay_t<Fun>> repeat(Fun&& fun) {
2091 return { CATCH_FORWARD(fun) };
2092 }
2093 } // namespace Detail
2094 } // namespace Benchmark
2095 } // namespace Catch
2096
2097 #endif // CATCH_REPEAT_HPP_INCLUDED
2098
2099
2100 // Adapted from donated nonius code.
2101
2102 #ifndef CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED
2103 #define CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED
2104
2105
2106
2107 // Adapted from donated nonius code.
2108
2109 #ifndef CATCH_MEASURE_HPP_INCLUDED
2110 #define CATCH_MEASURE_HPP_INCLUDED
2111
2112
2113
2114 // Adapted from donated nonius code.
2115
2116 #ifndef CATCH_TIMING_HPP_INCLUDED
2117 #define CATCH_TIMING_HPP_INCLUDED
2118
2119
2120 #include <type_traits>
2121
2122 namespace Catch {
2123 namespace Benchmark {
2124 template <typename Duration, typename Result>
2125 struct Timing {
2126 Duration elapsed;
2127 Result result;
2128 int iterations;
2129 };
2130 template <typename Clock, typename Func, typename... Args>
2131 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
2132 } // namespace Benchmark
2133 } // namespace Catch
2134
2135 #endif // CATCH_TIMING_HPP_INCLUDED
2136
2137 namespace Catch {
2138 namespace Benchmark {
2139 namespace Detail {
2140 template <typename Clock, typename Fun, typename... Args>
2141 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
2142 auto start = Clock::now();
2143 auto&& r = Detail::complete_invoke(fun, CATCH_FORWARD(args)...);
2144 auto end = Clock::now();
2145 auto delta = end - start;
2146 return { delta, CATCH_FORWARD(r), 1 };
2147 }
2148 } // namespace Detail
2149 } // namespace Benchmark
2150 } // namespace Catch
2151
2152 #endif // CATCH_MEASURE_HPP_INCLUDED
2153
2154 #include <type_traits>
2155
2156 namespace Catch {
2157 namespace Benchmark {
2158 namespace Detail {
2159 template <typename Clock, typename Fun>
2160 TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
2161 return Detail::measure<Clock>(fun, iters);
2162 }
2163 template <typename Clock, typename Fun>
2164 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
2165 Detail::ChronometerModel<Clock> meter;
2166 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
2167
2168 return { meter.elapsed(), CATCH_MOVE(result), iters };
2169 }
2170
2171 template <typename Clock, typename Fun>
2172 using run_for_at_least_argument_t = std::conditional_t<is_callable<Fun(Chronometer)>::value, Chronometer, int>;
2173
2174
2175 [[noreturn]]
2176 void throw_optimized_away_error();
2177
2178 template <typename Clock, typename Fun>
2179 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>>
2180 run_for_at_least(ClockDuration<Clock> how_long,
2181 const int initial_iterations,
2182 Fun&& fun) {
2183 auto iters = initial_iterations;
2184 while (iters < (1 << 30)) {
2185 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
2186
2187 if (Timing.elapsed >= how_long) {
2188 return { Timing.elapsed, CATCH_MOVE(Timing.result), iters };
2189 }
2190 iters *= 2;
2191 }
2192 throw_optimized_away_error();
2193 }
2194 } // namespace Detail
2195 } // namespace Benchmark
2196 } // namespace Catch
2197
2198 #endif // CATCH_RUN_FOR_AT_LEAST_HPP_INCLUDED
2199
2200 #include <algorithm>
2201 #include <iterator>
2202
2203 namespace Catch {
2204 namespace Benchmark {
2205 template <typename Duration>
2206 struct ExecutionPlan {
2207 int iterations_per_sample;
2208 Duration estimated_duration;
2209 Detail::BenchmarkFunction benchmark;
2210 Duration warmup_time;
2211 int warmup_iterations;
2212
2213 template <typename Duration2>
2214 operator ExecutionPlan<Duration2>() const {
2215 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
2216 }
2217
2218 template <typename Clock>
2219 std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
2220 // warmup a bit
2221 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
2222
2223 std::vector<FloatDuration<Clock>> times;
2224 times.reserve(cfg.benchmarkSamples());
2225 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
2226 Detail::ChronometerModel<Clock> model;
2227 this->benchmark(Chronometer(model, iterations_per_sample));
2228 auto sample_time = model.elapsed() - env.clock_cost.mean;
2229 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
2230 return sample_time / iterations_per_sample;
2231 });
2232 return times;
2233 }
2234 };
2235 } // namespace Benchmark
2236 } // namespace Catch
2237
2238 #endif // CATCH_EXECUTION_PLAN_HPP_INCLUDED
2239
2240
2241 // Adapted from donated nonius code.
2242
2243 #ifndef CATCH_ESTIMATE_CLOCK_HPP_INCLUDED
2244 #define CATCH_ESTIMATE_CLOCK_HPP_INCLUDED
2245
2246
2247
2248 // Adapted from donated nonius code.
2249
2250 #ifndef CATCH_STATS_HPP_INCLUDED
2251 #define CATCH_STATS_HPP_INCLUDED
2252
2253
2254 #include <algorithm>
2255 #include <vector>
2256 #include <numeric>
2257 #include <tuple>
2258 #include <cmath>
2259
2260 namespace Catch {
2261 namespace Benchmark {
2262 namespace Detail {
2263 using sample = std::vector<double>;
2264
2265 // Used when we know we want == comparison of two doubles
2266 // to centralize warning suppression
2267 bool directCompare( double lhs, double rhs );
2268
2269 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
2270
2271 template <typename Iterator>
2272 OutlierClassification classify_outliers(Iterator first, Iterator last) {
2273 std::vector<double> copy(first, last);
2274
2275 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
2276 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
2277 auto iqr = q3 - q1;
2278 auto los = q1 - (iqr * 3.);
2279 auto lom = q1 - (iqr * 1.5);
2280 auto him = q3 + (iqr * 1.5);
2281 auto his = q3 + (iqr * 3.);
2282
2283 OutlierClassification o;
2284 for (; first != last; ++first) {
2285 auto&& t = *first;
2286 if (t < los) ++o.low_severe;
2287 else if (t < lom) ++o.low_mild;
2288 else if (t > his) ++o.high_severe;
2289 else if (t > him) ++o.high_mild;
2290 ++o.samples_seen;
2291 }
2292 return o;
2293 }
2294
2295 template <typename Iterator>
2296 double mean(Iterator first, Iterator last) {
2297 auto count = last - first;
2298 double sum = std::accumulate(first, last, 0.);
2299 return sum / static_cast<double>(count);
2300 }
2301
2302 template <typename Estimator, typename Iterator>
2303 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
2304 auto n = static_cast<size_t>(last - first);
2305 auto second = first;
2306 ++second;
2307 sample results;
2308 results.reserve(n);
2309
2310 for (auto it = first; it != last; ++it) {
2311 std::iter_swap(it, first);
2312 results.push_back(estimator(second, last));
2313 }
2314
2315 return results;
2316 }
2317
2318 inline double normal_cdf(double x) {
2319 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
2320 }
2321
2322 double erfc_inv(double x);
2323
2324 double normal_quantile(double p);
2325
2326 template <typename Iterator, typename Estimator>
2327 Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
2328 auto n_samples = last - first;
2329
2330 double point = estimator(first, last);
2331 // Degenerate case with a single sample
2332 if (n_samples == 1) return { point, point, point, confidence_level };
2333
2334 sample jack = jackknife(estimator, first, last);
2335 double jack_mean = mean(jack.begin(), jack.end());
2336 double sum_squares, sum_cubes;
2337 std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
2338 auto d = jack_mean - x;
2339 auto d2 = d * d;
2340 auto d3 = d2 * d;
2341 return { sqcb.first + d2, sqcb.second + d3 };
2342 });
2343
2344 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
2345 long n = static_cast<long>(resample.size());
2346 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / static_cast<double>(n);
2347 // degenerate case with uniform samples
2348 if ( directCompare( prob_n, 0. ) ) {
2349 return { point, point, point, confidence_level };
2350 }
2351
2352 double bias = normal_quantile(prob_n);
2353 double z1 = normal_quantile((1. - confidence_level) / 2.);
2354
2355 auto cumn = [n]( double x ) -> long {
2356 return std::lround( normal_cdf( x ) * static_cast<double>(n) );
2357 };
2358 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
2359 double b1 = bias + z1;
2360 double b2 = bias - z1;
2361 double a1 = a(b1);
2362 double a2 = a(b2);
2363 auto lo = static_cast<size_t>((std::max)(cumn(a1), 0l));
2364 auto hi = static_cast<size_t>((std::min)(cumn(a2), n - 1));
2365
2366 return { point, resample[lo], resample[hi], confidence_level };
2367 }
2368
2369 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
2370
2371 struct bootstrap_analysis {
2372 Estimate<double> mean;
2373 Estimate<double> standard_deviation;
2374 double outlier_variance;
2375 };
2376
2377 bootstrap_analysis analyse_samples(double confidence_level, unsigned int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
2378 } // namespace Detail
2379 } // namespace Benchmark
2380 } // namespace Catch
2381
2382 #endif // CATCH_STATS_HPP_INCLUDED
2383
2384 #include <algorithm>
2385 #include <iterator>
2386 #include <vector>
2387 #include <cmath>
2388
2389 namespace Catch {
2390 namespace Benchmark {
2391 namespace Detail {
2392 template <typename Clock>
2393 std::vector<double> resolution(int k) {
2394 std::vector<TimePoint<Clock>> times;
2395 times.reserve(static_cast<size_t>(k + 1));
2396 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
2397
2398 std::vector<double> deltas;
2399 deltas.reserve(static_cast<size_t>(k));
2400 std::transform(std::next(times.begin()), times.end(), times.begin(),
2401 std::back_inserter(deltas),
2402 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
2403
2404 return deltas;
2405 }
2406
2407 const auto warmup_iterations = 10000;
2408 const auto warmup_time = std::chrono::milliseconds(100);
2409 const auto minimum_ticks = 1000;
2410 const auto warmup_seed = 10000;
2411 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
2412 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
2413 const auto clock_cost_estimation_tick_limit = 100000;
2414 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
2415 const auto clock_cost_estimation_iterations = 10000;
2416
2417 template <typename Clock>
2418 int warmup() {
2419 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
2420 .iterations;
2421 }
2422 template <typename Clock>
2423 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
2424 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
2425 .result;
2426 return {
2427 FloatDuration<Clock>(mean(r.begin(), r.end())),
2428 classify_outliers(r.begin(), r.end()),
2429 };
2430 }
2431 template <typename Clock>
2432 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
2433 auto time_limit = (std::min)(
2434 resolution * clock_cost_estimation_tick_limit,
2435 FloatDuration<Clock>(clock_cost_estimation_time_limit));
2436 auto time_clock = [](int k) {
2437 return Detail::measure<Clock>([k] {
2438 for (int i = 0; i < k; ++i) {
2439 volatile auto ignored = Clock::now();
2440 (void)ignored;
2441 }
2442 }).elapsed;
2443 };
2444 time_clock(1);
2445 int iters = clock_cost_estimation_iterations;
2446 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
2447 std::vector<double> times;
2448 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
2449 times.reserve(static_cast<size_t>(nsamples));
2450 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
2451 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
2452 });
2453 return {
2454 FloatDuration<Clock>(mean(times.begin(), times.end())),
2455 classify_outliers(times.begin(), times.end()),
2456 };
2457 }
2458
2459 template <typename Clock>
2460 Environment<FloatDuration<Clock>> measure_environment() {
2461 #if defined(__clang__)
2462 # pragma clang diagnostic push
2463 # pragma clang diagnostic ignored "-Wexit-time-destructors"
2464 #endif
2465 static Catch::Detail::unique_ptr<Environment<FloatDuration<Clock>>> env;
2466 #if defined(__clang__)
2467 # pragma clang diagnostic pop
2468 #endif
2469 if (env) {
2470 return *env;
2471 }
2472
2473 auto iters = Detail::warmup<Clock>();
2474 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
2475 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
2476
2477 env = Catch::Detail::make_unique<Environment<FloatDuration<Clock>>>( Environment<FloatDuration<Clock>>{resolution, cost} );
2478 return *env;
2479 }
2480 } // namespace Detail
2481 } // namespace Benchmark
2482 } // namespace Catch
2483
2484 #endif // CATCH_ESTIMATE_CLOCK_HPP_INCLUDED
2485
2486
2487 // Adapted from donated nonius code.
2488
2489 #ifndef CATCH_ANALYSE_HPP_INCLUDED
2490 #define CATCH_ANALYSE_HPP_INCLUDED
2491
2492
2493
2494 // Adapted from donated nonius code.
2495
2496 #ifndef CATCH_SAMPLE_ANALYSIS_HPP_INCLUDED
2497 #define CATCH_SAMPLE_ANALYSIS_HPP_INCLUDED
2498
2499
2500 #include <algorithm>
2501 #include <vector>
2502 #include <iterator>
2503
2504 namespace Catch {
2505 namespace Benchmark {
2506 template <typename Duration>
2507 struct SampleAnalysis {
2508 std::vector<Duration> samples;
2509 Estimate<Duration> mean;
2510 Estimate<Duration> standard_deviation;
2511 OutlierClassification outliers;
2512 double outlier_variance;
2513
2514 template <typename Duration2>
2515 operator SampleAnalysis<Duration2>() const {
2516 std::vector<Duration2> samples2;
2517 samples2.reserve(samples.size());
2518 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
2519 return {
2520 CATCH_MOVE(samples2),
2521 mean,
2522 standard_deviation,
2523 outliers,
2524 outlier_variance,
2525 };
2526 }
2527 };
2528 } // namespace Benchmark
2529 } // namespace Catch
2530
2531 #endif // CATCH_SAMPLE_ANALYSIS_HPP_INCLUDED
2532
2533 #include <algorithm>
2534 #include <iterator>
2535 #include <vector>
2536
2537 namespace Catch {
2538 namespace Benchmark {
2539 namespace Detail {
2540 template <typename Duration, typename Iterator>
2541 SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
2542 if (!cfg.benchmarkNoAnalysis()) {
2543 std::vector<double> samples;
2544 samples.reserve(static_cast<size_t>(last - first));
2545 std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
2546
2547 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
2548 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
2549
2550 auto wrap_estimate = [](Estimate<double> e) {
2551 return Estimate<Duration> {
2552 Duration(e.point),
2553 Duration(e.lower_bound),
2554 Duration(e.upper_bound),
2555 e.confidence_interval,
2556 };
2557 };
2558 std::vector<Duration> samples2;
2559 samples2.reserve(samples.size());
2560 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
2561 return {
2562 CATCH_MOVE(samples2),
2563 wrap_estimate(analysis.mean),
2564 wrap_estimate(analysis.standard_deviation),
2565 outliers,
2566 analysis.outlier_variance,
2567 };
2568 } else {
2569 std::vector<Duration> samples;
2570 samples.reserve(static_cast<size_t>(last - first));
2571
2572 Duration mean = Duration(0);
2573 int i = 0;
2574 for (auto it = first; it < last; ++it, ++i) {
2575 samples.push_back(Duration(*it));
2576 mean += Duration(*it);
2577 }
2578 mean /= i;
2579
2580 return {
2581 CATCH_MOVE(samples),
2582 Estimate<Duration>{mean, mean, mean, 0.0},
2583 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
2584 OutlierClassification{},
2585 0.0
2586 };
2587 }
2588 }
2589 } // namespace Detail
2590 } // namespace Benchmark
2591 } // namespace Catch
2592
2593 #endif // CATCH_ANALYSE_HPP_INCLUDED
2594
2595 #include <algorithm>
2596 #include <functional>
2597 #include <string>
2598 #include <vector>
2599 #include <cmath>
2600
2601 namespace Catch {
2602 namespace Benchmark {
2603 struct Benchmark {
2604 Benchmark(std::string&& benchmarkName)
2605 : name(CATCH_MOVE(benchmarkName)) {}
2606
2607 template <class FUN>
2608 Benchmark(std::string&& benchmarkName , FUN &&func)
2609 : fun(CATCH_MOVE(func)), name(CATCH_MOVE(benchmarkName)) {}
2610
2611 template <typename Clock>
2612 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
2613 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
2614 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
2615 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
2616 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
2617 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
2618 }
2619
2620 template <typename Clock = default_clock>
2621 void run() {
2622 auto const* cfg = getCurrentContext().getConfig();
2623
2624 auto env = Detail::measure_environment<Clock>();
2625
2626 getResultCapture().benchmarkPreparing(name);
2627 CATCH_TRY{
2628 auto plan = user_code([&] {
2629 return prepare<Clock>(*cfg, env);
2630 });
2631
2632 BenchmarkInfo info {
2633 name,
2634 plan.estimated_duration.count(),
2635 plan.iterations_per_sample,
2636 cfg->benchmarkSamples(),
2637 cfg->benchmarkResamples(),
2638 env.clock_resolution.mean.count(),
2639 env.clock_cost.mean.count()
2640 };
2641
2642 getResultCapture().benchmarkStarting(info);
2643
2644 auto samples = user_code([&] {
2645 return plan.template run<Clock>(*cfg, env);
2646 });
2647
2648 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
2649 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
2650 getResultCapture().benchmarkEnded(stats);
2651 } CATCH_CATCH_ANON (TestFailureException) {
2652 getResultCapture().benchmarkFailed("Benchmark failed due to failed assertion"_sr);
2653 } CATCH_CATCH_ALL{
2654 getResultCapture().benchmarkFailed(translateActiveException());
2655 // We let the exception go further up so that the
2656 // test case is marked as failed.
2657 std::rethrow_exception(std::current_exception());
2658 }
2659 }
2660
2661 // sets lambda to be used in fun *and* executes benchmark!
2662 template <typename Fun, std::enable_if_t<!Detail::is_related<Fun, Benchmark>::value, int> = 0>
2663 Benchmark & operator=(Fun func) {
2664 auto const* cfg = getCurrentContext().getConfig();
2665 if (!cfg->skipBenchmarks()) {
2666 fun = Detail::BenchmarkFunction(func);
2667 run();
2668 }
2669 return *this;
2670 }
2671
2672 explicit operator bool() {
2673 return true;
2674 }
2675
2676 private:
2677 Detail::BenchmarkFunction fun;
2678 std::string name;
2679 };
2680 }
2681 } // namespace Catch
2682
2683 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
2684 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
2685
2686 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
2687 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
2688 BenchmarkName = [&](int benchmarkIndex)
2689
2690 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
2691 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
2692 BenchmarkName = [&]
2693
2694 #if defined(CATCH_CONFIG_PREFIX_ALL)
2695
2696 #define CATCH_BENCHMARK(...) \
2697 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
2698 #define CATCH_BENCHMARK_ADVANCED(name) \
2699 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), name)
2700
2701 #else
2702
2703 #define BENCHMARK(...) \
2704 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
2705 #define BENCHMARK_ADVANCED(name) \
2706 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(CATCH2_INTERNAL_BENCHMARK_), name)
2707
2708 #endif
2709
2710 #endif // CATCH_BENCHMARK_HPP_INCLUDED
2711
2712
2713 // Adapted from donated nonius code.
2714
2715 #ifndef CATCH_CONSTRUCTOR_HPP_INCLUDED
2716 #define CATCH_CONSTRUCTOR_HPP_INCLUDED
2717
2718
2719 #include <type_traits>
2720
2721 namespace Catch {
2722 namespace Benchmark {
2723 namespace Detail {
2724 template <typename T, bool Destruct>
2725 struct ObjectStorage
2726 {
2727 ObjectStorage() = default;
2728
2729 ObjectStorage(const ObjectStorage& other)
2730 {
2731 new(&data) T(other.stored_object());
2732 }
2733
2734 ObjectStorage(ObjectStorage&& other)
2735 {
2736 new(data) T(CATCH_MOVE(other.stored_object()));
2737 }
2738
2739 ~ObjectStorage() { destruct_on_exit<T>(); }
2740
2741 template <typename... Args>
2742 void construct(Args&&... args)
2743 {
2744 new (data) T(CATCH_FORWARD(args)...);
2745 }
2746
2747 template <bool AllowManualDestruction = !Destruct>
2748 std::enable_if_t<AllowManualDestruction> destruct()
2749 {
2750 stored_object().~T();
2751 }
2752
2753 private:
2754 // If this is a constructor benchmark, destruct the underlying object
2755 template <typename U>
2756 void destruct_on_exit(std::enable_if_t<Destruct, U>* = nullptr) { destruct<true>(); }
2757 // Otherwise, don't
2758 template <typename U>
2759 void destruct_on_exit(std::enable_if_t<!Destruct, U>* = nullptr) { }
2760
2761 #if defined( __GNUC__ ) && __GNUC__ <= 6
2762 # pragma GCC diagnostic push
2763 # pragma GCC diagnostic ignored "-Wstrict-aliasing"
2764 #endif
2765 T& stored_object() { return *reinterpret_cast<T*>( data ); }
2766
2767 T const& stored_object() const {
2768 return *reinterpret_cast<T const*>( data );
2769 }
2770 #if defined( __GNUC__ ) && __GNUC__ <= 6
2771 # pragma GCC diagnostic pop
2772 #endif
2773
2774 alignas( T ) unsigned char data[sizeof( T )]{};
2775 };
2776 } // namespace Detail
2777
2778 template <typename T>
2779 using storage_for = Detail::ObjectStorage<T, true>;
2780
2781 template <typename T>
2782 using destructable_object = Detail::ObjectStorage<T, false>;
2783 } // namespace Benchmark
2784 } // namespace Catch
2785
2786 #endif // CATCH_CONSTRUCTOR_HPP_INCLUDED
2787
2788 #endif // CATCH_BENCHMARK_ALL_HPP_INCLUDED
2789
2790
2791 #ifndef CATCH_APPROX_HPP_INCLUDED
2792 #define CATCH_APPROX_HPP_INCLUDED
2793
2794
2795
2796 #ifndef CATCH_TOSTRING_HPP_INCLUDED
2797 #define CATCH_TOSTRING_HPP_INCLUDED
2798
2799
2800 #include <vector>
2801 #include <cstddef>
2802 #include <type_traits>
2803 #include <string>
2804
2805
2806
2807
2808 /** \file
2809 * Wrapper for the WCHAR configuration option
2810 *
2811 * We want to support platforms that do not provide `wchar_t`, so we
2812 * sometimes have to disable providing wchar_t overloads through Catch2,
2813 * e.g. the StringMaker specialization for `std::wstring`.
2814 */
2815
2816 #ifndef CATCH_CONFIG_WCHAR_HPP_INCLUDED
2817 #define CATCH_CONFIG_WCHAR_HPP_INCLUDED
2818
2819 // We assume that WCHAR should be enabled by default, and only disabled
2820 // for a shortlist (so far only DJGPP) of compilers.
2821
2822 #if defined(__DJGPP__)
2823 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
2824 #endif // __DJGPP__
2825
2826 #if !defined( CATCH_INTERNAL_CONFIG_NO_WCHAR ) && \
2827 !defined( CATCH_CONFIG_NO_WCHAR ) && \
2828 !defined( CATCH_CONFIG_WCHAR )
2829 # define CATCH_CONFIG_WCHAR
2830 #endif
2831
2832 #endif // CATCH_CONFIG_WCHAR_HPP_INCLUDED
2833
2834
2835 #ifndef CATCH_REUSABLE_STRING_STREAM_HPP_INCLUDED
2836 #define CATCH_REUSABLE_STRING_STREAM_HPP_INCLUDED
2837
2838
2839 #include <iosfwd>
2840 #include <cstddef>
2841 #include <ostream>
2842 #include <string>
2843
2844 namespace Catch {
2845
2846 class ReusableStringStream : Detail::NonCopyable {
2847 std::size_t m_index;
2848 std::ostream* m_oss;
2849 public:
2850 ReusableStringStream();
2851 ~ReusableStringStream();
2852
2853 //! Returns the serialized state
2854 std::string str() const;
2855 //! Sets internal state to `str`
2856 void str(std::string const& str);
2857
2858 #if defined(__GNUC__) && !defined(__clang__)
2859 #pragma GCC diagnostic push
2860 // Old versions of GCC do not understand -Wnonnull-compare
2861 #pragma GCC diagnostic ignored "-Wpragmas"
2862 // Streaming a function pointer triggers Waddress and Wnonnull-compare
2863 // on GCC, because it implicitly converts it to bool and then decides
2864 // that the check it uses (a? true : false) is tautological and cannot
2865 // be null...
2866 #pragma GCC diagnostic ignored "-Waddress"
2867 #pragma GCC diagnostic ignored "-Wnonnull-compare"
2868 #endif
2869
2870 template<typename T>
2871 auto operator << ( T const& value ) -> ReusableStringStream& {
2872 *m_oss << value;
2873 return *this;
2874 }
2875
2876 #if defined(__GNUC__) && !defined(__clang__)
2877 #pragma GCC diagnostic pop
2878 #endif
2879 auto get() -> std::ostream& { return *m_oss; }
2880 };
2881 }
2882
2883 #endif // CATCH_REUSABLE_STRING_STREAM_HPP_INCLUDED
2884
2885
2886 #ifndef CATCH_VOID_TYPE_HPP_INCLUDED
2887 #define CATCH_VOID_TYPE_HPP_INCLUDED
2888
2889
2890 namespace Catch {
2891 namespace Detail {
2892
2893 template <typename...>
2894 struct make_void { using type = void; };
2895
2896 template <typename... Ts>
2897 using void_t = typename make_void<Ts...>::type;
2898
2899 } // namespace Detail
2900 } // namespace Catch
2901
2902
2903 #endif // CATCH_VOID_TYPE_HPP_INCLUDED
2904
2905
2906 #ifndef CATCH_INTERFACES_ENUM_VALUES_REGISTRY_HPP_INCLUDED
2907 #define CATCH_INTERFACES_ENUM_VALUES_REGISTRY_HPP_INCLUDED
2908
2909
2910 #include <vector>
2911
2912 namespace Catch {
2913
2914 namespace Detail {
2915 struct EnumInfo {
2916 StringRef m_name;
2917 std::vector<std::pair<int, StringRef>> m_values;
2918
2919 ~EnumInfo();
2920
2921 StringRef lookup( int value ) const;
2922 };
2923 } // namespace Detail
2924
2925 class IMutableEnumValuesRegistry {
2926 public:
2927 virtual ~IMutableEnumValuesRegistry(); // = default;
2928
2929 virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
2930
2931 template<typename E>
2932 Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
2933 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
2934 std::vector<int> intValues;
2935 intValues.reserve( values.size() );
2936 for( auto enumValue : values )
2937 intValues.push_back( static_cast<int>( enumValue ) );
2938 return registerEnum( enumName, allEnums, intValues );
2939 }
2940 };
2941
2942 } // Catch
2943
2944 #endif // CATCH_INTERFACES_ENUM_VALUES_REGISTRY_HPP_INCLUDED
2945
2946 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2947 #include <string_view>
2948 #endif
2949
2950 #ifdef _MSC_VER
2951 #pragma warning(push)
2952 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
2953 #endif
2954
2955 // We need a dummy global operator<< so we can bring it into Catch namespace later
2956 struct Catch_global_namespace_dummy{};
2957 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
2958
2959 namespace Catch {
2960 // Bring in global namespace operator<< for ADL lookup in
2961 // `IsStreamInsertable` below.
2962 using ::operator<<;
2963
2964 namespace Detail {
2965
2966 inline std::size_t catch_strnlen(const char *str, std::size_t n) {
2967 auto ret = std::char_traits<char>::find(str, n, '\0');
2968 if (ret != nullptr) {
2969 return static_cast<std::size_t>(ret - str);
2970 }
2971 return n;
2972 }
2973
2974 constexpr StringRef unprintableString = "{?}"_sr;
2975
2976 //! Encases `string in quotes, and optionally escapes invisibles
2977 std::string convertIntoString( StringRef string, bool escapeInvisibles );
2978
2979 //! Encases `string` in quotes, and escapes invisibles if user requested
2980 //! it via CLI
2981 std::string convertIntoString( StringRef string );
2982
2983 std::string rawMemoryToString( const void *object, std::size_t size );
2984
2985 template<typename T>
2986 std::string rawMemoryToString( const T& object ) {
2987 return rawMemoryToString( &object, sizeof(object) );
2988 }
2989
2990 template<typename T>
2991 class IsStreamInsertable {
2992 template<typename Stream, typename U>
2993 static auto test(int)
2994 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
2995
2996 template<typename, typename>
2997 static auto test(...)->std::false_type;
2998
2999 public:
3000 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
3001 };
3002
3003 template<typename E>
3004 std::string convertUnknownEnumToString( E e );
3005
3006 template<typename T>
3007 std::enable_if_t<
3008 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
3009 std::string> convertUnstreamable( T const& ) {
3010 return std::string(Detail::unprintableString);
3011 }
3012 template<typename T>
3013 std::enable_if_t<
3014 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
3015 std::string> convertUnstreamable(T const& ex) {
3016 return ex.what();
3017 }
3018
3019
3020 template<typename T>
3021 std::enable_if_t<
3022 std::is_enum<T>::value,
3023 std::string> convertUnstreamable( T const& value ) {
3024 return convertUnknownEnumToString( value );
3025 }
3026
3027 #if defined(_MANAGED)
3028 //! Convert a CLR string to a utf8 std::string
3029 template<typename T>
3030 std::string clrReferenceToString( T^ ref ) {
3031 if (ref == nullptr)
3032 return std::string("null");
3033 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
3034 cli::pin_ptr<System::Byte> p = &bytes[0];
3035 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
3036 }
3037 #endif
3038
3039 } // namespace Detail
3040
3041
3042 // If we decide for C++14, change these to enable_if_ts
3043 template <typename T, typename = void>
3044 struct StringMaker {
3045 template <typename Fake = T>
3046 static
3047 std::enable_if_t<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>
3048 convert(const Fake& value) {
3049 ReusableStringStream rss;
3050 // NB: call using the function-like syntax to avoid ambiguity with
3051 // user-defined templated operator<< under clang.
3052 rss.operator<<(value);
3053 return rss.str();
3054 }
3055
3056 template <typename Fake = T>
3057 static
3058 std::enable_if_t<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>
3059 convert( const Fake& value ) {
3060 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
3061 return Detail::convertUnstreamable(value);
3062 #else
3063 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
3064 #endif
3065 }
3066 };
3067
3068 namespace Detail {
3069
3070 // This function dispatches all stringification requests inside of Catch.
3071 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
3072 template <typename T>
3073 std::string stringify(const T& e) {
3074 return ::Catch::StringMaker<std::remove_cv_t<std::remove_reference_t<T>>>::convert(e);
3075 }
3076
3077 template<typename E>
3078 std::string convertUnknownEnumToString( E e ) {
3079 return ::Catch::Detail::stringify(static_cast<std::underlying_type_t<E>>(e));
3080 }
3081
3082 #if defined(_MANAGED)
3083 template <typename T>
3084 std::string stringify( T^ e ) {
3085 return ::Catch::StringMaker<T^>::convert(e);
3086 }
3087 #endif
3088
3089 } // namespace Detail
3090
3091 // Some predefined specializations
3092
3093 template<>
3094 struct StringMaker<std::string> {
3095 static std::string convert(const std::string& str);
3096 };
3097
3098 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
3099 template<>
3100 struct StringMaker<std::string_view> {
3101 static std::string convert(std::string_view str);
3102 };
3103 #endif
3104
3105 template<>
3106 struct StringMaker<char const *> {
3107 static std::string convert(char const * str);
3108 };
3109 template<>
3110 struct StringMaker<char *> {
3111 static std::string convert(char * str);
3112 };
3113
3114 #if defined(CATCH_CONFIG_WCHAR)
3115 template<>
3116 struct StringMaker<std::wstring> {
3117 static std::string convert(const std::wstring& wstr);
3118 };
3119
3120 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
3121 template<>
3122 struct StringMaker<std::wstring_view> {
3123 static std::string convert(std::wstring_view str);
3124 };
3125 # endif
3126
3127 template<>
3128 struct StringMaker<wchar_t const *> {
3129 static std::string convert(wchar_t const * str);
3130 };
3131 template<>
3132 struct StringMaker<wchar_t *> {
3133 static std::string convert(wchar_t * str);
3134 };
3135 #endif // CATCH_CONFIG_WCHAR
3136
3137 template<size_t SZ>
3138 struct StringMaker<char[SZ]> {
3139 static std::string convert(char const* str) {
3140 return Detail::convertIntoString(
3141 StringRef( str, Detail::catch_strnlen( str, SZ ) ) );
3142 }
3143 };
3144 template<size_t SZ>
3145 struct StringMaker<signed char[SZ]> {
3146 static std::string convert(signed char const* str) {
3147 auto reinterpreted = reinterpret_cast<char const*>(str);
3148 return Detail::convertIntoString(
3149 StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ)));
3150 }
3151 };
3152 template<size_t SZ>
3153 struct StringMaker<unsigned char[SZ]> {
3154 static std::string convert(unsigned char const* str) {
3155 auto reinterpreted = reinterpret_cast<char const*>(str);
3156 return Detail::convertIntoString(
3157 StringRef(reinterpreted, Detail::catch_strnlen(reinterpreted, SZ)));
3158 }
3159 };
3160
3161 #if defined(CATCH_CONFIG_CPP17_BYTE)
3162 template<>
3163 struct StringMaker<std::byte> {
3164 static std::string convert(std::byte value);
3165 };
3166 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
3167 template<>
3168 struct StringMaker<int> {
3169 static std::string convert(int value);
3170 };
3171 template<>
3172 struct StringMaker<long> {
3173 static std::string convert(long value);
3174 };
3175 template<>
3176 struct StringMaker<long long> {
3177 static std::string convert(long long value);
3178 };
3179 template<>
3180 struct StringMaker<unsigned int> {
3181 static std::string convert(unsigned int value);
3182 };
3183 template<>
3184 struct StringMaker<unsigned long> {
3185 static std::string convert(unsigned long value);
3186 };
3187 template<>
3188 struct StringMaker<unsigned long long> {
3189 static std::string convert(unsigned long long value);
3190 };
3191
3192 template<>
3193 struct StringMaker<bool> {
3194 static std::string convert(bool b) {
3195 using namespace std::string_literals;
3196 return b ? "true"s : "false"s;
3197 }
3198 };
3199
3200 template<>
3201 struct StringMaker<char> {
3202 static std::string convert(char c);
3203 };
3204 template<>
3205 struct StringMaker<signed char> {
3206 static std::string convert(signed char c);
3207 };
3208 template<>
3209 struct StringMaker<unsigned char> {
3210 static std::string convert(unsigned char c);
3211 };
3212
3213 template<>
3214 struct StringMaker<std::nullptr_t> {
3215 static std::string convert(std::nullptr_t) {
3216 using namespace std::string_literals;
3217 return "nullptr"s;
3218 }
3219 };
3220
3221 template<>
3222 struct StringMaker<float> {
3223 static std::string convert(float value);
3224 CATCH_EXPORT static int precision;
3225 };
3226
3227 template<>
3228 struct StringMaker<double> {
3229 static std::string convert(double value);
3230 CATCH_EXPORT static int precision;
3231 };
3232
3233 template <typename T>
3234 struct StringMaker<T*> {
3235 template <typename U>
3236 static std::string convert(U* p) {
3237 if (p) {
3238 return ::Catch::Detail::rawMemoryToString(p);
3239 } else {
3240 return "nullptr";
3241 }
3242 }
3243 };
3244
3245 template <typename R, typename C>
3246 struct StringMaker<R C::*> {
3247 static std::string convert(R C::* p) {
3248 if (p) {
3249 return ::Catch::Detail::rawMemoryToString(p);
3250 } else {
3251 return "nullptr";
3252 }
3253 }
3254 };
3255
3256 #if defined(_MANAGED)
3257 template <typename T>
3258 struct StringMaker<T^> {
3259 static std::string convert( T^ ref ) {
3260 return ::Catch::Detail::clrReferenceToString(ref);
3261 }
3262 };
3263 #endif
3264
3265 namespace Detail {
3266 template<typename InputIterator, typename Sentinel = InputIterator>
3267 std::string rangeToString(InputIterator first, Sentinel last) {
3268 ReusableStringStream rss;
3269 rss << "{ ";
3270 if (first != last) {
3271 rss << ::Catch::Detail::stringify(*first);
3272 for (++first; first != last; ++first)
3273 rss << ", " << ::Catch::Detail::stringify(*first);
3274 }
3275 rss << " }";
3276 return rss.str();
3277 }
3278 }
3279
3280 } // namespace Catch
3281
3282 //////////////////////////////////////////////////////
3283 // Separate std-lib types stringification, so it can be selectively enabled
3284 // This means that we do not bring in their headers
3285
3286 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
3287 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
3288 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
3289 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
3290 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
3291 #endif
3292
3293 // Separate std::pair specialization
3294 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
3295 #include <utility>
3296 namespace Catch {
3297 template<typename T1, typename T2>
3298 struct StringMaker<std::pair<T1, T2> > {
3299 static std::string convert(const std::pair<T1, T2>& pair) {
3300 ReusableStringStream rss;
3301 rss << "{ "
3302 << ::Catch::Detail::stringify(pair.first)
3303 << ", "
3304 << ::Catch::Detail::stringify(pair.second)
3305 << " }";
3306 return rss.str();
3307 }
3308 };
3309 }
3310 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
3311
3312 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
3313 #include <optional>
3314 namespace Catch {
3315 template<typename T>
3316 struct StringMaker<std::optional<T> > {
3317 static std::string convert(const std::optional<T>& optional) {
3318 if (optional.has_value()) {
3319 return ::Catch::Detail::stringify(*optional);
3320 } else {
3321 return "{ }";
3322 }
3323 }
3324 };
3325 }
3326 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
3327
3328 // Separate std::tuple specialization
3329 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
3330 #include <tuple>
3331 namespace Catch {
3332 namespace Detail {
3333 template<
3334 typename Tuple,
3335 std::size_t N = 0,
3336 bool = (N < std::tuple_size<Tuple>::value)
3337 >
3338 struct TupleElementPrinter {
3339 static void print(const Tuple& tuple, std::ostream& os) {
3340 os << (N ? ", " : " ")
3341 << ::Catch::Detail::stringify(std::get<N>(tuple));
3342 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
3343 }
3344 };
3345
3346 template<
3347 typename Tuple,
3348 std::size_t N
3349 >
3350 struct TupleElementPrinter<Tuple, N, false> {
3351 static void print(const Tuple&, std::ostream&) {}
3352 };
3353
3354 }
3355
3356
3357 template<typename ...Types>
3358 struct StringMaker<std::tuple<Types...>> {
3359 static std::string convert(const std::tuple<Types...>& tuple) {
3360 ReusableStringStream rss;
3361 rss << '{';
3362 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
3363 rss << " }";
3364 return rss.str();
3365 }
3366 };
3367 }
3368 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
3369
3370 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
3371 #include <variant>
3372 namespace Catch {
3373 template<>
3374 struct StringMaker<std::monostate> {
3375 static std::string convert(const std::monostate&) {
3376 return "{ }";
3377 }
3378 };
3379
3380 template<typename... Elements>
3381 struct StringMaker<std::variant<Elements...>> {
3382 static std::string convert(const std::variant<Elements...>& variant) {
3383 if (variant.valueless_by_exception()) {
3384 return "{valueless variant}";
3385 } else {
3386 return std::visit(
3387 [](const auto& value) {
3388 return ::Catch::Detail::stringify(value);
3389 },
3390 variant
3391 );
3392 }
3393 }
3394 };
3395 }
3396 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
3397
3398 namespace Catch {
3399 // Import begin/ end from std here
3400 using std::begin;
3401 using std::end;
3402
3403 namespace Detail {
3404 template <typename T, typename = void>
3405 struct is_range_impl : std::false_type {};
3406
3407 template <typename T>
3408 struct is_range_impl<T, void_t<decltype(begin(std::declval<T>()))>> : std::true_type {};
3409 } // namespace Detail
3410
3411 template <typename T>
3412 struct is_range : Detail::is_range_impl<T> {};
3413
3414 #if defined(_MANAGED) // Managed types are never ranges
3415 template <typename T>
3416 struct is_range<T^> {
3417 static const bool value = false;
3418 };
3419 #endif
3420
3421 template<typename Range>
3422 std::string rangeToString( Range const& range ) {
3423 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
3424 }
3425
3426 // Handle vector<bool> specially
3427 template<typename Allocator>
3428 std::string rangeToString( std::vector<bool, Allocator> const& v ) {
3429 ReusableStringStream rss;
3430 rss << "{ ";
3431 bool first = true;
3432 for( bool b : v ) {
3433 if( first )
3434 first = false;
3435 else
3436 rss << ", ";
3437 rss << ::Catch::Detail::stringify( b );
3438 }
3439 rss << " }";
3440 return rss.str();
3441 }
3442
3443 template<typename R>
3444 struct StringMaker<R, std::enable_if_t<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>> {
3445 static std::string convert( R const& range ) {
3446 return rangeToString( range );
3447 }
3448 };
3449
3450 template <typename T, size_t SZ>
3451 struct StringMaker<T[SZ]> {
3452 static std::string convert(T const(&arr)[SZ]) {
3453 return rangeToString(arr);
3454 }
3455 };
3456
3457
3458 } // namespace Catch
3459
3460 // Separate std::chrono::duration specialization
3461 #include <ctime>
3462 #include <ratio>
3463 #include <chrono>
3464
3465
3466 namespace Catch {
3467
3468 template <class Ratio>
3469 struct ratio_string {
3470 static std::string symbol() {
3471 Catch::ReusableStringStream rss;
3472 rss << '[' << Ratio::num << '/'
3473 << Ratio::den << ']';
3474 return rss.str();
3475 }
3476 };
3477
3478 template <>
3479 struct ratio_string<std::atto> {
3480 static char symbol() { return 'a'; }
3481 };
3482 template <>
3483 struct ratio_string<std::femto> {
3484 static char symbol() { return 'f'; }
3485 };
3486 template <>
3487 struct ratio_string<std::pico> {
3488 static char symbol() { return 'p'; }
3489 };
3490 template <>
3491 struct ratio_string<std::nano> {
3492 static char symbol() { return 'n'; }
3493 };
3494 template <>
3495 struct ratio_string<std::micro> {
3496 static char symbol() { return 'u'; }
3497 };
3498 template <>
3499 struct ratio_string<std::milli> {
3500 static char symbol() { return 'm'; }
3501 };
3502
3503 ////////////
3504 // std::chrono::duration specializations
3505 template<typename Value, typename Ratio>
3506 struct StringMaker<std::chrono::duration<Value, Ratio>> {
3507 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
3508 ReusableStringStream rss;
3509 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
3510 return rss.str();
3511 }
3512 };
3513 template<typename Value>
3514 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
3515 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
3516 ReusableStringStream rss;
3517 rss << duration.count() << " s";
3518 return rss.str();
3519 }
3520 };
3521 template<typename Value>
3522 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
3523 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
3524 ReusableStringStream rss;
3525 rss << duration.count() << " m";
3526 return rss.str();
3527 }
3528 };
3529 template<typename Value>
3530 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
3531 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
3532 ReusableStringStream rss;
3533 rss << duration.count() << " h";
3534 return rss.str();
3535 }
3536 };
3537
3538 ////////////
3539 // std::chrono::time_point specialization
3540 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
3541 template<typename Clock, typename Duration>
3542 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
3543 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
3544 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
3545 }
3546 };
3547 // std::chrono::time_point<system_clock> specialization
3548 template<typename Duration>
3549 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
3550 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
3551 auto converted = std::chrono::system_clock::to_time_t(time_point);
3552
3553 #ifdef _MSC_VER
3554 std::tm timeInfo = {};
3555 gmtime_s(&timeInfo, &converted);
3556 #else
3557 std::tm* timeInfo = std::gmtime(&converted);
3558 #endif
3559
3560 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
3561 char timeStamp[timeStampSize];
3562 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
3563
3564 #ifdef _MSC_VER
3565 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
3566 #else
3567 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
3568 #endif
3569 return std::string(timeStamp, timeStampSize - 1);
3570 }
3571 };
3572 }
3573
3574
3575 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
3576 namespace Catch { \
3577 template<> struct StringMaker<enumName> { \
3578 static std::string convert( enumName value ) { \
3579 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
3580 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
3581 } \
3582 }; \
3583 }
3584
3585 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
3586
3587 #ifdef _MSC_VER
3588 #pragma warning(pop)
3589 #endif
3590
3591 #endif // CATCH_TOSTRING_HPP_INCLUDED
3592
3593 #include <type_traits>
3594
3595 namespace Catch {
3596
3597 class Approx {
3598 private:
3599 bool equalityComparisonImpl(double other) const;
3600 // Sets and validates the new margin (margin >= 0)
3601 void setMargin(double margin);
3602 // Sets and validates the new epsilon (0 < epsilon < 1)
3603 void setEpsilon(double epsilon);
3604
3605 public:
3606 explicit Approx ( double value );
3607
3608 static Approx custom();
3609
3610 Approx operator-() const;
3611
3612 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3613 Approx operator()( T const& value ) const {
3614 Approx approx( static_cast<double>(value) );
3615 approx.m_epsilon = m_epsilon;
3616 approx.m_margin = m_margin;
3617 approx.m_scale = m_scale;
3618 return approx;
3619 }
3620
3621 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3622 explicit Approx( T const& value ): Approx(static_cast<double>(value))
3623 {}
3624
3625
3626 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3627 friend bool operator == ( const T& lhs, Approx const& rhs ) {
3628 auto lhs_v = static_cast<double>(lhs);
3629 return rhs.equalityComparisonImpl(lhs_v);
3630 }
3631
3632 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3633 friend bool operator == ( Approx const& lhs, const T& rhs ) {
3634 return operator==( rhs, lhs );
3635 }
3636
3637 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3638 friend bool operator != ( T const& lhs, Approx const& rhs ) {
3639 return !operator==( lhs, rhs );
3640 }
3641
3642 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3643 friend bool operator != ( Approx const& lhs, T const& rhs ) {
3644 return !operator==( rhs, lhs );
3645 }
3646
3647 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3648 friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3649 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3650 }
3651
3652 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3653 friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3654 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3655 }
3656
3657 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3658 friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3659 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3660 }
3661
3662 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3663 friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3664 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3665 }
3666
3667 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3668 Approx& epsilon( T const& newEpsilon ) {
3669 const auto epsilonAsDouble = static_cast<double>(newEpsilon);
3670 setEpsilon(epsilonAsDouble);
3671 return *this;
3672 }
3673
3674 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3675 Approx& margin( T const& newMargin ) {
3676 const auto marginAsDouble = static_cast<double>(newMargin);
3677 setMargin(marginAsDouble);
3678 return *this;
3679 }
3680
3681 template <typename T, typename = std::enable_if_t<std::is_constructible<double, T>::value>>
3682 Approx& scale( T const& newScale ) {
3683 m_scale = static_cast<double>(newScale);
3684 return *this;
3685 }
3686
3687 std::string toString() const;
3688
3689 private:
3690 double m_epsilon;
3691 double m_margin;
3692 double m_scale;
3693 double m_value;
3694 };
3695
3696 namespace literals {
3697 Approx operator ""_a(long double val);
3698 Approx operator ""_a(unsigned long long val);
3699 } // end namespace literals
3700
3701 template<>
3702 struct StringMaker<Catch::Approx> {
3703 static std::string convert(Catch::Approx const& value);
3704 };
3705
3706 } // end namespace Catch
3707
3708 #endif // CATCH_APPROX_HPP_INCLUDED
3709
3710
3711 #ifndef CATCH_CONFIG_HPP_INCLUDED
3712 #define CATCH_CONFIG_HPP_INCLUDED
3713
3714
3715
3716 #ifndef CATCH_TEST_SPEC_HPP_INCLUDED
3717 #define CATCH_TEST_SPEC_HPP_INCLUDED
3718
3719 #ifdef __clang__
3720 #pragma clang diagnostic push
3721 #pragma clang diagnostic ignored "-Wpadded"
3722 #endif
3723
3724
3725
3726 #ifndef CATCH_WILDCARD_PATTERN_HPP_INCLUDED
3727 #define CATCH_WILDCARD_PATTERN_HPP_INCLUDED
3728
3729
3730
3731 #ifndef CATCH_CASE_SENSITIVE_HPP_INCLUDED
3732 #define CATCH_CASE_SENSITIVE_HPP_INCLUDED
3733
3734 namespace Catch {
3735
3736 enum class CaseSensitive { Yes, No };
3737
3738 } // namespace Catch
3739
3740 #endif // CATCH_CASE_SENSITIVE_HPP_INCLUDED
3741
3742 #include <string>
3743
3744 namespace Catch
3745 {
3746 class WildcardPattern {
3747 enum WildcardPosition {
3748 NoWildcard = 0,
3749 WildcardAtStart = 1,
3750 WildcardAtEnd = 2,
3751 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
3752 };
3753
3754 public:
3755
3756 WildcardPattern( std::string const& pattern, CaseSensitive caseSensitivity );
3757 bool matches( std::string const& str ) const;
3758
3759 private:
3760 std::string normaliseString( std::string const& str ) const;
3761 CaseSensitive m_caseSensitivity;
3762 WildcardPosition m_wildcard = NoWildcard;
3763 std::string m_pattern;
3764 };
3765 }
3766
3767 #endif // CATCH_WILDCARD_PATTERN_HPP_INCLUDED
3768
3769 #include <string>
3770 #include <vector>
3771
3772 namespace Catch {
3773
3774 class IConfig;
3775 struct TestCaseInfo;
3776 class TestCaseHandle;
3777
3778 class TestSpec {
3779
3780 class Pattern {
3781 public:
3782 explicit Pattern( std::string const& name );
3783 virtual ~Pattern();
3784 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
3785 std::string const& name() const;
3786 private:
3787 std::string const m_name;
3788 };
3789
3790 class NamePattern : public Pattern {
3791 public:
3792 explicit NamePattern( std::string const& name, std::string const& filterString );
3793 bool matches( TestCaseInfo const& testCase ) const override;
3794 private:
3795 WildcardPattern m_wildcardPattern;
3796 };
3797
3798 class TagPattern : public Pattern {
3799 public:
3800 explicit TagPattern( std::string const& tag, std::string const& filterString );
3801 bool matches( TestCaseInfo const& testCase ) const override;
3802 private:
3803 std::string m_tag;
3804 };
3805
3806 struct Filter {
3807 std::vector<Detail::unique_ptr<Pattern>> m_required;
3808 std::vector<Detail::unique_ptr<Pattern>> m_forbidden;
3809
3810 bool matches( TestCaseInfo const& testCase ) const;
3811 std::string name() const;
3812 };
3813
3814 public:
3815 struct FilterMatch {
3816 std::string name;
3817 std::vector<TestCaseHandle const*> tests;
3818 };
3819 using Matches = std::vector<FilterMatch>;
3820 using vectorStrings = std::vector<std::string>;
3821
3822 bool hasFilters() const;
3823 bool matches( TestCaseInfo const& testCase ) const;
3824 Matches matchesByFilter( std::vector<TestCaseHandle> const& testCases, IConfig const& config ) const;
3825 const vectorStrings & getInvalidSpecs() const;
3826
3827 private:
3828 std::vector<Filter> m_filters;
3829 std::vector<std::string> m_invalidSpecs;
3830 friend class TestSpecParser;
3831 };
3832 }
3833
3834 #ifdef __clang__
3835 #pragma clang diagnostic pop
3836 #endif
3837
3838 #endif // CATCH_TEST_SPEC_HPP_INCLUDED
3839
3840
3841 #ifndef CATCH_OPTIONAL_HPP_INCLUDED
3842 #define CATCH_OPTIONAL_HPP_INCLUDED
3843
3844 #include <cassert>
3845
3846 namespace Catch {
3847
3848 // An optional type
3849 template<typename T>
3850 class Optional {
3851 public:
3852 Optional() : nullableValue( nullptr ) {}
3853 Optional( T const& _value )
3854 : nullableValue( new( storage ) T( _value ) )
3855 {}
3856 Optional( Optional const& _other )
3857 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
3858 {}
3859
3860 ~Optional() {
3861 reset();
3862 }
3863
3864 Optional& operator= ( Optional const& _other ) {
3865 if( &_other != this ) {
3866 reset();
3867 if( _other )
3868 nullableValue = new( storage ) T( *_other );
3869 }
3870 return *this;
3871 }
3872 Optional& operator = ( T const& _value ) {
3873 reset();
3874 nullableValue = new( storage ) T( _value );
3875 return *this;
3876 }
3877
3878 void reset() {
3879 if( nullableValue )
3880 nullableValue->~T();
3881 nullableValue = nullptr;
3882 }
3883
3884 T& operator*() {
3885 assert(nullableValue);
3886 return *nullableValue;
3887 }
3888 T const& operator*() const {
3889 assert(nullableValue);
3890 return *nullableValue;
3891 }
3892 T* operator->() {
3893 assert(nullableValue);
3894 return nullableValue;
3895 }
3896 const T* operator->() const {
3897 assert(nullableValue);
3898 return nullableValue;
3899 }
3900
3901 T valueOr( T const& defaultValue ) const {
3902 return nullableValue ? *nullableValue : defaultValue;
3903 }
3904
3905 bool some() const { return nullableValue != nullptr; }
3906 bool none() const { return nullableValue == nullptr; }
3907
3908 bool operator !() const { return nullableValue == nullptr; }
3909 explicit operator bool() const {
3910 return some();
3911 }
3912
3913 friend bool operator==(Optional const& a, Optional const& b) {
3914 if (a.none() && b.none()) {
3915 return true;
3916 } else if (a.some() && b.some()) {
3917 return *a == *b;
3918 } else {
3919 return false;
3920 }
3921 }
3922 friend bool operator!=(Optional const& a, Optional const& b) {
3923 return !( a == b );
3924 }
3925
3926 private:
3927 T *nullableValue;
3928 alignas(alignof(T)) char storage[sizeof(T)];
3929 };
3930
3931 } // end namespace Catch
3932
3933 #endif // CATCH_OPTIONAL_HPP_INCLUDED
3934
3935
3936 #ifndef CATCH_RANDOM_SEED_GENERATION_HPP_INCLUDED
3937 #define CATCH_RANDOM_SEED_GENERATION_HPP_INCLUDED
3938
3939 #include <cstdint>
3940
3941 namespace Catch {
3942
3943 enum class GenerateFrom {
3944 Time,
3945 RandomDevice,
3946 //! Currently equivalent to RandomDevice, but can change at any point
3947 Default
3948 };
3949
3950 std::uint32_t generateRandomSeed(GenerateFrom from);
3951
3952 } // end namespace Catch
3953
3954 #endif // CATCH_RANDOM_SEED_GENERATION_HPP_INCLUDED
3955
3956
3957 #ifndef CATCH_REPORTER_SPEC_PARSER_HPP_INCLUDED
3958 #define CATCH_REPORTER_SPEC_PARSER_HPP_INCLUDED
3959
3960
3961
3962 #ifndef CATCH_CONSOLE_COLOUR_HPP_INCLUDED
3963 #define CATCH_CONSOLE_COLOUR_HPP_INCLUDED
3964
3965
3966 #include <iosfwd>
3967 #include <cstdint>
3968
3969 namespace Catch {
3970
3971 enum class ColourMode : std::uint8_t;
3972 class IStream;
3973
3974 struct Colour {
3975 enum Code {
3976 None = 0,
3977
3978 White,
3979 Red,
3980 Green,
3981 Blue,
3982 Cyan,
3983 Yellow,
3984 Grey,
3985
3986 Bright = 0x10,
3987
3988 BrightRed = Bright | Red,
3989 BrightGreen = Bright | Green,
3990 LightGrey = Bright | Grey,
3991 BrightWhite = Bright | White,
3992 BrightYellow = Bright | Yellow,
3993
3994 // By intention
3995 FileName = LightGrey,
3996 Warning = BrightYellow,
3997 ResultError = BrightRed,
3998 ResultSuccess = BrightGreen,
3999 ResultExpectedFailure = Warning,
4000
4001 Error = BrightRed,
4002 Success = Green,
4003
4004 OriginalExpression = Cyan,
4005 ReconstructedExpression = BrightYellow,
4006
4007 SecondaryText = LightGrey,
4008 Headers = White
4009 };
4010 };
4011
4012 class ColourImpl {
4013 protected:
4014 //! The associated stream of this ColourImpl instance
4015 IStream* m_stream;
4016 public:
4017 ColourImpl( IStream* stream ): m_stream( stream ) {}
4018
4019 //! RAII wrapper around writing specific colour of text using specific
4020 //! colour impl into a stream.
4021 class ColourGuard {
4022 ColourImpl const* m_colourImpl;
4023 Colour::Code m_code;
4024 bool m_engaged = false;
4025
4026 public:
4027 //! Does **not** engage the guard/start the colour
4028 ColourGuard( Colour::Code code,
4029 ColourImpl const* colour );
4030
4031 ColourGuard( ColourGuard const& rhs ) = delete;
4032 ColourGuard& operator=( ColourGuard const& rhs ) = delete;
4033
4034 ColourGuard( ColourGuard&& rhs ) noexcept;
4035 ColourGuard& operator=( ColourGuard&& rhs ) noexcept;
4036
4037 //! Removes colour _if_ the guard was engaged
4038 ~ColourGuard();
4039
4040 /**
4041 * Explicitly engages colour for given stream.
4042 *
4043 * The API based on operator<< should be preferred.
4044 */
4045 ColourGuard& engage( std::ostream& stream ) &;
4046 /**
4047 * Explicitly engages colour for given stream.
4048 *
4049 * The API based on operator<< should be preferred.
4050 */
4051 ColourGuard&& engage( std::ostream& stream ) &&;
4052
4053 private:
4054 //! Engages the guard and starts using colour
4055 friend std::ostream& operator<<( std::ostream& lhs,
4056 ColourGuard& guard ) {
4057 guard.engageImpl( lhs );
4058 return lhs;
4059 }
4060 //! Engages the guard and starts using colour
4061 friend std::ostream& operator<<( std::ostream& lhs,
4062 ColourGuard&& guard) {
4063 guard.engageImpl( lhs );
4064 return lhs;
4065 }
4066
4067 void engageImpl( std::ostream& stream );
4068
4069 };
4070
4071 virtual ~ColourImpl(); // = default
4072 /**
4073 * Creates a guard object for given colour and this colour impl
4074 *
4075 * **Important:**
4076 * the guard starts disengaged, and has to be engaged explicitly.
4077 */
4078 ColourGuard guardColour( Colour::Code colourCode );
4079
4080 private:
4081 virtual void use( Colour::Code colourCode ) const = 0;
4082 };
4083
4084 //! Provides ColourImpl based on global config and target compilation platform
4085 Detail::unique_ptr<ColourImpl> makeColourImpl( ColourMode colourSelection,
4086 IStream* stream );
4087
4088 //! Checks if specific colour impl has been compiled into the binary
4089 bool isColourImplAvailable( ColourMode colourSelection );
4090
4091 } // end namespace Catch
4092
4093 #endif // CATCH_CONSOLE_COLOUR_HPP_INCLUDED
4094
4095 #include <map>
4096 #include <string>
4097 #include <vector>
4098
4099 namespace Catch {
4100
4101 enum class ColourMode : std::uint8_t;
4102
4103 namespace Detail {
4104 //! Splits the reporter spec into reporter name and kv-pair options
4105 std::vector<std::string> splitReporterSpec( StringRef reporterSpec );
4106
4107 Optional<ColourMode> stringToColourMode( StringRef colourMode );
4108 }
4109
4110 /**
4111 * Structured reporter spec that a reporter can be created from
4112 *
4113 * Parsing has been validated, but semantics have not. This means e.g.
4114 * that the colour mode is known to Catch2, but it might not be
4115 * compiled into the binary, and the output filename might not be
4116 * openable.
4117 */
4118 class ReporterSpec {
4119 std::string m_name;
4120 Optional<std::string> m_outputFileName;
4121 Optional<ColourMode> m_colourMode;
4122 std::map<std::string, std::string> m_customOptions;
4123
4124 friend bool operator==( ReporterSpec const& lhs,
4125 ReporterSpec const& rhs );
4126 friend bool operator!=( ReporterSpec const& lhs,
4127 ReporterSpec const& rhs ) {
4128 return !( lhs == rhs );
4129 }
4130
4131 public:
4132 ReporterSpec(
4133 std::string name,
4134 Optional<std::string> outputFileName,
4135 Optional<ColourMode> colourMode,
4136 std::map<std::string, std::string> customOptions );
4137
4138 std::string const& name() const { return m_name; }
4139
4140 Optional<std::string> const& outputFile() const {
4141 return m_outputFileName;
4142 }
4143
4144 Optional<ColourMode> const& colourMode() const { return m_colourMode; }
4145
4146 std::map<std::string, std::string> const& customOptions() const {
4147 return m_customOptions;
4148 }
4149 };
4150
4151 /**
4152 * Parses provided reporter spec string into
4153 *
4154 * Returns empty optional on errors, e.g.
4155 * * field that is not first and not a key+value pair
4156 * * duplicated keys in kv pair
4157 * * unknown catch reporter option
4158 * * empty key/value in an custom kv pair
4159 * * ...
4160 */
4161 Optional<ReporterSpec> parseReporterSpec( StringRef reporterSpec );
4162
4163 }
4164
4165 #endif // CATCH_REPORTER_SPEC_PARSER_HPP_INCLUDED
4166
4167 #include <chrono>
4168 #include <map>
4169 #include <string>
4170 #include <vector>
4171
4172 namespace Catch {
4173
4174 class IStream;
4175
4176 /**
4177 * `ReporterSpec` but with the defaults filled in.
4178 *
4179 * Like `ReporterSpec`, the semantics are unchecked.
4180 */
4181 struct ProcessedReporterSpec {
4182 std::string name;
4183 std::string outputFilename;
4184 ColourMode colourMode;
4185 std::map<std::string, std::string> customOptions;
4186 friend bool operator==( ProcessedReporterSpec const& lhs,
4187 ProcessedReporterSpec const& rhs );
4188 friend bool operator!=( ProcessedReporterSpec const& lhs,
4189 ProcessedReporterSpec const& rhs ) {
4190 return !( lhs == rhs );
4191 }
4192 };
4193
4194 struct ConfigData {
4195
4196 bool listTests = false;
4197 bool listTags = false;
4198 bool listReporters = false;
4199 bool listListeners = false;
4200
4201 bool showSuccessfulTests = false;
4202 bool shouldDebugBreak = false;
4203 bool noThrow = false;
4204 bool showHelp = false;
4205 bool showInvisibles = false;
4206 bool filenamesAsTags = false;
4207 bool libIdentify = false;
4208 bool allowZeroTests = false;
4209
4210 int abortAfter = -1;
4211 uint32_t rngSeed = generateRandomSeed(GenerateFrom::Default);
4212
4213 unsigned int shardCount = 1;
4214 unsigned int shardIndex = 0;
4215
4216 bool skipBenchmarks = false;
4217 bool benchmarkNoAnalysis = false;
4218 unsigned int benchmarkSamples = 100;
4219 double benchmarkConfidenceInterval = 0.95;
4220 unsigned int benchmarkResamples = 100000;
4221 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
4222
4223 Verbosity verbosity = Verbosity::Normal;
4224 WarnAbout::What warnings = WarnAbout::Nothing;
4225 ShowDurations showDurations = ShowDurations::DefaultForReporter;
4226 double minDuration = -1;
4227 TestRunOrder runOrder = TestRunOrder::Declared;
4228 ColourMode defaultColourMode = ColourMode::PlatformDefault;
4229 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
4230
4231 std::string defaultOutputFilename;
4232 std::string name;
4233 std::string processName;
4234 std::vector<ReporterSpec> reporterSpecifications;
4235
4236 std::vector<std::string> testsOrTags;
4237 std::vector<std::string> sectionsToRun;
4238 };
4239
4240
4241 class Config : public IConfig {
4242 public:
4243
4244 Config() = default;
4245 Config( ConfigData const& data );
4246 ~Config() override; // = default in the cpp file
4247
4248 bool listTests() const;
4249 bool listTags() const;
4250 bool listReporters() const;
4251 bool listListeners() const;
4252
4253 std::vector<ReporterSpec> const& getReporterSpecs() const;
4254 std::vector<ProcessedReporterSpec> const&
4255 getProcessedReporterSpecs() const;
4256
4257 std::vector<std::string> const& getTestsOrTags() const override;
4258 std::vector<std::string> const& getSectionsToRun() const override;
4259
4260 TestSpec const& testSpec() const override;
4261 bool hasTestFilters() const override;
4262
4263 bool showHelp() const;
4264
4265 // IConfig interface
4266 bool allowThrows() const override;
4267 StringRef name() const override;
4268 bool includeSuccessfulResults() const override;
4269 bool warnAboutMissingAssertions() const override;
4270 bool warnAboutUnmatchedTestSpecs() const override;
4271 bool zeroTestsCountAsSuccess() const override;
4272 ShowDurations showDurations() const override;
4273 double minDuration() const override;
4274 TestRunOrder runOrder() const override;
4275 uint32_t rngSeed() const override;
4276 unsigned int shardCount() const override;
4277 unsigned int shardIndex() const override;
4278 ColourMode defaultColourMode() const override;
4279 bool shouldDebugBreak() const override;
4280 int abortAfter() const override;
4281 bool showInvisibles() const override;
4282 Verbosity verbosity() const override;
4283 bool skipBenchmarks() const override;
4284 bool benchmarkNoAnalysis() const override;
4285 unsigned int benchmarkSamples() const override;
4286 double benchmarkConfidenceInterval() const override;
4287 unsigned int benchmarkResamples() const override;
4288 std::chrono::milliseconds benchmarkWarmupTime() const override;
4289
4290 private:
4291 ConfigData m_data;
4292 std::vector<ProcessedReporterSpec> m_processedReporterSpecs;
4293 TestSpec m_testSpec;
4294 bool m_hasTestFilters = false;
4295 };
4296 } // end namespace Catch
4297
4298 #endif // CATCH_CONFIG_HPP_INCLUDED
4299
4300
4301 #ifndef CATCH_GET_RANDOM_SEED_HPP_INCLUDED
4302 #define CATCH_GET_RANDOM_SEED_HPP_INCLUDED
4303
4304 #include <cstdint>
4305
4306 namespace Catch {
4307 //! Returns Catch2's current RNG seed.
4308 std::uint32_t getSeed();
4309 }
4310
4311 #endif // CATCH_GET_RANDOM_SEED_HPP_INCLUDED
4312
4313
4314 #ifndef CATCH_MESSAGE_HPP_INCLUDED
4315 #define CATCH_MESSAGE_HPP_INCLUDED
4316
4317
4318
4319 #ifndef CATCH_STREAM_END_STOP_HPP_INCLUDED
4320 #define CATCH_STREAM_END_STOP_HPP_INCLUDED
4321
4322
4323 namespace Catch {
4324
4325 // Use this in variadic streaming macros to allow
4326 // << +StreamEndStop
4327 // as well as
4328 // << stuff +StreamEndStop
4329 struct StreamEndStop {
4330 StringRef operator+() const { return StringRef(); }
4331
4332 template <typename T>
4333 friend T const& operator+( T const& value, StreamEndStop ) {
4334 return value;
4335 }
4336 };
4337
4338 } // namespace Catch
4339
4340 #endif // CATCH_STREAM_END_STOP_HPP_INCLUDED
4341
4342 #include <string>
4343 #include <vector>
4344
4345 namespace Catch {
4346
4347 struct SourceLineInfo;
4348
4349 struct MessageStream {
4350
4351 template<typename T>
4352 MessageStream& operator << ( T const& value ) {
4353 m_stream << value;
4354 return *this;
4355 }
4356
4357 ReusableStringStream m_stream;
4358 };
4359
4360 struct MessageBuilder : MessageStream {
4361 MessageBuilder( StringRef macroName,
4362 SourceLineInfo const& lineInfo,
4363 ResultWas::OfType type ):
4364 m_info(macroName, lineInfo, type) {}
4365
4366
4367 template<typename T>
4368 MessageBuilder& operator << ( T const& value ) {
4369 m_stream << value;
4370 return *this;
4371 }
4372
4373 MessageInfo m_info;
4374 };
4375
4376 class ScopedMessage {
4377 public:
4378 explicit ScopedMessage( MessageBuilder const& builder );
4379 ScopedMessage( ScopedMessage& duplicate ) = delete;
4380 ScopedMessage( ScopedMessage&& old ) noexcept;
4381 ~ScopedMessage();
4382
4383 MessageInfo m_info;
4384 bool m_moved = false;
4385 };
4386
4387 class Capturer {
4388 std::vector<MessageInfo> m_messages;
4389 IResultCapture& m_resultCapture = getResultCapture();
4390 size_t m_captured = 0;
4391 public:
4392 Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
4393
4394 Capturer(Capturer const&) = delete;
4395 Capturer& operator=(Capturer const&) = delete;
4396
4397 ~Capturer();
4398
4399 void captureValue( size_t index, std::string const& value );
4400
4401 template<typename T>
4402 void captureValues( size_t index, T const& value ) {
4403 captureValue( index, Catch::Detail::stringify( value ) );
4404 }
4405
4406 template<typename T, typename... Ts>
4407 void captureValues( size_t index, T const& value, Ts const&... values ) {
4408 captureValue( index, Catch::Detail::stringify(value) );
4409 captureValues( index+1, values... );
4410 }
4411 };
4412
4413 } // end namespace Catch
4414
4415 ///////////////////////////////////////////////////////////////////////////////
4416 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
4417 do { \
4418 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
4419 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
4420 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
4421 } while( false )
4422
4423 ///////////////////////////////////////////////////////////////////////////////
4424 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
4425 Catch::Capturer varName( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
4426 varName.captureValues( 0, __VA_ARGS__ )
4427
4428 ///////////////////////////////////////////////////////////////////////////////
4429 #define INTERNAL_CATCH_INFO( macroName, log ) \
4430 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
4431
4432 ///////////////////////////////////////////////////////////////////////////////
4433 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
4434 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
4435
4436
4437 #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
4438
4439 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
4440 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
4441 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
4442 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__ )
4443
4444 #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE)
4445
4446 #define CATCH_INFO( msg ) (void)(0)
4447 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
4448 #define CATCH_WARN( msg ) (void)(0)
4449 #define CATCH_CAPTURE( ... ) (void)(0)
4450
4451 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
4452
4453 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
4454 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
4455 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
4456 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__ )
4457
4458 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE)
4459
4460 #define INFO( msg ) (void)(0)
4461 #define UNSCOPED_INFO( msg ) (void)(0)
4462 #define WARN( msg ) (void)(0)
4463 #define CAPTURE( ... ) (void)(0)
4464
4465 #endif // end of user facing macro declarations
4466
4467
4468
4469
4470 #endif // CATCH_MESSAGE_HPP_INCLUDED
4471
4472
4473 #ifndef CATCH_SESSION_HPP_INCLUDED
4474 #define CATCH_SESSION_HPP_INCLUDED
4475
4476
4477
4478 #ifndef CATCH_COMMANDLINE_HPP_INCLUDED
4479 #define CATCH_COMMANDLINE_HPP_INCLUDED
4480
4481
4482
4483 #ifndef CATCH_CLARA_HPP_INCLUDED
4484 #define CATCH_CLARA_HPP_INCLUDED
4485
4486 #if defined( __clang__ )
4487 # pragma clang diagnostic push
4488 # pragma clang diagnostic ignored "-Wweak-vtables"
4489 # pragma clang diagnostic ignored "-Wshadow"
4490 # pragma clang diagnostic ignored "-Wdeprecated"
4491 #endif
4492
4493 #if defined( __GNUC__ )
4494 # pragma GCC diagnostic push
4495 # pragma GCC diagnostic ignored "-Wsign-conversion"
4496 #endif
4497
4498 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
4499 # ifdef __has_include
4500 # if __has_include( <optional>) && __cplusplus >= 201703L
4501 # include <optional>
4502 # define CLARA_CONFIG_OPTIONAL_TYPE std::optional
4503 # endif
4504 # endif
4505 #endif
4506
4507
4508 #include <cassert>
4509 #include <memory>
4510 #include <ostream>
4511 #include <sstream>
4512 #include <string>
4513 #include <type_traits>
4514 #include <vector>
4515
4516 namespace Catch {
4517 namespace Clara {
4518
4519 class Args;
4520 class Parser;
4521
4522 // enum of result types from a parse
4523 enum class ParseResultType {
4524 Matched,
4525 NoMatch,
4526 ShortCircuitAll,
4527 ShortCircuitSame
4528 };
4529
4530 struct accept_many_t {};
4531 constexpr accept_many_t accept_many {};
4532
4533 namespace Detail {
4534 struct fake_arg {
4535 template <typename T>
4536 operator T();
4537 };
4538
4539 template <typename F, typename = void>
4540 struct is_unary_function : std::false_type {};
4541
4542 template <typename F>
4543 struct is_unary_function<
4544 F,
4545 Catch::Detail::void_t<decltype(
4546 std::declval<F>()( fake_arg() ) )
4547 >
4548 > : std::true_type {};
4549
4550 // Traits for extracting arg and return type of lambdas (for single
4551 // argument lambdas)
4552 template <typename L>
4553 struct UnaryLambdaTraits
4554 : UnaryLambdaTraits<decltype( &L::operator() )> {};
4555
4556 template <typename ClassT, typename ReturnT, typename... Args>
4557 struct UnaryLambdaTraits<ReturnT ( ClassT::* )( Args... ) const> {
4558 static const bool isValid = false;
4559 };
4560
4561 template <typename ClassT, typename ReturnT, typename ArgT>
4562 struct UnaryLambdaTraits<ReturnT ( ClassT::* )( ArgT ) const> {
4563 static const bool isValid = true;
4564 using ArgType = std::remove_const_t<std::remove_reference_t<ArgT>>;
4565 using ReturnType = ReturnT;
4566 };
4567
4568 class TokenStream;
4569
4570 // Wraps a token coming from a token stream. These may not directly
4571 // correspond to strings as a single string may encode an option +
4572 // its argument if the : or = form is used
4573 enum class TokenType { Option, Argument };
4574 struct Token {
4575 TokenType type;
4576 std::string token;
4577 };
4578
4579 // Abstracts iterators into args as a stream of tokens, with option
4580 // arguments uniformly handled
4581 class TokenStream {
4582 using Iterator = std::vector<std::string>::const_iterator;
4583 Iterator it;
4584 Iterator itEnd;
4585 std::vector<Token> m_tokenBuffer;
4586
4587 void loadBuffer();
4588
4589 public:
4590 explicit TokenStream( Args const& args );
4591 TokenStream( Iterator it, Iterator itEnd );
4592
4593 explicit operator bool() const {
4594 return !m_tokenBuffer.empty() || it != itEnd;
4595 }
4596
4597 size_t count() const {
4598 return m_tokenBuffer.size() + ( itEnd - it );
4599 }
4600
4601 Token operator*() const {
4602 assert( !m_tokenBuffer.empty() );
4603 return m_tokenBuffer.front();
4604 }
4605
4606 Token const* operator->() const {
4607 assert( !m_tokenBuffer.empty() );
4608 return &m_tokenBuffer.front();
4609 }
4610
4611 TokenStream& operator++();
4612 };
4613
4614 //! Denotes type of a parsing result
4615 enum class ResultType {
4616 Ok, ///< No errors
4617 LogicError, ///< Error in user-specified arguments for
4618 ///< construction
4619 RuntimeError ///< Error in parsing inputs
4620 };
4621
4622 class ResultBase {
4623 protected:
4624 ResultBase( ResultType type ): m_type( type ) {}
4625 virtual ~ResultBase(); // = default;
4626
4627
4628 ResultBase(ResultBase const&) = default;
4629 ResultBase& operator=(ResultBase const&) = default;
4630 ResultBase(ResultBase&&) = default;
4631 ResultBase& operator=(ResultBase&&) = default;
4632
4633 virtual void enforceOk() const = 0;
4634
4635 ResultType m_type;
4636 };
4637
4638 template <typename T> class ResultValueBase : public ResultBase {
4639 public:
4640 auto value() const -> T const& {
4641 enforceOk();
4642 return m_value;
4643 }
4644
4645 protected:
4646 ResultValueBase( ResultType type ): ResultBase( type ) {}
4647
4648 ResultValueBase( ResultValueBase const& other ):
4649 ResultBase( other ) {
4650 if ( m_type == ResultType::Ok )
4651 new ( &m_value ) T( other.m_value );
4652 }
4653
4654 ResultValueBase( ResultType, T const& value ): ResultBase( ResultType::Ok ) {
4655 new ( &m_value ) T( value );
4656 }
4657
4658 auto operator=( ResultValueBase const& other )
4659 -> ResultValueBase& {
4660 if ( m_type == ResultType::Ok )
4661 m_value.~T();
4662 ResultBase::operator=( other );
4663 if ( m_type == ResultType::Ok )
4664 new ( &m_value ) T( other.m_value );
4665 return *this;
4666 }
4667
4668 ~ResultValueBase() override {
4669 if ( m_type == ResultType::Ok )
4670 m_value.~T();
4671 }
4672
4673 union {
4674 T m_value;
4675 };
4676 };
4677
4678 template <> class ResultValueBase<void> : public ResultBase {
4679 protected:
4680 using ResultBase::ResultBase;
4681 };
4682
4683 template <typename T = void>
4684 class BasicResult : public ResultValueBase<T> {
4685 public:
4686 template <typename U>
4687 explicit BasicResult( BasicResult<U> const& other ):
4688 ResultValueBase<T>( other.type() ),
4689 m_errorMessage( other.errorMessage() ) {
4690 assert( type() != ResultType::Ok );
4691 }
4692
4693 template <typename U>
4694 static auto ok( U const& value ) -> BasicResult {
4695 return { ResultType::Ok, value };
4696 }
4697 static auto ok() -> BasicResult { return { ResultType::Ok }; }
4698 static auto logicError( std::string&& message )
4699 -> BasicResult {
4700 return { ResultType::LogicError, CATCH_MOVE(message) };
4701 }
4702 static auto runtimeError( std::string&& message )
4703 -> BasicResult {
4704 return { ResultType::RuntimeError, CATCH_MOVE(message) };
4705 }
4706
4707 explicit operator bool() const {
4708 return m_type == ResultType::Ok;
4709 }
4710 auto type() const -> ResultType { return m_type; }
4711 auto errorMessage() const -> std::string const& {
4712 return m_errorMessage;
4713 }
4714
4715 protected:
4716 void enforceOk() const override {
4717
4718 // Errors shouldn't reach this point, but if they do
4719 // the actual error message will be in m_errorMessage
4720 assert( m_type != ResultType::LogicError );
4721 assert( m_type != ResultType::RuntimeError );
4722 if ( m_type != ResultType::Ok )
4723 std::abort();
4724 }
4725
4726 std::string
4727 m_errorMessage; // Only populated if resultType is an error
4728
4729 BasicResult( ResultType type,
4730 std::string&& message ):
4731 ResultValueBase<T>( type ), m_errorMessage( CATCH_MOVE(message) ) {
4732 assert( m_type != ResultType::Ok );
4733 }
4734
4735 using ResultValueBase<T>::ResultValueBase;
4736 using ResultBase::m_type;
4737 };
4738
4739 class ParseState {
4740 public:
4741 ParseState( ParseResultType type,
4742 TokenStream const& remainingTokens );
4743
4744 ParseResultType type() const { return m_type; }
4745 TokenStream const& remainingTokens() const {
4746 return m_remainingTokens;
4747 }
4748
4749 private:
4750 ParseResultType m_type;
4751 TokenStream m_remainingTokens;
4752 };
4753
4754 using Result = BasicResult<void>;
4755 using ParserResult = BasicResult<ParseResultType>;
4756 using InternalParseResult = BasicResult<ParseState>;
4757
4758 struct HelpColumns {
4759 std::string left;
4760 std::string right;
4761 };
4762
4763 template <typename T>
4764 ParserResult convertInto( std::string const& source, T& target ) {
4765 std::stringstream ss( source );
4766 ss >> target;
4767 if ( ss.fail() ) {
4768 return ParserResult::runtimeError(
4769 "Unable to convert '" + source +
4770 "' to destination type" );
4771 } else {
4772 return ParserResult::ok( ParseResultType::Matched );
4773 }
4774 }
4775 ParserResult convertInto( std::string const& source,
4776 std::string& target );
4777 ParserResult convertInto( std::string const& source, bool& target );
4778
4779 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
4780 template <typename T>
4781 auto convertInto( std::string const& source,
4782 CLARA_CONFIG_OPTIONAL_TYPE<T>& target )
4783 -> ParserResult {
4784 T temp;
4785 auto result = convertInto( source, temp );
4786 if ( result )
4787 target = CATCH_MOVE( temp );
4788 return result;
4789 }
4790 #endif // CLARA_CONFIG_OPTIONAL_TYPE
4791
4792 struct BoundRef : Catch::Detail::NonCopyable {
4793 virtual ~BoundRef() = default;
4794 virtual bool isContainer() const;
4795 virtual bool isFlag() const;
4796 };
4797 struct BoundValueRefBase : BoundRef {
4798 virtual auto setValue( std::string const& arg )
4799 -> ParserResult = 0;
4800 };
4801 struct BoundFlagRefBase : BoundRef {
4802 virtual auto setFlag( bool flag ) -> ParserResult = 0;
4803 bool isFlag() const override;
4804 };
4805
4806 template <typename T> struct BoundValueRef : BoundValueRefBase {
4807 T& m_ref;
4808
4809 explicit BoundValueRef( T& ref ): m_ref( ref ) {}
4810
4811 ParserResult setValue( std::string const& arg ) override {
4812 return convertInto( arg, m_ref );
4813 }
4814 };
4815
4816 template <typename T>
4817 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
4818 std::vector<T>& m_ref;
4819
4820 explicit BoundValueRef( std::vector<T>& ref ): m_ref( ref ) {}
4821
4822 auto isContainer() const -> bool override { return true; }
4823
4824 auto setValue( std::string const& arg )
4825 -> ParserResult override {
4826 T temp;
4827 auto result = convertInto( arg, temp );
4828 if ( result )
4829 m_ref.push_back( temp );
4830 return result;
4831 }
4832 };
4833
4834 struct BoundFlagRef : BoundFlagRefBase {
4835 bool& m_ref;
4836
4837 explicit BoundFlagRef( bool& ref ): m_ref( ref ) {}
4838
4839 ParserResult setFlag( bool flag ) override;
4840 };
4841
4842 template <typename ReturnType> struct LambdaInvoker {
4843 static_assert(
4844 std::is_same<ReturnType, ParserResult>::value,
4845 "Lambda must return void or clara::ParserResult" );
4846
4847 template <typename L, typename ArgType>
4848 static auto invoke( L const& lambda, ArgType const& arg )
4849 -> ParserResult {
4850 return lambda( arg );
4851 }
4852 };
4853
4854 template <> struct LambdaInvoker<void> {
4855 template <typename L, typename ArgType>
4856 static auto invoke( L const& lambda, ArgType const& arg )
4857 -> ParserResult {
4858 lambda( arg );
4859 return ParserResult::ok( ParseResultType::Matched );
4860 }
4861 };
4862
4863 template <typename ArgType, typename L>
4864 auto invokeLambda( L const& lambda, std::string const& arg )
4865 -> ParserResult {
4866 ArgType temp{};
4867 auto result = convertInto( arg, temp );
4868 return !result ? result
4869 : LambdaInvoker<typename UnaryLambdaTraits<
4870 L>::ReturnType>::invoke( lambda, temp );
4871 }
4872
4873 template <typename L> struct BoundLambda : BoundValueRefBase {
4874 L m_lambda;
4875
4876 static_assert(
4877 UnaryLambdaTraits<L>::isValid,
4878 "Supplied lambda must take exactly one argument" );
4879 explicit BoundLambda( L const& lambda ): m_lambda( lambda ) {}
4880
4881 auto setValue( std::string const& arg )
4882 -> ParserResult override {
4883 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(
4884 m_lambda, arg );
4885 }
4886 };
4887
4888 template <typename L> struct BoundManyLambda : BoundLambda<L> {
4889 explicit BoundManyLambda( L const& lambda ): BoundLambda<L>( lambda ) {}
4890 bool isContainer() const override { return true; }
4891 };
4892
4893 template <typename L> struct BoundFlagLambda : BoundFlagRefBase {
4894 L m_lambda;
4895
4896 static_assert(
4897 UnaryLambdaTraits<L>::isValid,
4898 "Supplied lambda must take exactly one argument" );
4899 static_assert(
4900 std::is_same<typename UnaryLambdaTraits<L>::ArgType,
4901 bool>::value,
4902 "flags must be boolean" );
4903
4904 explicit BoundFlagLambda( L const& lambda ):
4905 m_lambda( lambda ) {}
4906
4907 auto setFlag( bool flag ) -> ParserResult override {
4908 return LambdaInvoker<typename UnaryLambdaTraits<
4909 L>::ReturnType>::invoke( m_lambda, flag );
4910 }
4911 };
4912
4913 enum class Optionality { Optional, Required };
4914
4915 class ParserBase {
4916 public:
4917 virtual ~ParserBase() = default;
4918 virtual auto validate() const -> Result { return Result::ok(); }
4919 virtual auto parse( std::string const& exeName,
4920 TokenStream const& tokens ) const
4921 -> InternalParseResult = 0;
4922 virtual size_t cardinality() const;
4923
4924 InternalParseResult parse( Args const& args ) const;
4925 };
4926
4927 template <typename DerivedT>
4928 class ComposableParserImpl : public ParserBase {
4929 public:
4930 template <typename T>
4931 auto operator|( T const& other ) const -> Parser;
4932 };
4933
4934 // Common code and state for Args and Opts
4935 template <typename DerivedT>
4936 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
4937 protected:
4938 Optionality m_optionality = Optionality::Optional;
4939 std::shared_ptr<BoundRef> m_ref;
4940 std::string m_hint;
4941 std::string m_description;
4942
4943 explicit ParserRefImpl( std::shared_ptr<BoundRef> const& ref ):
4944 m_ref( ref ) {}
4945
4946 public:
4947 template <typename LambdaT>
4948 ParserRefImpl( accept_many_t,
4949 LambdaT const& ref,
4950 std::string const& hint ):
4951 m_ref( std::make_shared<BoundManyLambda<LambdaT>>( ref ) ),
4952 m_hint( hint ) {}
4953
4954 template <typename T,
4955 typename = typename std::enable_if_t<
4956 !Detail::is_unary_function<T>::value>>
4957 ParserRefImpl( T& ref, std::string const& hint ):
4958 m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
4959 m_hint( hint ) {}
4960
4961 template <typename LambdaT,
4962 typename = typename std::enable_if_t<
4963 Detail::is_unary_function<LambdaT>::value>>
4964 ParserRefImpl( LambdaT const& ref, std::string const& hint ):
4965 m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
4966 m_hint( hint ) {}
4967
4968 auto operator()( std::string const& description ) -> DerivedT& {
4969 m_description = description;
4970 return static_cast<DerivedT&>( *this );
4971 }
4972
4973 auto optional() -> DerivedT& {
4974 m_optionality = Optionality::Optional;
4975 return static_cast<DerivedT&>( *this );
4976 }
4977
4978 auto required() -> DerivedT& {
4979 m_optionality = Optionality::Required;
4980 return static_cast<DerivedT&>( *this );
4981 }
4982
4983 auto isOptional() const -> bool {
4984 return m_optionality == Optionality::Optional;
4985 }
4986
4987 auto cardinality() const -> size_t override {
4988 if ( m_ref->isContainer() )
4989 return 0;
4990 else
4991 return 1;
4992 }
4993
4994 std::string const& hint() const { return m_hint; }
4995 };
4996
4997 } // namespace detail
4998
4999
5000 // A parser for arguments
5001 class Arg : public Detail::ParserRefImpl<Arg> {
5002 public:
5003 using ParserRefImpl::ParserRefImpl;
5004 using ParserBase::parse;
5005
5006 Detail::InternalParseResult
5007 parse(std::string const&,
5008 Detail::TokenStream const& tokens) const override;
5009 };
5010
5011 // A parser for options
5012 class Opt : public Detail::ParserRefImpl<Opt> {
5013 protected:
5014 std::vector<std::string> m_optNames;
5015
5016 public:
5017 template <typename LambdaT>
5018 explicit Opt(LambdaT const& ref) :
5019 ParserRefImpl(
5020 std::make_shared<Detail::BoundFlagLambda<LambdaT>>(ref)) {}
5021
5022 explicit Opt(bool& ref);
5023
5024 template <typename LambdaT,
5025 typename = typename std::enable_if_t<
5026 Detail::is_unary_function<LambdaT>::value>>
5027 Opt( LambdaT const& ref, std::string const& hint ):
5028 ParserRefImpl( ref, hint ) {}
5029
5030 template <typename LambdaT>
5031 Opt( accept_many_t, LambdaT const& ref, std::string const& hint ):
5032 ParserRefImpl( accept_many, ref, hint ) {}
5033
5034 template <typename T,
5035 typename = typename std::enable_if_t<
5036 !Detail::is_unary_function<T>::value>>
5037 Opt( T& ref, std::string const& hint ):
5038 ParserRefImpl( ref, hint ) {}
5039
5040 auto operator[](std::string const& optName) -> Opt& {
5041 m_optNames.push_back(optName);
5042 return *this;
5043 }
5044
5045 std::vector<Detail::HelpColumns> getHelpColumns() const;
5046
5047 bool isMatch(std::string const& optToken) const;
5048
5049 using ParserBase::parse;
5050
5051 Detail::InternalParseResult
5052 parse(std::string const&,
5053 Detail::TokenStream const& tokens) const override;
5054
5055 Detail::Result validate() const override;
5056 };
5057
5058 // Specifies the name of the executable
5059 class ExeName : public Detail::ComposableParserImpl<ExeName> {
5060 std::shared_ptr<std::string> m_name;
5061 std::shared_ptr<Detail::BoundValueRefBase> m_ref;
5062
5063 public:
5064 ExeName();
5065 explicit ExeName(std::string& ref);
5066
5067 template <typename LambdaT>
5068 explicit ExeName(LambdaT const& lambda) : ExeName() {
5069 m_ref = std::make_shared<Detail::BoundLambda<LambdaT>>(lambda);
5070 }
5071
5072 // The exe name is not parsed out of the normal tokens, but is
5073 // handled specially
5074 Detail::InternalParseResult
5075 parse(std::string const&,
5076 Detail::TokenStream const& tokens) const override;
5077
5078 std::string const& name() const { return *m_name; }
5079 Detail::ParserResult set(std::string const& newName);
5080 };
5081
5082
5083 // A Combined parser
5084 class Parser : Detail::ParserBase {
5085 mutable ExeName m_exeName;
5086 std::vector<Opt> m_options;
5087 std::vector<Arg> m_args;
5088
5089 public:
5090
5091 auto operator|=(ExeName const& exeName) -> Parser& {
5092 m_exeName = exeName;
5093 return *this;
5094 }
5095
5096 auto operator|=(Arg const& arg) -> Parser& {
5097 m_args.push_back(arg);
5098 return *this;
5099 }
5100
5101 auto operator|=(Opt const& opt) -> Parser& {
5102 m_options.push_back(opt);
5103 return *this;
5104 }
5105
5106 Parser& operator|=(Parser const& other);
5107
5108 template <typename T>
5109 auto operator|(T const& other) const -> Parser {
5110 return Parser(*this) |= other;
5111 }
5112
5113 std::vector<Detail::HelpColumns> getHelpColumns() const;
5114
5115 void writeToStream(std::ostream& os) const;
5116
5117 friend auto operator<<(std::ostream& os, Parser const& parser)
5118 -> std::ostream& {
5119 parser.writeToStream(os);
5120 return os;
5121 }
5122
5123 Detail::Result validate() const override;
5124
5125 using ParserBase::parse;
5126 Detail::InternalParseResult
5127 parse(std::string const& exeName,
5128 Detail::TokenStream const& tokens) const override;
5129 };
5130
5131 // Transport for raw args (copied from main args, or supplied via
5132 // init list for testing)
5133 class Args {
5134 friend Detail::TokenStream;
5135 std::string m_exeName;
5136 std::vector<std::string> m_args;
5137
5138 public:
5139 Args(int argc, char const* const* argv);
5140 Args(std::initializer_list<std::string> args);
5141
5142 std::string const& exeName() const { return m_exeName; }
5143 };
5144
5145
5146 // Convenience wrapper for option parser that specifies the help option
5147 struct Help : Opt {
5148 Help(bool& showHelpFlag);
5149 };
5150
5151 // Result type for parser operation
5152 using Detail::ParserResult;
5153
5154 namespace Detail {
5155 template <typename DerivedT>
5156 template <typename T>
5157 Parser
5158 ComposableParserImpl<DerivedT>::operator|(T const& other) const {
5159 return Parser() | static_cast<DerivedT const&>(*this) | other;
5160 }
5161 }
5162
5163 } // namespace Clara
5164 } // namespace Catch
5165
5166 #if defined( __clang__ )
5167 # pragma clang diagnostic pop
5168 #endif
5169
5170 #if defined( __GNUC__ )
5171 # pragma GCC diagnostic pop
5172 #endif
5173
5174 #endif // CATCH_CLARA_HPP_INCLUDED
5175
5176 namespace Catch {
5177
5178 struct ConfigData;
5179
5180 Clara::Parser makeCommandLineParser( ConfigData& config );
5181
5182 } // end namespace Catch
5183
5184 #endif // CATCH_COMMANDLINE_HPP_INCLUDED
5185
5186 namespace Catch {
5187
5188 class Session : Detail::NonCopyable {
5189 public:
5190
5191 Session();
5192 ~Session();
5193
5194 void showHelp() const;
5195 void libIdentify();
5196
5197 int applyCommandLine( int argc, char const * const * argv );
5198 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
5199 int applyCommandLine( int argc, wchar_t const * const * argv );
5200 #endif
5201
5202 void useConfigData( ConfigData const& configData );
5203
5204 template<typename CharT>
5205 int run(int argc, CharT const * const argv[]) {
5206 if (m_startupExceptions)
5207 return 1;
5208 int returnCode = applyCommandLine(argc, argv);
5209 if (returnCode == 0)
5210 returnCode = run();
5211 return returnCode;
5212 }
5213
5214 int run();
5215
5216 Clara::Parser const& cli() const;
5217 void cli( Clara::Parser const& newParser );
5218 ConfigData& configData();
5219 Config& config();
5220 private:
5221 int runInternal();
5222
5223 Clara::Parser m_cli;
5224 ConfigData m_configData;
5225 Detail::unique_ptr<Config> m_config;
5226 bool m_startupExceptions = false;
5227 };
5228
5229 } // end namespace Catch
5230
5231 #endif // CATCH_SESSION_HPP_INCLUDED
5232
5233
5234 #ifndef CATCH_TAG_ALIAS_HPP_INCLUDED
5235 #define CATCH_TAG_ALIAS_HPP_INCLUDED
5236
5237
5238 #include <string>
5239
5240 namespace Catch {
5241
5242 struct TagAlias {
5243 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo):
5244 tag(_tag),
5245 lineInfo(_lineInfo)
5246 {}
5247
5248 std::string tag;
5249 SourceLineInfo lineInfo;
5250 };
5251
5252 } // end namespace Catch
5253
5254 #endif // CATCH_TAG_ALIAS_HPP_INCLUDED
5255
5256
5257 #ifndef CATCH_TAG_ALIAS_AUTOREGISTRAR_HPP_INCLUDED
5258 #define CATCH_TAG_ALIAS_AUTOREGISTRAR_HPP_INCLUDED
5259
5260
5261 namespace Catch {
5262
5263 struct RegistrarForTagAliases {
5264 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
5265 };
5266
5267 } // end namespace Catch
5268
5269 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
5270 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5271 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5272 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
5273 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
5274
5275 #endif // CATCH_TAG_ALIAS_AUTOREGISTRAR_HPP_INCLUDED
5276
5277
5278 #ifndef CATCH_TEMPLATE_TEST_MACROS_HPP_INCLUDED
5279 #define CATCH_TEMPLATE_TEST_MACROS_HPP_INCLUDED
5280
5281 // We need this suppression to leak, because it took until GCC 10
5282 // for the front end to handle local suppression via _Pragma properly
5283 // inside templates (so `TEMPLATE_TEST_CASE` and co).
5284 // **THIS IS DIFFERENT FOR STANDARD TESTS, WHERE GCC 9 IS SUFFICIENT**
5285 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && __GNUC__ < 10
5286 #pragma GCC diagnostic ignored "-Wparentheses"
5287 #endif
5288
5289
5290
5291
5292 #ifndef CATCH_TEST_MACROS_HPP_INCLUDED
5293 #define CATCH_TEST_MACROS_HPP_INCLUDED
5294
5295
5296
5297 #ifndef CATCH_TEST_MACRO_IMPL_HPP_INCLUDED
5298 #define CATCH_TEST_MACRO_IMPL_HPP_INCLUDED
5299
5300
5301
5302 #ifndef CATCH_ASSERTION_HANDLER_HPP_INCLUDED
5303 #define CATCH_ASSERTION_HANDLER_HPP_INCLUDED
5304
5305
5306
5307 #ifndef CATCH_DECOMPOSER_HPP_INCLUDED
5308 #define CATCH_DECOMPOSER_HPP_INCLUDED
5309
5310
5311 #include <iosfwd>
5312
5313 #ifdef _MSC_VER
5314 #pragma warning(push)
5315 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
5316 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
5317 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
5318 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
5319 #pragma warning(disable:4800) // Forcing result to true or false
5320 #endif
5321
5322 #ifdef __clang__
5323 # pragma clang diagnostic push
5324 # pragma clang diagnostic ignored "-Wsign-compare"
5325 #elif defined __GNUC__
5326 # pragma GCC diagnostic push
5327 # pragma GCC diagnostic ignored "-Wsign-compare"
5328 #endif
5329
5330 namespace Catch {
5331
5332 class ITransientExpression {
5333 bool m_isBinaryExpression;
5334 bool m_result;
5335
5336 public:
5337 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
5338 auto getResult() const -> bool { return m_result; }
5339 virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
5340
5341 ITransientExpression( bool isBinaryExpression, bool result )
5342 : m_isBinaryExpression( isBinaryExpression ),
5343 m_result( result )
5344 {}
5345
5346 ITransientExpression() = default;
5347 ITransientExpression(ITransientExpression const&) = default;
5348 ITransientExpression& operator=(ITransientExpression const&) = default;
5349
5350 // We don't actually need a virtual destructor, but many static analysers
5351 // complain if it's not here :-(
5352 virtual ~ITransientExpression(); // = default;
5353
5354 friend std::ostream& operator<<(std::ostream& out, ITransientExpression const& expr) {
5355 expr.streamReconstructedExpression(out);
5356 return out;
5357 }
5358 };
5359
5360 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
5361
5362 template<typename LhsT, typename RhsT>
5363 class BinaryExpr : public ITransientExpression {
5364 LhsT m_lhs;
5365 StringRef m_op;
5366 RhsT m_rhs;
5367
5368 void streamReconstructedExpression( std::ostream &os ) const override {
5369 formatReconstructedExpression
5370 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
5371 }
5372
5373 public:
5374 BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
5375 : ITransientExpression{ true, comparisonResult },
5376 m_lhs( lhs ),
5377 m_op( op ),
5378 m_rhs( rhs )
5379 {}
5380
5381 template<typename T>
5382 auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5383 static_assert(always_false<T>::value,
5384 "chained comparisons are not supported inside assertions, "
5385 "wrap the expression inside parentheses, or decompose it");
5386 }
5387
5388 template<typename T>
5389 auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5390 static_assert(always_false<T>::value,
5391 "chained comparisons are not supported inside assertions, "
5392 "wrap the expression inside parentheses, or decompose it");
5393 }
5394
5395 template<typename T>
5396 auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5397 static_assert(always_false<T>::value,
5398 "chained comparisons are not supported inside assertions, "
5399 "wrap the expression inside parentheses, or decompose it");
5400 }
5401
5402 template<typename T>
5403 auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5404 static_assert(always_false<T>::value,
5405 "chained comparisons are not supported inside assertions, "
5406 "wrap the expression inside parentheses, or decompose it");
5407 }
5408
5409 template<typename T>
5410 auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5411 static_assert(always_false<T>::value,
5412 "chained comparisons are not supported inside assertions, "
5413 "wrap the expression inside parentheses, or decompose it");
5414 }
5415
5416 template<typename T>
5417 auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5418 static_assert(always_false<T>::value,
5419 "chained comparisons are not supported inside assertions, "
5420 "wrap the expression inside parentheses, or decompose it");
5421 }
5422
5423 template<typename T>
5424 auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5425 static_assert(always_false<T>::value,
5426 "chained comparisons are not supported inside assertions, "
5427 "wrap the expression inside parentheses, or decompose it");
5428 }
5429
5430 template<typename T>
5431 auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
5432 static_assert(always_false<T>::value,
5433 "chained comparisons are not supported inside assertions, "
5434 "wrap the expression inside parentheses, or decompose it");
5435 }
5436 };
5437
5438 template<typename LhsT>
5439 class UnaryExpr : public ITransientExpression {
5440 LhsT m_lhs;
5441
5442 void streamReconstructedExpression( std::ostream &os ) const override {
5443 os << Catch::Detail::stringify( m_lhs );
5444 }
5445
5446 public:
5447 explicit UnaryExpr( LhsT lhs )
5448 : ITransientExpression{ false, static_cast<bool>(lhs) },
5449 m_lhs( lhs )
5450 {}
5451 };
5452
5453
5454 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
5455 template<typename LhsT, typename RhsT>
5456 auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
5457 template<typename T>
5458 auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
5459 template<typename T>
5460 auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
5461 template<typename T>
5462 auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
5463 template<typename T>
5464 auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
5465
5466 template<typename LhsT, typename RhsT>
5467 auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
5468 template<typename T>
5469 auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
5470 template<typename T>
5471 auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
5472 template<typename T>
5473 auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
5474 template<typename T>
5475 auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
5476
5477
5478 template<typename LhsT>
5479 class ExprLhs {
5480 LhsT m_lhs;
5481 public:
5482 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
5483
5484 template<typename RhsT, std::enable_if_t<!std::is_arithmetic<std::remove_reference_t<RhsT>>::value, int> = 0>
5485 friend auto operator == ( ExprLhs && lhs, RhsT && rhs ) -> BinaryExpr<LhsT, RhsT const&> {
5486 return { compareEqual( lhs.m_lhs, rhs ), lhs.m_lhs, "=="_sr, rhs };
5487 }
5488 template<typename RhsT, std::enable_if_t<std::is_arithmetic<RhsT>::value, int> = 0>
5489 friend auto operator == ( ExprLhs && lhs, RhsT rhs ) -> BinaryExpr<LhsT, RhsT> {
5490 return { compareEqual( lhs.m_lhs, rhs ), lhs.m_lhs, "=="_sr, rhs };
5491 }
5492
5493 template<typename RhsT, std::enable_if_t<!std::is_arithmetic<std::remove_reference_t<RhsT>>::value, int> = 0>
5494 friend auto operator != ( ExprLhs && lhs, RhsT && rhs ) -> BinaryExpr<LhsT, RhsT const&> {
5495 return { compareNotEqual( lhs.m_lhs, rhs ), lhs.m_lhs, "!="_sr, rhs };
5496 }
5497 template<typename RhsT, std::enable_if_t<std::is_arithmetic<RhsT>::value, int> = 0>
5498 friend auto operator != ( ExprLhs && lhs, RhsT rhs ) -> BinaryExpr<LhsT, RhsT> {
5499 return { compareNotEqual( lhs.m_lhs, rhs ), lhs.m_lhs, "!="_sr, rhs };
5500 }
5501
5502 #define CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(op) \
5503 template<typename RhsT, std::enable_if_t<!std::is_arithmetic<std::remove_reference_t<RhsT>>::value, int> = 0> \
5504 friend auto operator op ( ExprLhs && lhs, RhsT && rhs ) -> BinaryExpr<LhsT, RhsT const&> { \
5505 return { static_cast<bool>(lhs.m_lhs op rhs), lhs.m_lhs, #op##_sr, rhs }; \
5506 } \
5507 template<typename RhsT, std::enable_if_t<std::is_arithmetic<RhsT>::value, int> = 0> \
5508 friend auto operator op ( ExprLhs && lhs, RhsT rhs ) -> BinaryExpr<LhsT, RhsT> { \
5509 return { static_cast<bool>(lhs.m_lhs op rhs), lhs.m_lhs, #op##_sr, rhs }; \
5510 }
5511
5512 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(<)
5513 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(>)
5514 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(<=)
5515 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(>=)
5516 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(|)
5517 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(&)
5518 CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR(^)
5519
5520 #undef CATCH_INTERNAL_DEFINE_EXPRESSION_OPERATOR
5521
5522 template<typename RhsT>
5523 friend auto operator && ( ExprLhs &&, RhsT && ) -> BinaryExpr<LhsT, RhsT const&> {
5524 static_assert(always_false<RhsT>::value,
5525 "operator&& is not supported inside assertions, "
5526 "wrap the expression inside parentheses, or decompose it");
5527 }
5528
5529 template<typename RhsT>
5530 friend auto operator || ( ExprLhs &&, RhsT && ) -> BinaryExpr<LhsT, RhsT const&> {
5531 static_assert(always_false<RhsT>::value,
5532 "operator|| is not supported inside assertions, "
5533 "wrap the expression inside parentheses, or decompose it");
5534 }
5535
5536 auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
5537 return UnaryExpr<LhsT>{ m_lhs };
5538 }
5539 };
5540
5541 struct Decomposer {
5542 template<typename T, std::enable_if_t<!std::is_arithmetic<std::remove_reference_t<T>>::value, int> = 0>
5543 friend auto operator <= ( Decomposer &&, T && lhs ) -> ExprLhs<T const&> {
5544 return ExprLhs<const T&>{ lhs };
5545 }
5546
5547 template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
5548 friend auto operator <= ( Decomposer &&, T value ) -> ExprLhs<T> {
5549 return ExprLhs<T>{ value };
5550 }
5551 };
5552
5553 } // end namespace Catch
5554
5555 #ifdef _MSC_VER
5556 #pragma warning(pop)
5557 #endif
5558 #ifdef __clang__
5559 # pragma clang diagnostic pop
5560 #elif defined __GNUC__
5561 # pragma GCC diagnostic pop
5562 #endif
5563
5564 #endif // CATCH_DECOMPOSER_HPP_INCLUDED
5565
5566 #include <string>
5567
5568 namespace Catch {
5569
5570 class IResultCapture;
5571
5572 struct AssertionReaction {
5573 bool shouldDebugBreak = false;
5574 bool shouldThrow = false;
5575 };
5576
5577 class AssertionHandler {
5578 AssertionInfo m_assertionInfo;
5579 AssertionReaction m_reaction;
5580 bool m_completed = false;
5581 IResultCapture& m_resultCapture;
5582
5583 public:
5584 AssertionHandler
5585 ( StringRef macroName,
5586 SourceLineInfo const& lineInfo,
5587 StringRef capturedExpression,
5588 ResultDisposition::Flags resultDisposition );
5589 ~AssertionHandler() {
5590 if ( !m_completed ) {
5591 m_resultCapture.handleIncomplete( m_assertionInfo );
5592 }
5593 }
5594
5595
5596 template<typename T>
5597 void handleExpr( ExprLhs<T> const& expr ) {
5598 handleExpr( expr.makeUnaryExpr() );
5599 }
5600 void handleExpr( ITransientExpression const& expr );
5601
5602 void handleMessage(ResultWas::OfType resultType, StringRef message);
5603
5604 void handleExceptionThrownAsExpected();
5605 void handleUnexpectedExceptionNotThrown();
5606 void handleExceptionNotThrownAsExpected();
5607 void handleThrowingCallSkipped();
5608 void handleUnexpectedInflightException();
5609
5610 void complete();
5611 void setCompleted();
5612
5613 // query
5614 auto allowThrows() const -> bool;
5615 };
5616
5617 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
5618
5619 } // namespace Catch
5620
5621 #endif // CATCH_ASSERTION_HANDLER_HPP_INCLUDED
5622
5623 // We need this suppression to leak, because it took until GCC 10
5624 // for the front end to handle local suppression via _Pragma properly
5625 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && __GNUC__ <= 9
5626 #pragma GCC diagnostic ignored "-Wparentheses"
5627 #endif
5628
5629 #if !defined(CATCH_CONFIG_DISABLE)
5630
5631 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
5632 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
5633 #else
5634 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
5635 #endif
5636
5637 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
5638
5639 ///////////////////////////////////////////////////////////////////////////////
5640 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
5641 // macros.
5642 #define INTERNAL_CATCH_TRY
5643 #define INTERNAL_CATCH_CATCH( capturer )
5644
5645 #else // CATCH_CONFIG_FAST_COMPILE
5646
5647 #define INTERNAL_CATCH_TRY try
5648 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
5649
5650 #endif
5651
5652 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
5653
5654 ///////////////////////////////////////////////////////////////////////////////
5655 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
5656 do { /* NOLINT(bugprone-infinite-loop) */ \
5657 /* The expression should not be evaluated, but warnings should hopefully be checked */ \
5658 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
5659 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
5660 INTERNAL_CATCH_TRY { \
5661 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5662 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
5663 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
5664 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5665 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
5666 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
5667 } while( (void)0, (false) && static_cast<const bool&>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
5668 // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
5669
5670 ///////////////////////////////////////////////////////////////////////////////
5671 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
5672 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
5673 if( Catch::getResultCapture().lastAssertionPassed() )
5674
5675 ///////////////////////////////////////////////////////////////////////////////
5676 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
5677 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
5678 if( !Catch::getResultCapture().lastAssertionPassed() )
5679
5680 ///////////////////////////////////////////////////////////////////////////////
5681 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
5682 do { \
5683 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
5684 try { \
5685 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5686 CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
5687 static_cast<void>(__VA_ARGS__); \
5688 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5689 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
5690 } \
5691 catch( ... ) { \
5692 catchAssertionHandler.handleUnexpectedInflightException(); \
5693 } \
5694 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
5695 } while( false )
5696
5697 ///////////////////////////////////////////////////////////////////////////////
5698 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
5699 do { \
5700 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
5701 if( catchAssertionHandler.allowThrows() ) \
5702 try { \
5703 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5704 CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
5705 static_cast<void>(__VA_ARGS__); \
5706 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5707 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
5708 } \
5709 catch( ... ) { \
5710 catchAssertionHandler.handleExceptionThrownAsExpected(); \
5711 } \
5712 else \
5713 catchAssertionHandler.handleThrowingCallSkipped(); \
5714 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
5715 } while( false )
5716
5717 ///////////////////////////////////////////////////////////////////////////////
5718 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
5719 do { \
5720 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
5721 if( catchAssertionHandler.allowThrows() ) \
5722 try { \
5723 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5724 CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
5725 static_cast<void>(expr); \
5726 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5727 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
5728 } \
5729 catch( exceptionType const& ) { \
5730 catchAssertionHandler.handleExceptionThrownAsExpected(); \
5731 } \
5732 catch( ... ) { \
5733 catchAssertionHandler.handleUnexpectedInflightException(); \
5734 } \
5735 else \
5736 catchAssertionHandler.handleThrowingCallSkipped(); \
5737 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
5738 } while( false )
5739
5740
5741
5742 ///////////////////////////////////////////////////////////////////////////////
5743 // Although this is matcher-based, it can be used with just a string
5744 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
5745 do { \
5746 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
5747 if( catchAssertionHandler.allowThrows() ) \
5748 try { \
5749 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5750 CATCH_INTERNAL_SUPPRESS_USELESS_CAST_WARNINGS \
5751 static_cast<void>(__VA_ARGS__); \
5752 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5753 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
5754 } \
5755 catch( ... ) { \
5756 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
5757 } \
5758 else \
5759 catchAssertionHandler.handleThrowingCallSkipped(); \
5760 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
5761 } while( false )
5762
5763 #endif // CATCH_CONFIG_DISABLE
5764
5765 #endif // CATCH_TEST_MACRO_IMPL_HPP_INCLUDED
5766
5767
5768 #ifndef CATCH_SECTION_HPP_INCLUDED
5769 #define CATCH_SECTION_HPP_INCLUDED
5770
5771
5772
5773 #ifndef CATCH_TIMER_HPP_INCLUDED
5774 #define CATCH_TIMER_HPP_INCLUDED
5775
5776 #include <cstdint>
5777
5778 namespace Catch {
5779
5780 class Timer {
5781 uint64_t m_nanoseconds = 0;
5782 public:
5783 void start();
5784 auto getElapsedNanoseconds() const -> uint64_t;
5785 auto getElapsedMicroseconds() const -> uint64_t;
5786 auto getElapsedMilliseconds() const -> unsigned int;
5787 auto getElapsedSeconds() const -> double;
5788 };
5789
5790 } // namespace Catch
5791
5792 #endif // CATCH_TIMER_HPP_INCLUDED
5793
5794 namespace Catch {
5795
5796 class Section : Detail::NonCopyable {
5797 public:
5798 Section( SectionInfo&& info );
5799 ~Section();
5800
5801 // This indicates whether the section should be executed or not
5802 explicit operator bool() const;
5803
5804 private:
5805 SectionInfo m_info;
5806
5807 Counts m_assertions;
5808 bool m_sectionIncluded;
5809 Timer m_timer;
5810 };
5811
5812 } // end namespace Catch
5813
5814 #define INTERNAL_CATCH_SECTION( ... ) \
5815 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5816 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
5817 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
5818 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
5819
5820 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
5821 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5822 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
5823 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
5824 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
5825
5826 #endif // CATCH_SECTION_HPP_INCLUDED
5827
5828
5829 #ifndef CATCH_TEST_REGISTRY_HPP_INCLUDED
5830 #define CATCH_TEST_REGISTRY_HPP_INCLUDED
5831
5832
5833
5834 #ifndef CATCH_INTERFACES_TESTCASE_HPP_INCLUDED
5835 #define CATCH_INTERFACES_TESTCASE_HPP_INCLUDED
5836
5837 #include <vector>
5838
5839 namespace Catch {
5840
5841 class TestSpec;
5842 struct TestCaseInfo;
5843
5844 class ITestInvoker {
5845 public:
5846 virtual void invoke () const = 0;
5847 virtual ~ITestInvoker(); // = default
5848 };
5849
5850 class TestCaseHandle;
5851 class IConfig;
5852
5853 class ITestCaseRegistry {
5854 public:
5855 virtual ~ITestCaseRegistry(); // = default
5856 // TODO: this exists only for adding filenames to test cases -- let's expose this in a saner way later
5857 virtual std::vector<TestCaseInfo* > const& getAllInfos() const = 0;
5858 virtual std::vector<TestCaseHandle> const& getAllTests() const = 0;
5859 virtual std::vector<TestCaseHandle> const& getAllTestsSorted( IConfig const& config ) const = 0;
5860 };
5861
5862 bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config );
5863 bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config );
5864 std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config );
5865 std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config );
5866
5867 }
5868
5869 #endif // CATCH_INTERFACES_TESTCASE_HPP_INCLUDED
5870
5871
5872 #ifndef CATCH_PREPROCESSOR_REMOVE_PARENS_HPP_INCLUDED
5873 #define CATCH_PREPROCESSOR_REMOVE_PARENS_HPP_INCLUDED
5874
5875 #define INTERNAL_CATCH_EXPAND1( param ) INTERNAL_CATCH_EXPAND2( param )
5876 #define INTERNAL_CATCH_EXPAND2( ... ) INTERNAL_CATCH_NO##__VA_ARGS__
5877 #define INTERNAL_CATCH_DEF( ... ) INTERNAL_CATCH_DEF __VA_ARGS__
5878 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
5879
5880 #define INTERNAL_CATCH_REMOVE_PARENS( ... ) \
5881 INTERNAL_CATCH_EXPAND1( INTERNAL_CATCH_DEF __VA_ARGS__ )
5882
5883 #endif // CATCH_PREPROCESSOR_REMOVE_PARENS_HPP_INCLUDED
5884
5885 // GCC 5 and older do not properly handle disabling unused-variable warning
5886 // with a _Pragma. This means that we have to leak the suppression to the
5887 // user code as well :-(
5888 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ <= 5
5889 #pragma GCC diagnostic ignored "-Wunused-variable"
5890 #endif
5891
5892
5893
5894 namespace Catch {
5895
5896 template<typename C>
5897 class TestInvokerAsMethod : public ITestInvoker {
5898 void (C::*m_testAsMethod)();
5899 public:
5900 TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
5901
5902 void invoke() const override {
5903 C obj;
5904 (obj.*m_testAsMethod)();
5905 }
5906 };
5907
5908 Detail::unique_ptr<ITestInvoker> makeTestInvoker( void(*testAsFunction)() );
5909
5910 template<typename C>
5911 Detail::unique_ptr<ITestInvoker> makeTestInvoker( void (C::*testAsMethod)() ) {
5912 return Detail::make_unique<TestInvokerAsMethod<C>>( testAsMethod );
5913 }
5914
5915 struct NameAndTags {
5916 constexpr NameAndTags( StringRef name_ = StringRef(),
5917 StringRef tags_ = StringRef() ) noexcept:
5918 name( name_ ), tags( tags_ ) {}
5919 StringRef name;
5920 StringRef tags;
5921 };
5922
5923 struct AutoReg : Detail::NonCopyable {
5924 AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
5925 };
5926
5927 } // end namespace Catch
5928
5929 #if defined(CATCH_CONFIG_DISABLE)
5930 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
5931 static inline void TestName()
5932 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
5933 namespace{ \
5934 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
5935 void test(); \
5936 }; \
5937 } \
5938 void TestName::test()
5939 #endif
5940
5941 ///////////////////////////////////////////////////////////////////////////////
5942 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
5943 static void TestName(); \
5944 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5945 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5946 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
5947 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
5948 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5949 static void TestName()
5950 #define INTERNAL_CATCH_TESTCASE( ... ) \
5951 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), __VA_ARGS__ )
5952
5953 ///////////////////////////////////////////////////////////////////////////////
5954 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
5955 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5956 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5957 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
5958 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
5959 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
5960
5961 ///////////////////////////////////////////////////////////////////////////////
5962 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
5963 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5964 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5965 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
5966 namespace{ \
5967 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
5968 void test(); \
5969 }; \
5970 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
5971 } \
5972 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5973 void TestName::test()
5974 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
5975 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), ClassName, __VA_ARGS__ )
5976
5977 ///////////////////////////////////////////////////////////////////////////////
5978 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
5979 do { \
5980 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
5981 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5982 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
5983 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
5984 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
5985 } while(false)
5986
5987
5988 #endif // CATCH_TEST_REGISTRY_HPP_INCLUDED
5989
5990
5991 // All of our user-facing macros support configuration toggle, that
5992 // forces them to be defined prefixed with CATCH_. We also like to
5993 // support another toggle that can minimize (disable) their implementation.
5994 // Given this, we have 4 different configuration options below
5995
5996 #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
5997
5998 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
5999 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
6000
6001 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
6002 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
6003 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
6004
6005 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6006 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
6007 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
6008 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
6009 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
6010
6011 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6012 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
6013 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6014
6015 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
6016 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
6017 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
6018 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
6019 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
6020 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
6021 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
6022 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6023 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6024
6025
6026 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
6027 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
6028 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
6029 #define CATCH_STATIC_CHECK( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
6030 #define CATCH_STATIC_CHECK_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
6031 #else
6032 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
6033 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
6034 #define CATCH_STATIC_CHECK( ... ) CATCH_CHECK( __VA_ARGS__ )
6035 #define CATCH_STATIC_CHECK_FALSE( ... ) CATCH_CHECK_FALSE( __VA_ARGS__ )
6036 #endif
6037
6038
6039 // "BDD-style" convenience wrappers
6040 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
6041 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
6042 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
6043 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
6044 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
6045 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
6046 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
6047 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
6048
6049 #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) // ^^ prefixed, implemented | vv prefixed, disabled
6050
6051 #define CATCH_REQUIRE( ... ) (void)(0)
6052 #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
6053
6054 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
6055 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
6056 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
6057
6058 #define CATCH_CHECK( ... ) (void)(0)
6059 #define CATCH_CHECK_FALSE( ... ) (void)(0)
6060 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
6061 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
6062 #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
6063
6064 #define CATCH_CHECK_THROWS( ... ) (void)(0)
6065 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
6066 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
6067
6068 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
6069 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
6070 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
6071 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
6072 #define CATCH_SECTION( ... )
6073 #define CATCH_DYNAMIC_SECTION( ... )
6074 #define CATCH_FAIL( ... ) (void)(0)
6075 #define CATCH_FAIL_CHECK( ... ) (void)(0)
6076 #define CATCH_SUCCEED( ... ) (void)(0)
6077
6078 #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
6079 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
6080 #define CATCH_STATIC_CHECK( ... ) (void)(0)
6081 #define CATCH_STATIC_CHECK_FALSE( ... ) (void)(0)
6082
6083 // "BDD-style" convenience wrappers
6084 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
6085 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), className )
6086 #define CATCH_GIVEN( desc )
6087 #define CATCH_AND_GIVEN( desc )
6088 #define CATCH_WHEN( desc )
6089 #define CATCH_AND_WHEN( desc )
6090 #define CATCH_THEN( desc )
6091 #define CATCH_AND_THEN( desc )
6092
6093 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE) // ^^ prefixed, disabled | vv unprefixed, implemented
6094
6095 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
6096 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
6097
6098 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
6099 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
6100 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
6101
6102 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6103 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
6104 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
6105 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
6106 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
6107
6108 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6109 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
6110 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6111
6112 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
6113 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
6114 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
6115 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
6116 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
6117 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
6118 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
6119 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6120 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
6121
6122
6123 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
6124 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
6125 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
6126 #define STATIC_CHECK( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
6127 #define STATIC_CHECK_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
6128 #else
6129 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
6130 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
6131 #define STATIC_CHECK( ... ) CHECK( __VA_ARGS__ )
6132 #define STATIC_CHECK_FALSE( ... ) CHECK_FALSE( __VA_ARGS__ )
6133 #endif
6134
6135 // "BDD-style" convenience wrappers
6136 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
6137 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
6138 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
6139 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
6140 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
6141 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
6142 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
6143 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
6144
6145 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE) // ^^ unprefixed, implemented | vv unprefixed, disabled
6146
6147 #define REQUIRE( ... ) (void)(0)
6148 #define REQUIRE_FALSE( ... ) (void)(0)
6149
6150 #define REQUIRE_THROWS( ... ) (void)(0)
6151 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
6152 #define REQUIRE_NOTHROW( ... ) (void)(0)
6153
6154 #define CHECK( ... ) (void)(0)
6155 #define CHECK_FALSE( ... ) (void)(0)
6156 #define CHECKED_IF( ... ) if (__VA_ARGS__)
6157 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
6158 #define CHECK_NOFAIL( ... ) (void)(0)
6159
6160 #define CHECK_THROWS( ... ) (void)(0)
6161 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
6162 #define CHECK_NOTHROW( ... ) (void)(0)
6163
6164 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), __VA_ARGS__)
6165 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ))
6166 #define METHOD_AS_TEST_CASE( method, ... )
6167 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
6168 #define SECTION( ... )
6169 #define DYNAMIC_SECTION( ... )
6170 #define FAIL( ... ) (void)(0)
6171 #define FAIL_CHECK( ... ) (void)(0)
6172 #define SUCCEED( ... ) (void)(0)
6173
6174 #define STATIC_REQUIRE( ... ) (void)(0)
6175 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
6176 #define STATIC_CHECK( ... ) (void)(0)
6177 #define STATIC_CHECK_FALSE( ... ) (void)(0)
6178
6179 // "BDD-style" convenience wrappers
6180 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ) )
6181 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEST_ ), className )
6182
6183 #define GIVEN( desc )
6184 #define AND_GIVEN( desc )
6185 #define WHEN( desc )
6186 #define AND_WHEN( desc )
6187 #define THEN( desc )
6188 #define AND_THEN( desc )
6189
6190 #endif // ^^ unprefixed, disabled
6191
6192 // end of user facing macros
6193
6194 #endif // CATCH_TEST_MACROS_HPP_INCLUDED
6195
6196
6197 #ifndef CATCH_TEMPLATE_TEST_REGISTRY_HPP_INCLUDED
6198 #define CATCH_TEMPLATE_TEST_REGISTRY_HPP_INCLUDED
6199
6200
6201
6202 #ifndef CATCH_PREPROCESSOR_HPP_INCLUDED
6203 #define CATCH_PREPROCESSOR_HPP_INCLUDED
6204
6205
6206 #if defined(__GNUC__)
6207 // We need to silence "empty __VA_ARGS__ warning", and using just _Pragma does not work
6208 #pragma GCC system_header
6209 #endif
6210
6211
6212 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
6213 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
6214 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
6215 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
6216 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
6217 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
6218
6219 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6220 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
6221 // MSVC needs more evaluations
6222 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
6223 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
6224 #else
6225 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
6226 #endif
6227
6228 #define CATCH_REC_END(...)
6229 #define CATCH_REC_OUT
6230
6231 #define CATCH_EMPTY()
6232 #define CATCH_DEFER(id) id CATCH_EMPTY()
6233
6234 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
6235 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
6236 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
6237 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
6238 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
6239 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
6240
6241 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
6242 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
6243 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
6244
6245 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
6246 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
6247 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
6248
6249 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
6250 // and passes userdata as the first parameter to each invocation,
6251 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
6252 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
6253
6254 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
6255
6256 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
6257 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6258 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
6259 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
6260 #else
6261 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
6262 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
6263 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
6264 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
6265 #endif
6266
6267 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
6268 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
6269
6270 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6271 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
6272 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
6273 #else
6274 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
6275 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
6276 #endif
6277
6278 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
6279 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
6280
6281 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
6282 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
6283 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
6284 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
6285 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
6286 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
6287 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
6288 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
6289 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
6290 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
6291 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
6292
6293 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
6294
6295 #define INTERNAL_CATCH_TYPE_GEN\
6296 template<typename...> struct TypeList {};\
6297 template<typename...Ts>\
6298 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
6299 template<template<typename...> class...> struct TemplateTypeList{};\
6300 template<template<typename...> class...Cs>\
6301 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
6302 template<typename...>\
6303 struct append;\
6304 template<typename...>\
6305 struct rewrap;\
6306 template<template<typename...> class, typename...>\
6307 struct create;\
6308 template<template<typename...> class, typename>\
6309 struct convert;\
6310 \
6311 template<typename T> \
6312 struct append<T> { using type = T; };\
6313 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
6314 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
6315 template< template<typename...> class L1, typename...E1, typename...Rest>\
6316 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
6317 \
6318 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
6319 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
6320 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
6321 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
6322 \
6323 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
6324 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
6325 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
6326 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
6327
6328 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
6329 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
6330 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6331 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
6332 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
6333 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
6334 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
6335 \
6336 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6337 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
6338 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
6339 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
6340 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
6341 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
6342
6343 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
6344 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
6345 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6346 static void TestName()
6347 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
6348 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6349 static void TestName()
6350
6351 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
6352 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
6353 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6354 static void TestName()
6355 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
6356 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6357 static void TestName()
6358
6359 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
6360 template<typename Type>\
6361 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
6362 {\
6363 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
6364 }
6365
6366 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
6367 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6368 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
6369 {\
6370 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
6371 }
6372
6373 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
6374 template<typename Type>\
6375 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
6376 {\
6377 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
6378 }
6379
6380 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
6381 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
6382 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
6383 {\
6384 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
6385 }
6386
6387 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
6388 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
6389 template<typename TestType> \
6390 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
6391 void test();\
6392 }
6393
6394 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
6395 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
6396 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
6397 void test();\
6398 }
6399
6400 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
6401 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
6402 template<typename TestType> \
6403 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
6404 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
6405 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
6406 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
6407
6408 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6409 #define INTERNAL_CATCH_NTTP_0
6410 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
6411 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
6412 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
6413 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
6414 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
6415 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
6416 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
6417 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
6418 #else
6419 #define INTERNAL_CATCH_NTTP_0(signature)
6420 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
6421 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
6422 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
6423 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
6424 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
6425 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
6426 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
6427 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
6428 #endif
6429
6430 #endif // CATCH_PREPROCESSOR_HPP_INCLUDED
6431
6432
6433 // GCC 5 and older do not properly handle disabling unused-variable warning
6434 // with a _Pragma. This means that we have to leak the suppression to the
6435 // user code as well :-(
6436 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ <= 5
6437 #pragma GCC diagnostic ignored "-Wunused-variable"
6438 #endif
6439
6440 #if defined(CATCH_CONFIG_DISABLE)
6441 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
6442 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
6443 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
6444 namespace{ \
6445 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
6446 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
6447 } \
6448 } \
6449 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
6450
6451 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6452 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
6453 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, typename TestType, __VA_ARGS__ )
6454 #else
6455 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
6456 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
6457 #endif
6458
6459 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6460 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
6461 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, Signature, __VA_ARGS__ )
6462 #else
6463 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
6464 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, Signature, __VA_ARGS__ ) )
6465 #endif
6466
6467 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6468 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
6469 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
6470 #else
6471 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
6472 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
6473 #endif
6474
6475 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6476 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
6477 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
6478 #else
6479 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
6480 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
6481 #endif
6482 #endif
6483
6484
6485 ///////////////////////////////////////////////////////////////////////////////
6486 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
6487 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6488 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6489 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
6490 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
6491 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
6492 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
6493 namespace {\
6494 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
6495 INTERNAL_CATCH_TYPE_GEN\
6496 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
6497 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
6498 template<typename...Types> \
6499 struct TestName{\
6500 TestName(){\
6501 size_t index = 0; \
6502 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; /* NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,hicpp-avoid-c-arrays) */\
6503 using expander = size_t[]; /* NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays,hicpp-avoid-c-arrays) */\
6504 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
6505 }\
6506 };\
6507 static const int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
6508 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
6509 return 0;\
6510 }();\
6511 }\
6512 }\
6513 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
6514 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
6515
6516 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6517 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
6518 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, typename TestType, __VA_ARGS__ )
6519 #else
6520 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
6521 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
6522 #endif
6523
6524 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6525 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
6526 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, Signature, __VA_ARGS__ )
6527 #else
6528 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
6529 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, Signature, __VA_ARGS__ ) )
6530 #endif
6531
6532 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
6533 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6534 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6535 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
6536 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
6537 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
6538 template<typename TestType> static void TestFuncName(); \
6539 namespace {\
6540 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
6541 INTERNAL_CATCH_TYPE_GEN \
6542 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
6543 template<typename... Types> \
6544 struct TestName { \
6545 void reg_tests() { \
6546 size_t index = 0; \
6547 using expander = size_t[]; \
6548 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
6549 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
6550 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
6551 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + '<' + std::string(types_list[index % num_types]) + '>', Tags } ), index++)... };/* NOLINT */\
6552 } \
6553 }; \
6554 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
6555 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
6556 TestInit t; \
6557 t.reg_tests(); \
6558 return 0; \
6559 }(); \
6560 } \
6561 } \
6562 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
6563 template<typename TestType> \
6564 static void TestFuncName()
6565
6566 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6567 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
6568 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, typename T,__VA_ARGS__)
6569 #else
6570 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
6571 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, typename T, __VA_ARGS__ ) )
6572 #endif
6573
6574 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6575 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
6576 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, Signature, __VA_ARGS__)
6577 #else
6578 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
6579 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, Signature, __VA_ARGS__ ) )
6580 #endif
6581
6582 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
6583 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6584 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6585 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
6586 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
6587 template<typename TestType> static void TestFunc(); \
6588 namespace {\
6589 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
6590 INTERNAL_CATCH_TYPE_GEN\
6591 template<typename... Types> \
6592 struct TestName { \
6593 void reg_tests() { \
6594 size_t index = 0; \
6595 using expander = size_t[]; \
6596 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
6597 } \
6598 };\
6599 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
6600 using TestInit = typename convert<TestName, TmplList>::type; \
6601 TestInit t; \
6602 t.reg_tests(); \
6603 return 0; \
6604 }(); \
6605 }}\
6606 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
6607 template<typename TestType> \
6608 static void TestFunc()
6609
6610 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
6611 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), Name, Tags, TmplList )
6612
6613
6614 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
6615 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6616 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6617 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
6618 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
6619 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
6620 namespace {\
6621 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
6622 INTERNAL_CATCH_TYPE_GEN\
6623 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
6624 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
6625 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
6626 template<typename...Types> \
6627 struct TestNameClass{\
6628 TestNameClass(){\
6629 size_t index = 0; \
6630 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
6631 using expander = size_t[];\
6632 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
6633 }\
6634 };\
6635 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
6636 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
6637 return 0;\
6638 }();\
6639 }\
6640 }\
6641 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
6642 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
6643
6644 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6645 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
6646 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
6647 #else
6648 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
6649 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
6650 #endif
6651
6652 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6653 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
6654 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
6655 #else
6656 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
6657 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_CLASS_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
6658 #endif
6659
6660 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
6661 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6662 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6663 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
6664 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
6665 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
6666 template<typename TestType> \
6667 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
6668 void test();\
6669 };\
6670 namespace {\
6671 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
6672 INTERNAL_CATCH_TYPE_GEN \
6673 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
6674 template<typename...Types>\
6675 struct TestNameClass{\
6676 void reg_tests(){\
6677 std::size_t index = 0;\
6678 using expander = std::size_t[];\
6679 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
6680 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
6681 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
6682 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + '<' + std::string(types_list[index % num_types]) + '>', Tags } ), index++)... };/* NOLINT */ \
6683 }\
6684 };\
6685 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
6686 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
6687 TestInit t;\
6688 t.reg_tests();\
6689 return 0;\
6690 }(); \
6691 }\
6692 }\
6693 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
6694 template<typename TestType> \
6695 void TestName<TestType>::test()
6696
6697 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6698 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
6699 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
6700 #else
6701 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
6702 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
6703 #endif
6704
6705 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6706 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
6707 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
6708 #else
6709 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
6710 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
6711 #endif
6712
6713 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
6714 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6715 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6716 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
6717 CATCH_INTERNAL_SUPPRESS_UNUSED_VARIABLE_WARNINGS \
6718 template<typename TestType> \
6719 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
6720 void test();\
6721 };\
6722 namespace {\
6723 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
6724 INTERNAL_CATCH_TYPE_GEN\
6725 template<typename...Types>\
6726 struct TestNameClass{\
6727 void reg_tests(){\
6728 size_t index = 0;\
6729 using expander = size_t[];\
6730 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
6731 }\
6732 };\
6733 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
6734 using TestInit = typename convert<TestNameClass, TmplList>::type;\
6735 TestInit t;\
6736 t.reg_tests();\
6737 return 0;\
6738 }(); \
6739 }}\
6740 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
6741 template<typename TestType> \
6742 void TestName<TestType>::test()
6743
6744 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
6745 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), INTERNAL_CATCH_UNIQUE_NAME( CATCH2_INTERNAL_TEMPLATE_TEST_ ), ClassName, Name, Tags, TmplList )
6746
6747
6748 #endif // CATCH_TEMPLATE_TEST_REGISTRY_HPP_INCLUDED
6749
6750
6751 #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
6752
6753 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6754 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
6755 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
6756 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6757 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
6758 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
6759 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
6760 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
6761 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
6762 #define CATCH_TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
6763 #define CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
6764 #else
6765 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
6766 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
6767 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
6768 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
6769 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
6770 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
6771 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
6772 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
6773 #define CATCH_TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
6774 #define CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
6775 #endif
6776
6777 #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE)
6778
6779 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6780 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
6781 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
6782 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
6783 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
6784 #else
6785 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
6786 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
6787 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
6788 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
6789 #endif
6790
6791 // When disabled, these can be shared between proper preprocessor and MSVC preprocessor
6792 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
6793 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
6794 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6795 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6796 #define CATCH_TEMPLATE_LIST_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
6797 #define CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6798
6799 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
6800
6801 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6802 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
6803 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
6804 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6805 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
6806 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
6807 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
6808 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
6809 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
6810 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
6811 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
6812 #else
6813 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
6814 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
6815 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
6816 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
6817 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
6818 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
6819 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
6820 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
6821 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
6822 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
6823 #endif
6824
6825 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE)
6826
6827 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
6828 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
6829 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
6830 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
6831 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
6832 #else
6833 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
6834 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
6835 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
6836 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
6837 #endif
6838
6839 // When disabled, these can be shared between proper preprocessor and MSVC preprocessor
6840 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
6841 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
6842 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6843 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6844 #define TEMPLATE_LIST_TEST_CASE( ... ) TEMPLATE_TEST_CASE(__VA_ARGS__)
6845 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
6846
6847 #endif // end of user facing macro declarations
6848
6849
6850 #endif // CATCH_TEMPLATE_TEST_MACROS_HPP_INCLUDED
6851
6852
6853 #ifndef CATCH_TEST_CASE_INFO_HPP_INCLUDED
6854 #define CATCH_TEST_CASE_INFO_HPP_INCLUDED
6855
6856
6857
6858 #include <string>
6859 #include <vector>
6860
6861 #ifdef __clang__
6862 #pragma clang diagnostic push
6863 #pragma clang diagnostic ignored "-Wpadded"
6864 #endif
6865
6866 namespace Catch {
6867
6868 /**
6869 * A **view** of a tag string that provides case insensitive comparisons
6870 *
6871 * Note that in Catch2 internals, the square brackets around tags are
6872 * not a part of tag's representation, so e.g. "[cool-tag]" is represented
6873 * as "cool-tag" internally.
6874 */
6875 struct Tag {
6876 constexpr Tag(StringRef original_):
6877 original(original_)
6878 {}
6879 StringRef original;
6880
6881 friend bool operator< ( Tag const& lhs, Tag const& rhs );
6882 friend bool operator==( Tag const& lhs, Tag const& rhs );
6883 };
6884
6885 class ITestInvoker;
6886
6887 enum class TestCaseProperties : uint8_t {
6888 None = 0,
6889 IsHidden = 1 << 1,
6890 ShouldFail = 1 << 2,
6891 MayFail = 1 << 3,
6892 Throws = 1 << 4,
6893 NonPortable = 1 << 5,
6894 Benchmark = 1 << 6
6895 };
6896
6897 /**
6898 * Various metadata about the test case.
6899 *
6900 * A test case is uniquely identified by its (class)name and tags
6901 * combination, with source location being ignored, and other properties
6902 * being determined from tags.
6903 *
6904 * Tags are kept sorted.
6905 */
6906 struct TestCaseInfo : Detail::NonCopyable {
6907
6908 TestCaseInfo(StringRef _className,
6909 NameAndTags const& _tags,
6910 SourceLineInfo const& _lineInfo);
6911
6912 bool isHidden() const;
6913 bool throws() const;
6914 bool okToFail() const;
6915 bool expectedToFail() const;
6916
6917 // Adds the tag(s) with test's filename (for the -# flag)
6918 void addFilenameTag();
6919
6920 //! Orders by name, classname and tags
6921 friend bool operator<( TestCaseInfo const& lhs,
6922 TestCaseInfo const& rhs );
6923
6924
6925 std::string tagsAsString() const;
6926
6927 std::string name;
6928 StringRef className;
6929 private:
6930 std::string backingTags;
6931 // Internally we copy tags to the backing storage and then add
6932 // refs to this storage to the tags vector.
6933 void internalAppendTag(StringRef tagString);
6934 public:
6935 std::vector<Tag> tags;
6936 SourceLineInfo lineInfo;
6937 TestCaseProperties properties = TestCaseProperties::None;
6938 };
6939
6940 /**
6941 * Wrapper over the test case information and the test case invoker
6942 *
6943 * Does not own either, and is specifically made to be cheap
6944 * to copy around.
6945 */
6946 class TestCaseHandle {
6947 TestCaseInfo* m_info;
6948 ITestInvoker* m_invoker;
6949 public:
6950 TestCaseHandle(TestCaseInfo* info, ITestInvoker* invoker) :
6951 m_info(info), m_invoker(invoker) {}
6952
6953 void invoke() const {
6954 m_invoker->invoke();
6955 }
6956
6957 TestCaseInfo const& getTestCaseInfo() const;
6958 };
6959
6960 Detail::unique_ptr<TestCaseInfo>
6961 makeTestCaseInfo( StringRef className,
6962 NameAndTags const& nameAndTags,
6963 SourceLineInfo const& lineInfo );
6964 }
6965
6966 #ifdef __clang__
6967 #pragma clang diagnostic pop
6968 #endif
6969
6970 #endif // CATCH_TEST_CASE_INFO_HPP_INCLUDED
6971
6972
6973 #ifndef CATCH_TRANSLATE_EXCEPTION_HPP_INCLUDED
6974 #define CATCH_TRANSLATE_EXCEPTION_HPP_INCLUDED
6975
6976
6977
6978 #ifndef CATCH_INTERFACES_EXCEPTION_HPP_INCLUDED
6979 #define CATCH_INTERFACES_EXCEPTION_HPP_INCLUDED
6980
6981
6982 #include <string>
6983 #include <vector>
6984
6985 namespace Catch {
6986 using exceptionTranslateFunction = std::string(*)();
6987
6988 class IExceptionTranslator;
6989 using ExceptionTranslators = std::vector<Detail::unique_ptr<IExceptionTranslator const>>;
6990
6991 class IExceptionTranslator {
6992 public:
6993 virtual ~IExceptionTranslator(); // = default
6994 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
6995 };
6996
6997 class IExceptionTranslatorRegistry {
6998 public:
6999 virtual ~IExceptionTranslatorRegistry(); // = default
7000 virtual std::string translateActiveException() const = 0;
7001 };
7002
7003 } // namespace Catch
7004
7005 #endif // CATCH_INTERFACES_EXCEPTION_HPP_INCLUDED
7006
7007 #include <exception>
7008
7009 namespace Catch {
7010
7011 class ExceptionTranslatorRegistrar {
7012 template<typename T>
7013 class ExceptionTranslator : public IExceptionTranslator {
7014 public:
7015
7016 ExceptionTranslator( std::string(*translateFunction)( T const& ) )
7017 : m_translateFunction( translateFunction )
7018 {}
7019
7020 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
7021 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
7022 try {
7023 if( it == itEnd )
7024 std::rethrow_exception(std::current_exception());
7025 else
7026 return (*it)->translate( it+1, itEnd );
7027 }
7028 catch( T const& ex ) {
7029 return m_translateFunction( ex );
7030 }
7031 #else
7032 return "You should never get here!";
7033 #endif
7034 }
7035
7036 protected:
7037 std::string(*m_translateFunction)( T const& );
7038 };
7039
7040 public:
7041 template<typename T>
7042 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T const& ) ) {
7043 getMutableRegistryHub().registerTranslator(
7044 Detail::make_unique<ExceptionTranslator<T>>(translateFunction)
7045 );
7046 }
7047 };
7048
7049 } // namespace Catch
7050
7051 ///////////////////////////////////////////////////////////////////////////////
7052 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
7053 static std::string translatorName( signature ); \
7054 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
7055 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
7056 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
7057 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
7058 static std::string translatorName( signature )
7059
7060 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
7061
7062 #if defined(CATCH_CONFIG_DISABLE)
7063 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
7064 static std::string translatorName( signature )
7065 #endif
7066
7067
7068 // This macro is always prefixed
7069 #if !defined(CATCH_CONFIG_DISABLE)
7070 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
7071 #else
7072 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
7073 #endif
7074
7075
7076 #endif // CATCH_TRANSLATE_EXCEPTION_HPP_INCLUDED
7077
7078
7079 #ifndef CATCH_VERSION_HPP_INCLUDED
7080 #define CATCH_VERSION_HPP_INCLUDED
7081
7082 #include <iosfwd>
7083
7084 namespace Catch {
7085
7086 // Versioning information
7087 struct Version {
7088 Version( Version const& ) = delete;
7089 Version& operator=( Version const& ) = delete;
7090 Version( unsigned int _majorVersion,
7091 unsigned int _minorVersion,
7092 unsigned int _patchNumber,
7093 char const * const _branchName,
7094 unsigned int _buildNumber );
7095
7096 unsigned int const majorVersion;
7097 unsigned int const minorVersion;
7098 unsigned int const patchNumber;
7099
7100 // buildNumber is only used if branchName is not null
7101 char const * const branchName;
7102 unsigned int const buildNumber;
7103
7104 friend std::ostream& operator << ( std::ostream& os, Version const& version );
7105 };
7106
7107 Version const& libraryVersion();
7108 }
7109
7110 #endif // CATCH_VERSION_HPP_INCLUDED
7111
7112
7113 #ifndef CATCH_VERSION_MACROS_HPP_INCLUDED
7114 #define CATCH_VERSION_MACROS_HPP_INCLUDED
7115
7116 #define CATCH_VERSION_MAJOR 3
7117 #define CATCH_VERSION_MINOR 1
7118 #define CATCH_VERSION_PATCH 1
7119
7120 #endif // CATCH_VERSION_MACROS_HPP_INCLUDED
7121
7122
7123 /** \file
7124 * This is a convenience header for Catch2's Generator support. It includes
7125 * **all** of Catch2 headers related to generators.
7126 *
7127 * Generally the Catch2 users should use specific includes they need,
7128 * but this header can be used instead for ease-of-experimentation, or
7129 * just plain convenience, at the cost of (significantly) increased
7130 * compilation times.
7131 *
7132 * When a new header is added to either the `generators` folder,
7133 * or to the corresponding internal subfolder, it should be added here.
7134 */
7135
7136 #ifndef CATCH_GENERATORS_ALL_HPP_INCLUDED
7137 #define CATCH_GENERATORS_ALL_HPP_INCLUDED
7138
7139
7140
7141 #ifndef CATCH_GENERATOR_EXCEPTION_HPP_INCLUDED
7142 #define CATCH_GENERATOR_EXCEPTION_HPP_INCLUDED
7143
7144 #include <exception>
7145
7146 namespace Catch {
7147
7148 // Exception type to be thrown when a Generator runs into an error,
7149 // e.g. it cannot initialize the first return value based on
7150 // runtime information
7151 class GeneratorException : public std::exception {
7152 const char* const m_msg = "";
7153
7154 public:
7155 GeneratorException(const char* msg):
7156 m_msg(msg)
7157 {}
7158
7159 const char* what() const noexcept override final;
7160 };
7161
7162 } // end namespace Catch
7163
7164 #endif // CATCH_GENERATOR_EXCEPTION_HPP_INCLUDED
7165
7166
7167 #ifndef CATCH_GENERATORS_HPP_INCLUDED
7168 #define CATCH_GENERATORS_HPP_INCLUDED
7169
7170
7171
7172 #ifndef CATCH_INTERFACES_GENERATORTRACKER_HPP_INCLUDED
7173 #define CATCH_INTERFACES_GENERATORTRACKER_HPP_INCLUDED
7174
7175
7176 #include <string>
7177
7178 namespace Catch {
7179
7180 namespace Generators {
7181 class GeneratorUntypedBase {
7182 // Caches result from `toStringImpl`, assume that when it is an
7183 // empty string, the cache is invalidated.
7184 mutable std::string m_stringReprCache;
7185
7186 // Counts based on `next` returning true
7187 std::size_t m_currentElementIndex = 0;
7188
7189 /**
7190 * Attempts to move the generator to the next element
7191 *
7192 * Returns true iff the move succeeded (and a valid element
7193 * can be retrieved).
7194 */
7195 virtual bool next() = 0;
7196
7197 //! Customization point for `currentElementAsString`
7198 virtual std::string stringifyImpl() const = 0;
7199
7200 public:
7201 GeneratorUntypedBase() = default;
7202 // Generation of copy ops is deprecated (and Clang will complain)
7203 // if there is a user destructor defined
7204 GeneratorUntypedBase(GeneratorUntypedBase const&) = default;
7205 GeneratorUntypedBase& operator=(GeneratorUntypedBase const&) = default;
7206
7207 virtual ~GeneratorUntypedBase(); // = default;
7208
7209 /**
7210 * Attempts to move the generator to the next element
7211 *
7212 * Serves as a non-virtual interface to `next`, so that the
7213 * top level interface can provide sanity checking and shared
7214 * features.
7215 *
7216 * As with `next`, returns true iff the move succeeded and
7217 * the generator has new valid element to provide.
7218 */
7219 bool countedNext();
7220
7221 std::size_t currentElementIndex() const { return m_currentElementIndex; }
7222
7223 /**
7224 * Returns generator's current element as user-friendly string.
7225 *
7226 * By default returns string equivalent to calling
7227 * `Catch::Detail::stringify` on the current element, but generators
7228 * can customize their implementation as needed.
7229 *
7230 * Not thread-safe due to internal caching.
7231 *
7232 * The returned ref is valid only until the generator instance
7233 * is destructed, or it moves onto the next element, whichever
7234 * comes first.
7235 */
7236 StringRef currentElementAsString() const;
7237 };
7238 using GeneratorBasePtr = Catch::Detail::unique_ptr<GeneratorUntypedBase>;
7239
7240 } // namespace Generators
7241
7242 class IGeneratorTracker {
7243 public:
7244 virtual ~IGeneratorTracker(); // = default;
7245 virtual auto hasGenerator() const -> bool = 0;
7246 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
7247 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
7248 };
7249
7250 } // namespace Catch
7251
7252 #endif // CATCH_INTERFACES_GENERATORTRACKER_HPP_INCLUDED
7253
7254 #include <vector>
7255 #include <tuple>
7256
7257 namespace Catch {
7258
7259 namespace Generators {
7260
7261 namespace Detail {
7262
7263 //! Throws GeneratorException with the provided message
7264 [[noreturn]]
7265 void throw_generator_exception(char const * msg);
7266
7267 } // end namespace detail
7268
7269 template<typename T>
7270 class IGenerator : public GeneratorUntypedBase {
7271 std::string stringifyImpl() const override {
7272 return ::Catch::Detail::stringify( get() );
7273 }
7274
7275 public:
7276 ~IGenerator() override = default;
7277 IGenerator() = default;
7278 IGenerator(IGenerator const&) = default;
7279 IGenerator& operator=(IGenerator const&) = default;
7280
7281
7282 // Returns the current element of the generator
7283 //
7284 // \Precondition The generator is either freshly constructed,
7285 // or the last call to `next()` returned true
7286 virtual T const& get() const = 0;
7287 using type = T;
7288 };
7289
7290 template <typename T>
7291 using GeneratorPtr = Catch::Detail::unique_ptr<IGenerator<T>>;
7292
7293 template <typename T>
7294 class GeneratorWrapper final {
7295 GeneratorPtr<T> m_generator;
7296 public:
7297 //! Takes ownership of the passed pointer.
7298 GeneratorWrapper(IGenerator<T>* generator):
7299 m_generator(generator) {}
7300 GeneratorWrapper(GeneratorPtr<T> generator):
7301 m_generator(CATCH_MOVE(generator)) {}
7302
7303 T const& get() const {
7304 return m_generator->get();
7305 }
7306 bool next() {
7307 return m_generator->countedNext();
7308 }
7309 };
7310
7311
7312 template<typename T>
7313 class SingleValueGenerator final : public IGenerator<T> {
7314 T m_value;
7315 public:
7316 SingleValueGenerator(T const& value) :
7317 m_value(value)
7318 {}
7319 SingleValueGenerator(T&& value):
7320 m_value(CATCH_MOVE(value))
7321 {}
7322
7323 T const& get() const override {
7324 return m_value;
7325 }
7326 bool next() override {
7327 return false;
7328 }
7329 };
7330
7331 template<typename T>
7332 class FixedValuesGenerator final : public IGenerator<T> {
7333 static_assert(!std::is_same<T, bool>::value,
7334 "FixedValuesGenerator does not support bools because of std::vector<bool>"
7335 "specialization, use SingleValue Generator instead.");
7336 std::vector<T> m_values;
7337 size_t m_idx = 0;
7338 public:
7339 FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
7340
7341 T const& get() const override {
7342 return m_values[m_idx];
7343 }
7344 bool next() override {
7345 ++m_idx;
7346 return m_idx < m_values.size();
7347 }
7348 };
7349
7350 template <typename T, typename DecayedT = std::decay_t<T>>
7351 GeneratorWrapper<DecayedT> value( T&& value ) {
7352 return GeneratorWrapper<DecayedT>(
7353 Catch::Detail::make_unique<SingleValueGenerator<DecayedT>>(
7354 CATCH_FORWARD( value ) ) );
7355 }
7356 template <typename T>
7357 GeneratorWrapper<T> values(std::initializer_list<T> values) {
7358 return GeneratorWrapper<T>(Catch::Detail::make_unique<FixedValuesGenerator<T>>(values));
7359 }
7360
7361 template<typename T>
7362 class Generators : public IGenerator<T> {
7363 std::vector<GeneratorWrapper<T>> m_generators;
7364 size_t m_current = 0;
7365
7366 void add_generator( GeneratorWrapper<T>&& generator ) {
7367 m_generators.emplace_back( CATCH_MOVE( generator ) );
7368 }
7369 void add_generator( T const& val ) {
7370 m_generators.emplace_back( value( val ) );
7371 }
7372 void add_generator( T&& val ) {
7373 m_generators.emplace_back( value( CATCH_MOVE( val ) ) );
7374 }
7375 template <typename U>
7376 std::enable_if_t<!std::is_same<std::decay_t<U>, T>::value>
7377 add_generator( U&& val ) {
7378 add_generator( T( CATCH_FORWARD( val ) ) );
7379 }
7380
7381 template <typename U> void add_generators( U&& valueOrGenerator ) {
7382 add_generator( CATCH_FORWARD( valueOrGenerator ) );
7383 }
7384
7385 template <typename U, typename... Gs>
7386 void add_generators( U&& valueOrGenerator, Gs&&... moreGenerators ) {
7387 add_generator( CATCH_FORWARD( valueOrGenerator ) );
7388 add_generators( CATCH_FORWARD( moreGenerators )... );
7389 }
7390
7391 public:
7392 template <typename... Gs>
7393 Generators(Gs &&... moreGenerators) {
7394 m_generators.reserve(sizeof...(Gs));
7395 add_generators(CATCH_FORWARD(moreGenerators)...);
7396 }
7397
7398 T const& get() const override {
7399 return m_generators[m_current].get();
7400 }
7401
7402 bool next() override {
7403 if (m_current >= m_generators.size()) {
7404 return false;
7405 }
7406 const bool current_status = m_generators[m_current].next();
7407 if (!current_status) {
7408 ++m_current;
7409 }
7410 return m_current < m_generators.size();
7411 }
7412 };
7413
7414
7415 template <typename... Ts>
7416 GeneratorWrapper<std::tuple<std::decay_t<Ts>...>>
7417 table( std::initializer_list<std::tuple<std::decay_t<Ts>...>> tuples ) {
7418 return values<std::tuple<Ts...>>( tuples );
7419 }
7420
7421 // Tag type to signal that a generator sequence should convert arguments to a specific type
7422 template <typename T>
7423 struct as {};
7424
7425 template<typename T, typename... Gs>
7426 auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
7427 return Generators<T>(CATCH_MOVE(generator), CATCH_FORWARD(moreGenerators)...);
7428 }
7429 template<typename T>
7430 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
7431 return Generators<T>(CATCH_MOVE(generator));
7432 }
7433 template<typename T, typename... Gs>
7434 auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<std::decay_t<T>> {
7435 return makeGenerators( value( CATCH_FORWARD( val ) ), CATCH_FORWARD( moreGenerators )... );
7436 }
7437 template<typename T, typename U, typename... Gs>
7438 auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
7439 return makeGenerators( value( T( CATCH_FORWARD( val ) ) ), CATCH_FORWARD( moreGenerators )... );
7440 }
7441
7442 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
7443
7444 template<typename L>
7445 // Note: The type after -> is weird, because VS2015 cannot parse
7446 // the expression used in the typedef inside, when it is in
7447 // return type. Yeah.
7448 auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
7449 using UnderlyingType = typename decltype(generatorExpression())::type;
7450
7451 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
7452 if (!tracker.hasGenerator()) {
7453 tracker.setGenerator(Catch::Detail::make_unique<Generators<UnderlyingType>>(generatorExpression()));
7454 }
7455
7456 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
7457 return generator.get();
7458 }
7459
7460 } // namespace Generators
7461 } // namespace Catch
7462
7463 #define GENERATE( ... ) \
7464 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
7465 CATCH_INTERNAL_LINEINFO, \
7466 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
7467 #define GENERATE_COPY( ... ) \
7468 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
7469 CATCH_INTERNAL_LINEINFO, \
7470 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
7471 #define GENERATE_REF( ... ) \
7472 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
7473 CATCH_INTERNAL_LINEINFO, \
7474 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
7475
7476 #endif // CATCH_GENERATORS_HPP_INCLUDED
7477
7478
7479 #ifndef CATCH_GENERATORS_ADAPTERS_HPP_INCLUDED
7480 #define CATCH_GENERATORS_ADAPTERS_HPP_INCLUDED
7481
7482
7483 #include <cassert>
7484
7485 namespace Catch {
7486 namespace Generators {
7487
7488 template <typename T>
7489 class TakeGenerator final : public IGenerator<T> {
7490 GeneratorWrapper<T> m_generator;
7491 size_t m_returned = 0;
7492 size_t m_target;
7493 public:
7494 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
7495 m_generator(CATCH_MOVE(generator)),
7496 m_target(target)
7497 {
7498 assert(target != 0 && "Empty generators are not allowed");
7499 }
7500 T const& get() const override {
7501 return m_generator.get();
7502 }
7503 bool next() override {
7504 ++m_returned;
7505 if (m_returned >= m_target) {
7506 return false;
7507 }
7508
7509 const auto success = m_generator.next();
7510 // If the underlying generator does not contain enough values
7511 // then we cut short as well
7512 if (!success) {
7513 m_returned = m_target;
7514 }
7515 return success;
7516 }
7517 };
7518
7519 template <typename T>
7520 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
7521 return GeneratorWrapper<T>(Catch::Detail::make_unique<TakeGenerator<T>>(target, CATCH_MOVE(generator)));
7522 }
7523
7524
7525 template <typename T, typename Predicate>
7526 class FilterGenerator final : public IGenerator<T> {
7527 GeneratorWrapper<T> m_generator;
7528 Predicate m_predicate;
7529 public:
7530 template <typename P = Predicate>
7531 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
7532 m_generator(CATCH_MOVE(generator)),
7533 m_predicate(CATCH_FORWARD(pred))
7534 {
7535 if (!m_predicate(m_generator.get())) {
7536 // It might happen that there are no values that pass the
7537 // filter. In that case we throw an exception.
7538 auto has_initial_value = next();
7539 if (!has_initial_value) {
7540 Detail::throw_generator_exception("No valid value found in filtered generator");
7541 }
7542 }
7543 }
7544
7545 T const& get() const override {
7546 return m_generator.get();
7547 }
7548
7549 bool next() override {
7550 bool success = m_generator.next();
7551 if (!success) {
7552 return false;
7553 }
7554 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
7555 return success;
7556 }
7557 };
7558
7559
7560 template <typename T, typename Predicate>
7561 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
7562 return GeneratorWrapper<T>(Catch::Detail::make_unique<FilterGenerator<T, Predicate>>(CATCH_FORWARD(pred), CATCH_MOVE(generator)));
7563 }
7564
7565 template <typename T>
7566 class RepeatGenerator final : public IGenerator<T> {
7567 static_assert(!std::is_same<T, bool>::value,
7568 "RepeatGenerator currently does not support bools"
7569 "because of std::vector<bool> specialization");
7570 GeneratorWrapper<T> m_generator;
7571 mutable std::vector<T> m_returned;
7572 size_t m_target_repeats;
7573 size_t m_current_repeat = 0;
7574 size_t m_repeat_index = 0;
7575 public:
7576 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
7577 m_generator(CATCH_MOVE(generator)),
7578 m_target_repeats(repeats)
7579 {
7580 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
7581 }
7582
7583 T const& get() const override {
7584 if (m_current_repeat == 0) {
7585 m_returned.push_back(m_generator.get());
7586 return m_returned.back();
7587 }
7588 return m_returned[m_repeat_index];
7589 }
7590
7591 bool next() override {
7592 // There are 2 basic cases:
7593 // 1) We are still reading the generator
7594 // 2) We are reading our own cache
7595
7596 // In the first case, we need to poke the underlying generator.
7597 // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
7598 if (m_current_repeat == 0) {
7599 const auto success = m_generator.next();
7600 if (!success) {
7601 ++m_current_repeat;
7602 }
7603 return m_current_repeat < m_target_repeats;
7604 }
7605
7606 // In the second case, we need to move indices forward and check that we haven't run up against the end
7607 ++m_repeat_index;
7608 if (m_repeat_index == m_returned.size()) {
7609 m_repeat_index = 0;
7610 ++m_current_repeat;
7611 }
7612 return m_current_repeat < m_target_repeats;
7613 }
7614 };
7615
7616 template <typename T>
7617 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
7618 return GeneratorWrapper<T>(Catch::Detail::make_unique<RepeatGenerator<T>>(repeats, CATCH_MOVE(generator)));
7619 }
7620
7621 template <typename T, typename U, typename Func>
7622 class MapGenerator final : public IGenerator<T> {
7623 // TBD: provide static assert for mapping function, for friendly error message
7624 GeneratorWrapper<U> m_generator;
7625 Func m_function;
7626 // To avoid returning dangling reference, we have to save the values
7627 T m_cache;
7628 public:
7629 template <typename F2 = Func>
7630 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
7631 m_generator(CATCH_MOVE(generator)),
7632 m_function(CATCH_FORWARD(function)),
7633 m_cache(m_function(m_generator.get()))
7634 {}
7635
7636 T const& get() const override {
7637 return m_cache;
7638 }
7639 bool next() override {
7640 const auto success = m_generator.next();
7641 if (success) {
7642 m_cache = m_function(m_generator.get());
7643 }
7644 return success;
7645 }
7646 };
7647
7648 template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
7649 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
7650 return GeneratorWrapper<T>(
7651 Catch::Detail::make_unique<MapGenerator<T, U, Func>>(CATCH_FORWARD(function), CATCH_MOVE(generator))
7652 );
7653 }
7654
7655 template <typename T, typename U, typename Func>
7656 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
7657 return GeneratorWrapper<T>(
7658 Catch::Detail::make_unique<MapGenerator<T, U, Func>>(CATCH_FORWARD(function), CATCH_MOVE(generator))
7659 );
7660 }
7661
7662 template <typename T>
7663 class ChunkGenerator final : public IGenerator<std::vector<T>> {
7664 std::vector<T> m_chunk;
7665 size_t m_chunk_size;
7666 GeneratorWrapper<T> m_generator;
7667 bool m_used_up = false;
7668 public:
7669 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
7670 m_chunk_size(size), m_generator(CATCH_MOVE(generator))
7671 {
7672 m_chunk.reserve(m_chunk_size);
7673 if (m_chunk_size != 0) {
7674 m_chunk.push_back(m_generator.get());
7675 for (size_t i = 1; i < m_chunk_size; ++i) {
7676 if (!m_generator.next()) {
7677 Detail::throw_generator_exception("Not enough values to initialize the first chunk");
7678 }
7679 m_chunk.push_back(m_generator.get());
7680 }
7681 }
7682 }
7683 std::vector<T> const& get() const override {
7684 return m_chunk;
7685 }
7686 bool next() override {
7687 m_chunk.clear();
7688 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
7689 if (!m_generator.next()) {
7690 return false;
7691 }
7692 m_chunk.push_back(m_generator.get());
7693 }
7694 return true;
7695 }
7696 };
7697
7698 template <typename T>
7699 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
7700 return GeneratorWrapper<std::vector<T>>(
7701 Catch::Detail::make_unique<ChunkGenerator<T>>(size, CATCH_MOVE(generator))
7702 );
7703 }
7704
7705 } // namespace Generators
7706 } // namespace Catch
7707
7708
7709 #endif // CATCH_GENERATORS_ADAPTERS_HPP_INCLUDED
7710
7711
7712 #ifndef CATCH_GENERATORS_RANDOM_HPP_INCLUDED
7713 #define CATCH_GENERATORS_RANDOM_HPP_INCLUDED
7714
7715
7716
7717 #ifndef CATCH_RANDOM_NUMBER_GENERATOR_HPP_INCLUDED
7718 #define CATCH_RANDOM_NUMBER_GENERATOR_HPP_INCLUDED
7719
7720 #include <cstdint>
7721
7722 namespace Catch {
7723
7724 // This is a simple implementation of C++11 Uniform Random Number
7725 // Generator. It does not provide all operators, because Catch2
7726 // does not use it, but it should behave as expected inside stdlib's
7727 // distributions.
7728 // The implementation is based on the PCG family (http://pcg-random.org)
7729 class SimplePcg32 {
7730 using state_type = std::uint64_t;
7731 public:
7732 using result_type = std::uint32_t;
7733 static constexpr result_type (min)() {
7734 return 0;
7735 }
7736 static constexpr result_type (max)() {
7737 return static_cast<result_type>(-1);
7738 }
7739
7740 // Provide some default initial state for the default constructor
7741 SimplePcg32():SimplePcg32(0xed743cc4U) {}
7742
7743 explicit SimplePcg32(result_type seed_);
7744
7745 void seed(result_type seed_);
7746 void discard(uint64_t skip);
7747
7748 result_type operator()();
7749
7750 private:
7751 friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
7752 friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
7753
7754 // In theory we also need operator<< and operator>>
7755 // In practice we do not use them, so we will skip them for now
7756
7757
7758 std::uint64_t m_state;
7759 // This part of the state determines which "stream" of the numbers
7760 // is chosen -- we take it as a constant for Catch2, so we only
7761 // need to deal with seeding the main state.
7762 // Picked by reading 8 bytes from `/dev/random` :-)
7763 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
7764 };
7765
7766 } // end namespace Catch
7767
7768 #endif // CATCH_RANDOM_NUMBER_GENERATOR_HPP_INCLUDED
7769
7770 #include <random>
7771
7772 namespace Catch {
7773 namespace Generators {
7774 namespace Detail {
7775 // Returns a suitable seed for a random floating generator based off
7776 // the primary internal rng. It does so by taking current value from
7777 // the rng and returning it as the seed.
7778 std::uint32_t getSeed();
7779 }
7780
7781 template <typename Float>
7782 class RandomFloatingGenerator final : public IGenerator<Float> {
7783 Catch::SimplePcg32 m_rng;
7784 std::uniform_real_distribution<Float> m_dist;
7785 Float m_current_number;
7786 public:
7787 RandomFloatingGenerator( Float a, Float b, std::uint32_t seed ):
7788 m_rng(seed),
7789 m_dist(a, b) {
7790 static_cast<void>(next());
7791 }
7792
7793 Float const& get() const override {
7794 return m_current_number;
7795 }
7796 bool next() override {
7797 m_current_number = m_dist(m_rng);
7798 return true;
7799 }
7800 };
7801
7802 template <typename Integer>
7803 class RandomIntegerGenerator final : public IGenerator<Integer> {
7804 Catch::SimplePcg32 m_rng;
7805 std::uniform_int_distribution<Integer> m_dist;
7806 Integer m_current_number;
7807 public:
7808 RandomIntegerGenerator( Integer a, Integer b, std::uint32_t seed ):
7809 m_rng(seed),
7810 m_dist(a, b) {
7811 static_cast<void>(next());
7812 }
7813
7814 Integer const& get() const override {
7815 return m_current_number;
7816 }
7817 bool next() override {
7818 m_current_number = m_dist(m_rng);
7819 return true;
7820 }
7821 };
7822
7823 template <typename T>
7824 std::enable_if_t<std::is_integral<T>::value, GeneratorWrapper<T>>
7825 random(T a, T b) {
7826 static_assert(
7827 !std::is_same<T, char>::value &&
7828 !std::is_same<T, int8_t>::value &&
7829 !std::is_same<T, uint8_t>::value &&
7830 !std::is_same<T, signed char>::value &&
7831 !std::is_same<T, unsigned char>::value &&
7832 !std::is_same<T, bool>::value,
7833 "The requested type is not supported by the underlying random distributions from std" );
7834 return GeneratorWrapper<T>(
7835 Catch::Detail::make_unique<RandomIntegerGenerator<T>>(a, b, Detail::getSeed())
7836 );
7837 }
7838
7839 template <typename T>
7840 std::enable_if_t<std::is_floating_point<T>::value,
7841 GeneratorWrapper<T>>
7842 random(T a, T b) {
7843 return GeneratorWrapper<T>(
7844 Catch::Detail::make_unique<RandomFloatingGenerator<T>>(a, b, Detail::getSeed())
7845 );
7846 }
7847
7848
7849 } // namespace Generators
7850 } // namespace Catch
7851
7852
7853 #endif // CATCH_GENERATORS_RANDOM_HPP_INCLUDED
7854
7855
7856 #ifndef CATCH_GENERATORS_RANGE_HPP_INCLUDED
7857 #define CATCH_GENERATORS_RANGE_HPP_INCLUDED
7858
7859
7860 #include <iterator>
7861 #include <type_traits>
7862
7863 namespace Catch {
7864 namespace Generators {
7865
7866
7867 template <typename T>
7868 class RangeGenerator final : public IGenerator<T> {
7869 T m_current;
7870 T m_end;
7871 T m_step;
7872 bool m_positive;
7873
7874 public:
7875 RangeGenerator(T const& start, T const& end, T const& step):
7876 m_current(start),
7877 m_end(end),
7878 m_step(step),
7879 m_positive(m_step > T(0))
7880 {
7881 assert(m_current != m_end && "Range start and end cannot be equal");
7882 assert(m_step != T(0) && "Step size cannot be zero");
7883 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
7884 }
7885
7886 RangeGenerator(T const& start, T const& end):
7887 RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
7888 {}
7889
7890 T const& get() const override {
7891 return m_current;
7892 }
7893
7894 bool next() override {
7895 m_current += m_step;
7896 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
7897 }
7898 };
7899
7900 template <typename T>
7901 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
7902 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
7903 return GeneratorWrapper<T>(Catch::Detail::make_unique<RangeGenerator<T>>(start, end, step));
7904 }
7905
7906 template <typename T>
7907 GeneratorWrapper<T> range(T const& start, T const& end) {
7908 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
7909 return GeneratorWrapper<T>(Catch::Detail::make_unique<RangeGenerator<T>>(start, end));
7910 }
7911
7912
7913 template <typename T>
7914 class IteratorGenerator final : public IGenerator<T> {
7915 static_assert(!std::is_same<T, bool>::value,
7916 "IteratorGenerator currently does not support bools"
7917 "because of std::vector<bool> specialization");
7918
7919 std::vector<T> m_elems;
7920 size_t m_current = 0;
7921 public:
7922 template <typename InputIterator, typename InputSentinel>
7923 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
7924 if (m_elems.empty()) {
7925 Detail::throw_generator_exception("IteratorGenerator received no valid values");
7926 }
7927 }
7928
7929 T const& get() const override {
7930 return m_elems[m_current];
7931 }
7932
7933 bool next() override {
7934 ++m_current;
7935 return m_current != m_elems.size();
7936 }
7937 };
7938
7939 template <typename InputIterator,
7940 typename InputSentinel,
7941 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
7942 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
7943 return GeneratorWrapper<ResultType>(Catch::Detail::make_unique<IteratorGenerator<ResultType>>(from, to));
7944 }
7945
7946 template <typename Container,
7947 typename ResultType = typename Container::value_type>
7948 GeneratorWrapper<ResultType> from_range(Container const& cnt) {
7949 return GeneratorWrapper<ResultType>(Catch::Detail::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
7950 }
7951
7952
7953 } // namespace Generators
7954 } // namespace Catch
7955
7956
7957 #endif // CATCH_GENERATORS_RANGE_HPP_INCLUDED
7958
7959 #endif // CATCH_GENERATORS_ALL_HPP_INCLUDED
7960
7961
7962 /** \file
7963 * This is a convenience header for Catch2's interfaces. It includes
7964 * **all** of Catch2 headers related to interfaces.
7965 *
7966 * Generally the Catch2 users should use specific includes they need,
7967 * but this header can be used instead for ease-of-experimentation, or
7968 * just plain convenience, at the cost of somewhat increased compilation
7969 * times.
7970 *
7971 * When a new header is added to either the `interfaces` folder, or to
7972 * the corresponding internal subfolder, it should be added here.
7973 */
7974
7975
7976 #ifndef CATCH_INTERFACES_ALL_HPP_INCLUDED
7977 #define CATCH_INTERFACES_ALL_HPP_INCLUDED
7978
7979
7980
7981 #ifndef CATCH_INTERFACES_REPORTER_FACTORY_HPP_INCLUDED
7982 #define CATCH_INTERFACES_REPORTER_FACTORY_HPP_INCLUDED
7983
7984
7985 #include <string>
7986
7987 namespace Catch {
7988
7989 struct ReporterConfig;
7990 class IConfig;
7991 class IEventListener;
7992 using IEventListenerPtr = Detail::unique_ptr<IEventListener>;
7993
7994
7995 class IReporterFactory {
7996 public:
7997 virtual ~IReporterFactory(); // = default
7998
7999 virtual IEventListenerPtr
8000 create( ReporterConfig&& config ) const = 0;
8001 virtual std::string getDescription() const = 0;
8002 };
8003 using IReporterFactoryPtr = Detail::unique_ptr<IReporterFactory>;
8004
8005 class EventListenerFactory {
8006 public:
8007 virtual ~EventListenerFactory(); // = default
8008 virtual IEventListenerPtr create( IConfig const* config ) const = 0;
8009 //! Return a meaningful name for the listener, e.g. its type name
8010 virtual StringRef getName() const = 0;
8011 //! Return listener's description if available
8012 virtual std::string getDescription() const = 0;
8013 };
8014 } // namespace Catch
8015
8016 #endif // CATCH_INTERFACES_REPORTER_FACTORY_HPP_INCLUDED
8017
8018
8019 #ifndef CATCH_INTERFACES_REPORTER_REGISTRY_HPP_INCLUDED
8020 #define CATCH_INTERFACES_REPORTER_REGISTRY_HPP_INCLUDED
8021
8022
8023
8024 #ifndef CATCH_CASE_INSENSITIVE_COMPARISONS_HPP_INCLUDED
8025 #define CATCH_CASE_INSENSITIVE_COMPARISONS_HPP_INCLUDED
8026
8027
8028 namespace Catch {
8029 namespace Detail {
8030 //! Provides case-insensitive `op<` semantics when called
8031 struct CaseInsensitiveLess {
8032 bool operator()( StringRef lhs,
8033 StringRef rhs ) const;
8034 };
8035
8036 //! Provides case-insensitive `op==` semantics when called
8037 struct CaseInsensitiveEqualTo {
8038 bool operator()( StringRef lhs,
8039 StringRef rhs ) const;
8040 };
8041
8042 } // namespace Detail
8043 } // namespace Catch
8044
8045 #endif // CATCH_CASE_INSENSITIVE_COMPARISONS_HPP_INCLUDED
8046
8047 #include <string>
8048 #include <vector>
8049 #include <map>
8050
8051 namespace Catch {
8052
8053 class IConfig;
8054
8055 class IEventListener;
8056 using IEventListenerPtr = Detail::unique_ptr<IEventListener>;
8057 class IReporterFactory;
8058 using IReporterFactoryPtr = Detail::unique_ptr<IReporterFactory>;
8059 struct ReporterConfig;
8060 class EventListenerFactory;
8061
8062 class IReporterRegistry {
8063 public:
8064 using FactoryMap = std::map<std::string, IReporterFactoryPtr, Detail::CaseInsensitiveLess>;
8065 using Listeners = std::vector<Detail::unique_ptr<EventListenerFactory>>;
8066
8067 virtual ~IReporterRegistry(); // = default
8068 virtual IEventListenerPtr create( std::string const& name, ReporterConfig&& config ) const = 0;
8069 virtual FactoryMap const& getFactories() const = 0;
8070 virtual Listeners const& getListeners() const = 0;
8071 };
8072
8073 } // end namespace Catch
8074
8075 #endif // CATCH_INTERFACES_REPORTER_REGISTRY_HPP_INCLUDED
8076
8077
8078 #ifndef CATCH_INTERFACES_TAG_ALIAS_REGISTRY_HPP_INCLUDED
8079 #define CATCH_INTERFACES_TAG_ALIAS_REGISTRY_HPP_INCLUDED
8080
8081 #include <string>
8082
8083 namespace Catch {
8084
8085 struct TagAlias;
8086
8087 class ITagAliasRegistry {
8088 public:
8089 virtual ~ITagAliasRegistry(); // = default
8090 // Nullptr if not present
8091 virtual TagAlias const* find( std::string const& alias ) const = 0;
8092 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
8093
8094 static ITagAliasRegistry const& get();
8095 };
8096
8097 } // end namespace Catch
8098
8099 #endif // CATCH_INTERFACES_TAG_ALIAS_REGISTRY_HPP_INCLUDED
8100
8101 #endif // CATCH_INTERFACES_ALL_HPP_INCLUDED
8102
8103
8104
8105 /** \file
8106 * Wrapper for ANDROID_LOGWRITE configuration option
8107 *
8108 * We want to default to enabling it when compiled for android, but
8109 * users of the library should also be able to disable it if they want
8110 * to.
8111 */
8112
8113 #ifndef CATCH_CONFIG_ANDROID_LOGWRITE_HPP_INCLUDED
8114 #define CATCH_CONFIG_ANDROID_LOGWRITE_HPP_INCLUDED
8115
8116
8117 #if defined(__ANDROID__)
8118 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
8119 #endif
8120
8121
8122 #if defined( CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE ) && \
8123 !defined( CATCH_CONFIG_NO_ANDROID_LOGWRITE ) && \
8124 !defined( CATCH_CONFIG_ANDROID_LOGWRITE )
8125 # define CATCH_CONFIG_ANDROID_LOGWRITE
8126 #endif
8127
8128 #endif // CATCH_CONFIG_ANDROID_LOGWRITE_HPP_INCLUDED
8129
8130
8131
8132 /** \file
8133 * Wrapper for UNCAUGHT_EXCEPTIONS configuration option
8134 *
8135 * For some functionality, Catch2 requires to know whether there is
8136 * an active exception. Because `std::uncaught_exception` is deprecated
8137 * in C++17, we want to use `std::uncaught_exceptions` if possible.
8138 */
8139
8140 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
8141 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
8142
8143 #if defined(_MSC_VER)
8144 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
8145 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
8146 # endif
8147 #endif
8148
8149
8150 #include <exception>
8151
8152 #if defined(__cpp_lib_uncaught_exceptions) \
8153 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
8154
8155 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
8156 #endif // __cpp_lib_uncaught_exceptions
8157
8158
8159 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
8160 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
8161 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
8162
8163 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
8164 #endif
8165
8166
8167 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
8168
8169
8170 #ifndef CATCH_CONSOLE_WIDTH_HPP_INCLUDED
8171 #define CATCH_CONSOLE_WIDTH_HPP_INCLUDED
8172
8173 // This include must be kept so that user's configured value for CONSOLE_WIDTH
8174 // is used before we attempt to provide a default value
8175
8176 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
8177 #define CATCH_CONFIG_CONSOLE_WIDTH 80
8178 #endif
8179
8180 #endif // CATCH_CONSOLE_WIDTH_HPP_INCLUDED
8181
8182
8183 #ifndef CATCH_CONTAINER_NONMEMBERS_HPP_INCLUDED
8184 #define CATCH_CONTAINER_NONMEMBERS_HPP_INCLUDED
8185
8186
8187 #include <cstddef>
8188 #include <initializer_list>
8189
8190 // We want a simple polyfill over `std::empty`, `std::size` and so on
8191 // for C++14 or C++ libraries with incomplete support.
8192 // We also have to handle that MSVC std lib will happily provide these
8193 // under older standards.
8194 #if defined(CATCH_CPP17_OR_GREATER) || defined(_MSC_VER)
8195
8196 // We are already using this header either way, so there shouldn't
8197 // be much additional overhead in including it to get the feature
8198 // test macros
8199 #include <string>
8200
8201 # if !defined(__cpp_lib_nonmember_container_access)
8202 # define CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS
8203 # endif
8204
8205 #else
8206 #define CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS
8207 #endif
8208
8209
8210
8211 namespace Catch {
8212 namespace Detail {
8213
8214 #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS)
8215 template <typename Container>
8216 constexpr auto empty(Container const& cont) -> decltype(cont.empty()) {
8217 return cont.empty();
8218 }
8219 template <typename T, std::size_t N>
8220 constexpr bool empty(const T (&)[N]) noexcept {
8221 // GCC < 7 does not support the const T(&)[] parameter syntax
8222 // so we have to ignore the length explicitly
8223 (void)N;
8224 return false;
8225 }
8226 template <typename T>
8227 constexpr bool empty(std::initializer_list<T> list) noexcept {
8228 return list.size() > 0;
8229 }
8230
8231
8232 template <typename Container>
8233 constexpr auto size(Container const& cont) -> decltype(cont.size()) {
8234 return cont.size();
8235 }
8236 template <typename T, std::size_t N>
8237 constexpr std::size_t size(const T(&)[N]) noexcept {
8238 return N;
8239 }
8240 #endif // CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS
8241
8242 } // end namespace Detail
8243 } // end namespace Catch
8244
8245
8246
8247 #endif // CATCH_CONTAINER_NONMEMBERS_HPP_INCLUDED
8248
8249
8250 #ifndef CATCH_DEBUG_CONSOLE_HPP_INCLUDED
8251 #define CATCH_DEBUG_CONSOLE_HPP_INCLUDED
8252
8253 #include <string>
8254
8255 namespace Catch {
8256 void writeToDebugConsole( std::string const& text );
8257 }
8258
8259 #endif // CATCH_DEBUG_CONSOLE_HPP_INCLUDED
8260
8261
8262 #ifndef CATCH_DEBUGGER_HPP_INCLUDED
8263 #define CATCH_DEBUGGER_HPP_INCLUDED
8264
8265
8266 namespace Catch {
8267 bool isDebuggerActive();
8268 }
8269
8270 #ifdef CATCH_PLATFORM_MAC
8271
8272 #if defined(__i386__) || defined(__x86_64__)
8273 #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
8274 #elif defined(__aarch64__)
8275 #define CATCH_TRAP() __asm__(".inst 0xd43e0000")
8276 #endif
8277
8278 #elif defined(CATCH_PLATFORM_IPHONE)
8279
8280 // use inline assembler
8281 #if defined(__i386__) || defined(__x86_64__)
8282 #define CATCH_TRAP() __asm__("int $3")
8283 #elif defined(__aarch64__)
8284 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8285 #elif defined(__arm__) && !defined(__thumb__)
8286 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
8287 #elif defined(__arm__) && defined(__thumb__)
8288 #define CATCH_TRAP() __asm__(".inst 0xde01")
8289 #endif
8290
8291 #elif defined(CATCH_PLATFORM_LINUX)
8292 // If we can use inline assembler, do it because this allows us to break
8293 // directly at the location of the failing check instead of breaking inside
8294 // raise() called from it, i.e. one stack frame below.
8295 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
8296 #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
8297 #else // Fall back to the generic way.
8298 #include <signal.h>
8299
8300 #define CATCH_TRAP() raise(SIGTRAP)
8301 #endif
8302 #elif defined(_MSC_VER)
8303 #define CATCH_TRAP() __debugbreak()
8304 #elif defined(__MINGW32__)
8305 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
8306 #define CATCH_TRAP() DebugBreak()
8307 #endif
8308
8309 #ifndef CATCH_BREAK_INTO_DEBUGGER
8310 #ifdef CATCH_TRAP
8311 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
8312 #else
8313 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
8314 #endif
8315 #endif
8316
8317 #endif // CATCH_DEBUGGER_HPP_INCLUDED
8318
8319
8320 #ifndef CATCH_ENFORCE_HPP_INCLUDED
8321 #define CATCH_ENFORCE_HPP_INCLUDED
8322
8323
8324 #include <exception>
8325
8326 namespace Catch {
8327 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8328 template <typename Ex>
8329 [[noreturn]]
8330 void throw_exception(Ex const& e) {
8331 throw e;
8332 }
8333 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
8334 [[noreturn]]
8335 void throw_exception(std::exception const& e);
8336 #endif
8337
8338 [[noreturn]]
8339 void throw_logic_error(std::string const& msg);
8340 [[noreturn]]
8341 void throw_domain_error(std::string const& msg);
8342 [[noreturn]]
8343 void throw_runtime_error(std::string const& msg);
8344
8345 } // namespace Catch;
8346
8347 #define CATCH_MAKE_MSG(...) \
8348 (Catch::ReusableStringStream() << __VA_ARGS__).str()
8349
8350 #define CATCH_INTERNAL_ERROR(...) \
8351 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
8352
8353 #define CATCH_ERROR(...) \
8354 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
8355
8356 #define CATCH_RUNTIME_ERROR(...) \
8357 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
8358
8359 #define CATCH_ENFORCE( condition, ... ) \
8360 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
8361
8362
8363 #endif // CATCH_ENFORCE_HPP_INCLUDED
8364
8365
8366 #ifndef CATCH_ENUM_VALUES_REGISTRY_HPP_INCLUDED
8367 #define CATCH_ENUM_VALUES_REGISTRY_HPP_INCLUDED
8368
8369
8370 #include <vector>
8371
8372 namespace Catch {
8373
8374 namespace Detail {
8375
8376 Catch::Detail::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
8377
8378 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
8379
8380 std::vector<Catch::Detail::unique_ptr<EnumInfo>> m_enumInfos;
8381
8382 EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
8383 };
8384
8385 std::vector<StringRef> parseEnums( StringRef enums );
8386
8387 } // Detail
8388
8389 } // Catch
8390
8391 #endif // CATCH_ENUM_VALUES_REGISTRY_HPP_INCLUDED
8392
8393
8394 #ifndef CATCH_ERRNO_GUARD_HPP_INCLUDED
8395 #define CATCH_ERRNO_GUARD_HPP_INCLUDED
8396
8397 namespace Catch {
8398
8399 //! Simple RAII class that stores the value of `errno`
8400 //! at construction and restores it at destruction.
8401 class ErrnoGuard {
8402 public:
8403 // Keep these outlined to avoid dragging in macros from <cerrno>
8404
8405 ErrnoGuard();
8406 ~ErrnoGuard();
8407 private:
8408 int m_oldErrno;
8409 };
8410
8411 }
8412
8413 #endif // CATCH_ERRNO_GUARD_HPP_INCLUDED
8414
8415
8416 #ifndef CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
8417 #define CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
8418
8419
8420 #include <vector>
8421 #include <string>
8422
8423 namespace Catch {
8424
8425 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
8426 public:
8427 ~ExceptionTranslatorRegistry() override;
8428 void registerTranslator( Detail::unique_ptr<IExceptionTranslator>&& translator );
8429 std::string translateActiveException() const override;
8430 std::string tryTranslators() const;
8431
8432 private:
8433 ExceptionTranslators m_translators;
8434 };
8435 }
8436
8437 #endif // CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
8438
8439
8440 #ifndef CATCH_FATAL_CONDITION_HANDLER_HPP_INCLUDED
8441 #define CATCH_FATAL_CONDITION_HANDLER_HPP_INCLUDED
8442
8443
8444 #include <cassert>
8445
8446 namespace Catch {
8447
8448 /**
8449 * Wrapper for platform-specific fatal error (signals/SEH) handlers
8450 *
8451 * Tries to be cooperative with other handlers, and not step over
8452 * other handlers. This means that unknown structured exceptions
8453 * are passed on, previous signal handlers are called, and so on.
8454 *
8455 * Can only be instantiated once, and assumes that once a signal
8456 * is caught, the binary will end up terminating. Thus, there
8457 */
8458 class FatalConditionHandler {
8459 bool m_started = false;
8460
8461 // Install/disengage implementation for specific platform.
8462 // Should be if-defed to work on current platform, can assume
8463 // engage-disengage 1:1 pairing.
8464 void engage_platform();
8465 void disengage_platform() noexcept;
8466 public:
8467 // Should also have platform-specific implementations as needed
8468 FatalConditionHandler();
8469 ~FatalConditionHandler();
8470
8471 void engage() {
8472 assert(!m_started && "Handler cannot be installed twice.");
8473 m_started = true;
8474 engage_platform();
8475 }
8476
8477 void disengage() noexcept {
8478 assert(m_started && "Handler cannot be uninstalled without being installed first");
8479 m_started = false;
8480 disengage_platform();
8481 }
8482 };
8483
8484 //! Simple RAII guard for (dis)engaging the FatalConditionHandler
8485 class FatalConditionHandlerGuard {
8486 FatalConditionHandler* m_handler;
8487 public:
8488 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8489 m_handler(handler) {
8490 m_handler->engage();
8491 }
8492 ~FatalConditionHandlerGuard() {
8493 m_handler->disengage();
8494 }
8495 };
8496
8497 } // end namespace Catch
8498
8499 #endif // CATCH_FATAL_CONDITION_HANDLER_HPP_INCLUDED
8500
8501
8502 #ifndef CATCH_FLOATING_POINT_HELPERS_HPP_INCLUDED
8503 #define CATCH_FLOATING_POINT_HELPERS_HPP_INCLUDED
8504
8505
8506
8507 #ifndef CATCH_POLYFILLS_HPP_INCLUDED
8508 #define CATCH_POLYFILLS_HPP_INCLUDED
8509
8510 namespace Catch {
8511 bool isnan(float f);
8512 bool isnan(double d);
8513 }
8514
8515 #endif // CATCH_POLYFILLS_HPP_INCLUDED
8516
8517 #include <cassert>
8518 #include <cmath>
8519 #include <cstdint>
8520 #include <utility>
8521 #include <limits>
8522
8523 namespace Catch {
8524 namespace Detail {
8525
8526 uint32_t convertToBits(float f);
8527 uint64_t convertToBits(double d);
8528
8529 } // end namespace Detail
8530
8531
8532
8533 #if defined( __GNUC__ ) || defined( __clang__ )
8534 # pragma GCC diagnostic push
8535 // We do a bunch of direct compensations of floating point numbers,
8536 // because we know what we are doing and actually do want the direct
8537 // comparison behaviour.
8538 # pragma GCC diagnostic ignored "-Wfloat-equal"
8539 #endif
8540
8541 /**
8542 * Calculates the ULP distance between two floating point numbers
8543 *
8544 * The ULP distance of two floating point numbers is the count of
8545 * valid floating point numbers representable between them.
8546 *
8547 * There are some exceptions between how this function counts the
8548 * distance, and the interpretation of the standard as implemented.
8549 * by e.g. `nextafter`. For this function it always holds that:
8550 * * `(x == y) => ulpDistance(x, y) == 0` (so `ulpDistance(-0, 0) == 0`)
8551 * * `ulpDistance(maxFinite, INF) == 1`
8552 * * `ulpDistance(x, -x) == 2 * ulpDistance(x, 0)`
8553 *
8554 * \pre `!isnan( lhs )`
8555 * \pre `!isnan( rhs )`
8556 * \pre floating point numbers are represented in IEEE-754 format
8557 */
8558 template <typename FP>
8559 uint64_t ulpDistance( FP lhs, FP rhs ) {
8560 assert( std::numeric_limits<FP>::is_iec559 &&
8561 "ulpDistance assumes IEEE-754 format for floating point types" );
8562 assert( !Catch::isnan( lhs ) &&
8563 "Distance between NaN and number is not meaningful" );
8564 assert( !Catch::isnan( rhs ) &&
8565 "Distance between NaN and number is not meaningful" );
8566
8567 // We want X == Y to imply 0 ULP distance even if X and Y aren't
8568 // bit-equal (-0 and 0), or X - Y != 0 (same sign infinities).
8569 if ( lhs == rhs ) { return 0; }
8570
8571 // We need a properly typed positive zero for type inference.
8572 static constexpr FP positive_zero{};
8573
8574 // We want to ensure that +/- 0 is always represented as positive zero
8575 if ( lhs == positive_zero ) { lhs = positive_zero; }
8576 if ( rhs == positive_zero ) { rhs = positive_zero; }
8577
8578 // If arguments have different signs, we can handle them by summing
8579 // how far are they from 0 each.
8580 if ( std::signbit( lhs ) != std::signbit( rhs ) ) {
8581 return ulpDistance( std::abs( lhs ), positive_zero ) +
8582 ulpDistance( std::abs( rhs ), positive_zero );
8583 }
8584
8585 // When both lhs and rhs are of the same sign, we can just
8586 // read the numbers bitwise as integers, and then subtract them
8587 // (assuming IEEE).
8588 uint64_t lc = Detail::convertToBits( lhs );
8589 uint64_t rc = Detail::convertToBits( rhs );
8590
8591 // The ulp distance between two numbers is symmetric, so to avoid
8592 // dealing with overflows we want the bigger converted number on the lhs
8593 if ( lc < rc ) {
8594 std::swap( lc, rc );
8595 }
8596
8597 return lc - rc;
8598 }
8599
8600 #if defined( __GNUC__ ) || defined( __clang__ )
8601 # pragma GCC diagnostic pop
8602 #endif
8603
8604
8605 } // end namespace Catch
8606
8607 #endif // CATCH_FLOATING_POINT_HELPERS_HPP_INCLUDED
8608
8609
8610 #ifndef CATCH_ISTREAM_HPP_INCLUDED
8611 #define CATCH_ISTREAM_HPP_INCLUDED
8612
8613
8614 #include <iosfwd>
8615 #include <cstddef>
8616 #include <ostream>
8617 #include <string>
8618
8619 namespace Catch {
8620
8621 class IStream {
8622 public:
8623 virtual ~IStream(); // = default
8624 virtual std::ostream& stream() = 0;
8625 /**
8626 * Best guess on whether the instance is writing to a console (e.g. via stdout/stderr)
8627 *
8628 * This is useful for e.g. Win32 colour support, because the Win32
8629 * API manipulates console directly, unlike POSIX escape codes,
8630 * that can be written anywhere.
8631 *
8632 * Due to variety of ways to change where the stdout/stderr is
8633 * _actually_ being written, users should always assume that
8634 * the answer might be wrong.
8635 */
8636 virtual bool isConsole() const { return false; }
8637 };
8638
8639 /**
8640 * Creates a stream wrapper that writes to specific file.
8641 *
8642 * Also recognizes 4 special filenames
8643 * * `-` for stdout
8644 * * `%stdout` for stdout
8645 * * `%stderr` for stderr
8646 * * `%debug` for platform specific debugging output
8647 *
8648 * \throws if passed an unrecognized %-prefixed stream
8649 */
8650 auto makeStream( std::string const& filename ) -> Detail::unique_ptr<IStream>;
8651
8652 }
8653
8654 #endif // CATCH_STREAM_HPP_INCLUDED
8655
8656
8657 #ifndef CATCH_LEAK_DETECTOR_HPP_INCLUDED
8658 #define CATCH_LEAK_DETECTOR_HPP_INCLUDED
8659
8660 namespace Catch {
8661
8662 struct LeakDetector {
8663 LeakDetector();
8664 ~LeakDetector();
8665 };
8666
8667 }
8668 #endif // CATCH_LEAK_DETECTOR_HPP_INCLUDED
8669
8670
8671 #ifndef CATCH_LIST_HPP_INCLUDED
8672 #define CATCH_LIST_HPP_INCLUDED
8673
8674
8675 #include <set>
8676 #include <string>
8677
8678
8679 namespace Catch {
8680
8681 class IEventListener;
8682 class Config;
8683
8684
8685 struct ReporterDescription {
8686 std::string name, description;
8687 };
8688 struct ListenerDescription {
8689 StringRef name;
8690 std::string description;
8691 };
8692
8693 struct TagInfo {
8694 void add(StringRef spelling);
8695 std::string all() const;
8696
8697 std::set<StringRef> spellings;
8698 std::size_t count = 0;
8699 };
8700
8701 bool list( IEventListener& reporter, Config const& config );
8702
8703 } // end namespace Catch
8704
8705 #endif // CATCH_LIST_HPP_INCLUDED
8706
8707
8708 #ifndef CATCH_OUTPUT_REDIRECT_HPP_INCLUDED
8709 #define CATCH_OUTPUT_REDIRECT_HPP_INCLUDED
8710
8711
8712 #include <cstdio>
8713 #include <iosfwd>
8714 #include <string>
8715
8716 namespace Catch {
8717
8718 class RedirectedStream {
8719 std::ostream& m_originalStream;
8720 std::ostream& m_redirectionStream;
8721 std::streambuf* m_prevBuf;
8722
8723 public:
8724 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
8725 ~RedirectedStream();
8726 };
8727
8728 class RedirectedStdOut {
8729 ReusableStringStream m_rss;
8730 RedirectedStream m_cout;
8731 public:
8732 RedirectedStdOut();
8733 auto str() const -> std::string;
8734 };
8735
8736 // StdErr has two constituent streams in C++, std::cerr and std::clog
8737 // This means that we need to redirect 2 streams into 1 to keep proper
8738 // order of writes
8739 class RedirectedStdErr {
8740 ReusableStringStream m_rss;
8741 RedirectedStream m_cerr;
8742 RedirectedStream m_clog;
8743 public:
8744 RedirectedStdErr();
8745 auto str() const -> std::string;
8746 };
8747
8748 class RedirectedStreams {
8749 public:
8750 RedirectedStreams(RedirectedStreams const&) = delete;
8751 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
8752 RedirectedStreams(RedirectedStreams&&) = delete;
8753 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
8754
8755 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
8756 ~RedirectedStreams();
8757 private:
8758 std::string& m_redirectedCout;
8759 std::string& m_redirectedCerr;
8760 RedirectedStdOut m_redirectedStdOut;
8761 RedirectedStdErr m_redirectedStdErr;
8762 };
8763
8764 #if defined(CATCH_CONFIG_NEW_CAPTURE)
8765
8766 // Windows's implementation of std::tmpfile is terrible (it tries
8767 // to create a file inside system folder, thus requiring elevated
8768 // privileges for the binary), so we have to use tmpnam(_s) and
8769 // create the file ourselves there.
8770 class TempFile {
8771 public:
8772 TempFile(TempFile const&) = delete;
8773 TempFile& operator=(TempFile const&) = delete;
8774 TempFile(TempFile&&) = delete;
8775 TempFile& operator=(TempFile&&) = delete;
8776
8777 TempFile();
8778 ~TempFile();
8779
8780 std::FILE* getFile();
8781 std::string getContents();
8782
8783 private:
8784 std::FILE* m_file = nullptr;
8785 #if defined(_MSC_VER)
8786 char m_buffer[L_tmpnam] = { 0 };
8787 #endif
8788 };
8789
8790
8791 class OutputRedirect {
8792 public:
8793 OutputRedirect(OutputRedirect const&) = delete;
8794 OutputRedirect& operator=(OutputRedirect const&) = delete;
8795 OutputRedirect(OutputRedirect&&) = delete;
8796 OutputRedirect& operator=(OutputRedirect&&) = delete;
8797
8798
8799 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
8800 ~OutputRedirect();
8801
8802 private:
8803 int m_originalStdout = -1;
8804 int m_originalStderr = -1;
8805 TempFile m_stdoutFile;
8806 TempFile m_stderrFile;
8807 std::string& m_stdoutDest;
8808 std::string& m_stderrDest;
8809 };
8810
8811 #endif
8812
8813 } // end namespace Catch
8814
8815 #endif // CATCH_OUTPUT_REDIRECT_HPP_INCLUDED
8816
8817
8818 #ifndef CATCH_REPORTER_REGISTRY_HPP_INCLUDED
8819 #define CATCH_REPORTER_REGISTRY_HPP_INCLUDED
8820
8821
8822 #include <map>
8823
8824 namespace Catch {
8825
8826 class ReporterRegistry : public IReporterRegistry {
8827 public:
8828
8829 ReporterRegistry();
8830 ~ReporterRegistry() override; // = default, out of line to allow fwd decl
8831
8832 IEventListenerPtr create( std::string const& name, ReporterConfig&& config ) const override;
8833
8834 void registerReporter( std::string const& name, IReporterFactoryPtr factory );
8835 void registerListener( Detail::unique_ptr<EventListenerFactory> factory );
8836
8837 FactoryMap const& getFactories() const override;
8838 Listeners const& getListeners() const override;
8839
8840 private:
8841 FactoryMap m_factories;
8842 Listeners m_listeners;
8843 };
8844 }
8845
8846 #endif // CATCH_REPORTER_REGISTRY_HPP_INCLUDED
8847
8848
8849 #ifndef CATCH_RUN_CONTEXT_HPP_INCLUDED
8850 #define CATCH_RUN_CONTEXT_HPP_INCLUDED
8851
8852
8853
8854 #ifndef CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
8855 #define CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
8856
8857
8858 #include <string>
8859 #include <vector>
8860
8861 namespace Catch {
8862 namespace TestCaseTracking {
8863
8864 struct NameAndLocation {
8865 std::string name;
8866 SourceLineInfo location;
8867
8868 NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
8869 friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
8870 return lhs.name == rhs.name
8871 && lhs.location == rhs.location;
8872 }
8873 };
8874
8875 class ITracker;
8876
8877 using ITrackerPtr = Catch::Detail::unique_ptr<ITracker>;
8878
8879 class ITracker {
8880 NameAndLocation m_nameAndLocation;
8881
8882 using Children = std::vector<ITrackerPtr>;
8883
8884 protected:
8885 enum CycleState {
8886 NotStarted,
8887 Executing,
8888 ExecutingChildren,
8889 NeedsAnotherRun,
8890 CompletedSuccessfully,
8891 Failed
8892 };
8893
8894 ITracker* m_parent = nullptr;
8895 Children m_children;
8896 CycleState m_runState = NotStarted;
8897
8898 public:
8899 ITracker( NameAndLocation const& nameAndLoc, ITracker* parent ):
8900 m_nameAndLocation( nameAndLoc ),
8901 m_parent( parent )
8902 {}
8903
8904
8905 // static queries
8906 NameAndLocation const& nameAndLocation() const {
8907 return m_nameAndLocation;
8908 }
8909 ITracker* parent() const {
8910 return m_parent;
8911 }
8912
8913 virtual ~ITracker(); // = default
8914
8915
8916 // dynamic queries
8917
8918 //! Returns true if tracker run to completion (successfully or not)
8919 virtual bool isComplete() const = 0;
8920 //! Returns true if tracker run to completion succesfully
8921 bool isSuccessfullyCompleted() const;
8922 //! Returns true if tracker has started but hasn't been completed
8923 bool isOpen() const;
8924 //! Returns true iff tracker has started
8925 bool hasStarted() const;
8926
8927 // actions
8928 virtual void close() = 0; // Successfully complete
8929 virtual void fail() = 0;
8930 void markAsNeedingAnotherRun();
8931
8932 //! Register a nested ITracker
8933 void addChild( ITrackerPtr&& child );
8934 /**
8935 * Returns ptr to specific child if register with this tracker.
8936 *
8937 * Returns nullptr if not found.
8938 */
8939 ITracker* findChild( NameAndLocation const& nameAndLocation );
8940 //! Have any children been added?
8941 bool hasChildren() const {
8942 return !m_children.empty();
8943 }
8944
8945
8946 //! Marks tracker as executing a child, doing se recursively up the tree
8947 void openChild();
8948
8949 /**
8950 * Returns true if the instance is a section tracker
8951 *
8952 * Subclasses should override to true if they are, replaces RTTI
8953 * for internal debug checks.
8954 */
8955 virtual bool isSectionTracker() const;
8956 /**
8957 * Returns true if the instance is a generator tracker
8958 *
8959 * Subclasses should override to true if they are, replaces RTTI
8960 * for internal debug checks.
8961 */
8962 virtual bool isGeneratorTracker() const;
8963 };
8964
8965 class TrackerContext {
8966
8967 enum RunState {
8968 NotStarted,
8969 Executing,
8970 CompletedCycle
8971 };
8972
8973 ITrackerPtr m_rootTracker;
8974 ITracker* m_currentTracker = nullptr;
8975 RunState m_runState = NotStarted;
8976
8977 public:
8978
8979 ITracker& startRun();
8980 void endRun();
8981
8982 void startCycle();
8983 void completeCycle();
8984
8985 bool completedCycle() const;
8986 ITracker& currentTracker();
8987 void setCurrentTracker( ITracker* tracker );
8988 };
8989
8990 class TrackerBase : public ITracker {
8991 protected:
8992
8993 TrackerContext& m_ctx;
8994
8995 public:
8996 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
8997
8998 bool isComplete() const override;
8999
9000 void open();
9001
9002 void close() override;
9003 void fail() override;
9004
9005 private:
9006 void moveToParent();
9007 void moveToThis();
9008 };
9009
9010 class SectionTracker : public TrackerBase {
9011 std::vector<StringRef> m_filters;
9012 std::string m_trimmed_name;
9013 public:
9014 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
9015
9016 bool isSectionTracker() const override;
9017
9018 bool isComplete() const override;
9019
9020 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
9021
9022 void tryOpen();
9023
9024 void addInitialFilters( std::vector<std::string> const& filters );
9025 void addNextFilters( std::vector<StringRef> const& filters );
9026 //! Returns filters active in this tracker
9027 std::vector<StringRef> const& getFilters() const;
9028 //! Returns whitespace-trimmed name of the tracked section
9029 StringRef trimmedName() const;
9030 };
9031
9032 } // namespace TestCaseTracking
9033
9034 using TestCaseTracking::ITracker;
9035 using TestCaseTracking::TrackerContext;
9036 using TestCaseTracking::SectionTracker;
9037
9038 } // namespace Catch
9039
9040 #endif // CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
9041
9042 #include <string>
9043
9044 namespace Catch {
9045
9046 class IMutableContext;
9047 class IGeneratorTracker;
9048 class IConfig;
9049
9050 ///////////////////////////////////////////////////////////////////////////
9051
9052 class RunContext : public IResultCapture {
9053
9054 public:
9055 RunContext( RunContext const& ) = delete;
9056 RunContext& operator =( RunContext const& ) = delete;
9057
9058 explicit RunContext( IConfig const* _config, IEventListenerPtr&& reporter );
9059
9060 ~RunContext() override;
9061
9062 Totals runTest(TestCaseHandle const& testCase);
9063
9064 public: // IResultCapture
9065
9066 // Assertion handlers
9067 void handleExpr
9068 ( AssertionInfo const& info,
9069 ITransientExpression const& expr,
9070 AssertionReaction& reaction ) override;
9071 void handleMessage
9072 ( AssertionInfo const& info,
9073 ResultWas::OfType resultType,
9074 StringRef message,
9075 AssertionReaction& reaction ) override;
9076 void handleUnexpectedExceptionNotThrown
9077 ( AssertionInfo const& info,
9078 AssertionReaction& reaction ) override;
9079 void handleUnexpectedInflightException
9080 ( AssertionInfo const& info,
9081 std::string const& message,
9082 AssertionReaction& reaction ) override;
9083 void handleIncomplete
9084 ( AssertionInfo const& info ) override;
9085 void handleNonExpr
9086 ( AssertionInfo const &info,
9087 ResultWas::OfType resultType,
9088 AssertionReaction &reaction ) override;
9089
9090 bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
9091
9092 void sectionEnded( SectionEndInfo const& endInfo ) override;
9093 void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
9094
9095 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
9096
9097 void benchmarkPreparing( StringRef name ) override;
9098 void benchmarkStarting( BenchmarkInfo const& info ) override;
9099 void benchmarkEnded( BenchmarkStats<> const& stats ) override;
9100 void benchmarkFailed( StringRef error ) override;
9101
9102 void pushScopedMessage( MessageInfo const& message ) override;
9103 void popScopedMessage( MessageInfo const& message ) override;
9104
9105 void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
9106
9107 std::string getCurrentTestName() const override;
9108
9109 const AssertionResult* getLastResult() const override;
9110
9111 void exceptionEarlyReported() override;
9112
9113 void handleFatalErrorCondition( StringRef message ) override;
9114
9115 bool lastAssertionPassed() override;
9116
9117 void assertionPassed() override;
9118
9119 public:
9120 // !TBD We need to do this another way!
9121 bool aborting() const;
9122
9123 private:
9124
9125 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
9126 void invokeActiveTestCase();
9127
9128 void resetAssertionInfo();
9129 bool testForMissingAssertions( Counts& assertions );
9130
9131 void assertionEnded( AssertionResult const& result );
9132 void reportExpr
9133 ( AssertionInfo const &info,
9134 ResultWas::OfType resultType,
9135 ITransientExpression const *expr,
9136 bool negated );
9137
9138 void populateReaction( AssertionReaction& reaction );
9139
9140 private:
9141
9142 void handleUnfinishedSections();
9143
9144 TestRunInfo m_runInfo;
9145 IMutableContext& m_context;
9146 TestCaseHandle const* m_activeTestCase = nullptr;
9147 ITracker* m_testCaseTracker = nullptr;
9148 Optional<AssertionResult> m_lastResult;
9149
9150 IConfig const* m_config;
9151 Totals m_totals;
9152 IEventListenerPtr m_reporter;
9153 std::vector<MessageInfo> m_messages;
9154 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
9155 AssertionInfo m_lastAssertionInfo;
9156 std::vector<SectionEndInfo> m_unfinishedSections;
9157 std::vector<ITracker*> m_activeSections;
9158 TrackerContext m_trackerContext;
9159 FatalConditionHandler m_fatalConditionhandler;
9160 bool m_lastAssertionPassed = false;
9161 bool m_shouldReportUnexpected = true;
9162 bool m_includeSuccessfulResults;
9163 };
9164
9165 void seedRng(IConfig const& config);
9166 unsigned int rngSeed();
9167 } // end namespace Catch
9168
9169 #endif // CATCH_RUN_CONTEXT_HPP_INCLUDED
9170
9171
9172 #ifndef CATCH_SHARDING_HPP_INCLUDED
9173 #define CATCH_SHARDING_HPP_INCLUDED
9174
9175
9176 #include <cmath>
9177 #include <algorithm>
9178
9179 namespace Catch {
9180
9181 template<typename Container>
9182 Container createShard(Container const& container, std::size_t const shardCount, std::size_t const shardIndex) {
9183 assert(shardCount > shardIndex);
9184
9185 if (shardCount == 1) {
9186 return container;
9187 }
9188
9189 const std::size_t totalTestCount = container.size();
9190
9191 const std::size_t shardSize = totalTestCount / shardCount;
9192 const std::size_t leftoverTests = totalTestCount % shardCount;
9193
9194 const std::size_t startIndex = shardIndex * shardSize + (std::min)(shardIndex, leftoverTests);
9195 const std::size_t endIndex = (shardIndex + 1) * shardSize + (std::min)(shardIndex + 1, leftoverTests);
9196
9197 auto startIterator = std::next(container.begin(), static_cast<std::ptrdiff_t>(startIndex));
9198 auto endIterator = std::next(container.begin(), static_cast<std::ptrdiff_t>(endIndex));
9199
9200 return Container(startIterator, endIterator);
9201 }
9202
9203 }
9204
9205 #endif // CATCH_SHARDING_HPP_INCLUDED
9206
9207
9208 #ifndef CATCH_SINGLETONS_HPP_INCLUDED
9209 #define CATCH_SINGLETONS_HPP_INCLUDED
9210
9211 namespace Catch {
9212
9213 struct ISingleton {
9214 virtual ~ISingleton(); // = default
9215 };
9216
9217
9218 void addSingleton( ISingleton* singleton );
9219 void cleanupSingletons();
9220
9221
9222 template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
9223 class Singleton : SingletonImplT, public ISingleton {
9224
9225 static auto getInternal() -> Singleton* {
9226 static Singleton* s_instance = nullptr;
9227 if( !s_instance ) {
9228 s_instance = new Singleton;
9229 addSingleton( s_instance );
9230 }
9231 return s_instance;
9232 }
9233
9234 public:
9235 static auto get() -> InterfaceT const& {
9236 return *getInternal();
9237 }
9238 static auto getMutable() -> MutableInterfaceT& {
9239 return *getInternal();
9240 }
9241 };
9242
9243 } // namespace Catch
9244
9245 #endif // CATCH_SINGLETONS_HPP_INCLUDED
9246
9247
9248 #ifndef CATCH_STARTUP_EXCEPTION_REGISTRY_HPP_INCLUDED
9249 #define CATCH_STARTUP_EXCEPTION_REGISTRY_HPP_INCLUDED
9250
9251
9252 #include <vector>
9253 #include <exception>
9254
9255 namespace Catch {
9256
9257 class StartupExceptionRegistry {
9258 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
9259 public:
9260 void add(std::exception_ptr const& exception) noexcept;
9261 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
9262 private:
9263 std::vector<std::exception_ptr> m_exceptions;
9264 #endif
9265 };
9266
9267 } // end namespace Catch
9268
9269 #endif // CATCH_STARTUP_EXCEPTION_REGISTRY_HPP_INCLUDED
9270
9271
9272
9273 #ifndef CATCH_STDSTREAMS_HPP_INCLUDED
9274 #define CATCH_STDSTREAMS_HPP_INCLUDED
9275
9276 #include <iosfwd>
9277
9278 namespace Catch {
9279
9280 std::ostream& cout();
9281 std::ostream& cerr();
9282 std::ostream& clog();
9283
9284 } // namespace Catch
9285
9286 #endif
9287
9288
9289 #ifndef CATCH_STRING_MANIP_HPP_INCLUDED
9290 #define CATCH_STRING_MANIP_HPP_INCLUDED
9291
9292
9293 #include <string>
9294 #include <iosfwd>
9295 #include <vector>
9296
9297 namespace Catch {
9298
9299 bool startsWith( std::string const& s, std::string const& prefix );
9300 bool startsWith( StringRef s, char prefix );
9301 bool endsWith( std::string const& s, std::string const& suffix );
9302 bool endsWith( std::string const& s, char suffix );
9303 bool contains( std::string const& s, std::string const& infix );
9304 void toLowerInPlace( std::string& s );
9305 std::string toLower( std::string const& s );
9306 char toLower( char c );
9307 //! Returns a new string without whitespace at the start/end
9308 std::string trim( std::string const& str );
9309 //! Returns a substring of the original ref without whitespace. Beware lifetimes!
9310 StringRef trim(StringRef ref);
9311
9312 // !!! Be aware, returns refs into original string - make sure original string outlives them
9313 std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
9314 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
9315
9316 /**
9317 * Helper for streaming a "count [maybe-plural-of-label]" human-friendly string
9318 *
9319 * Usage example:
9320 * ```cpp
9321 * std::cout << "Found " << pluralise(count, "error") << '\n';
9322 * ```
9323 *
9324 * **Important:** The provided string must outlive the instance
9325 */
9326 class pluralise {
9327 std::uint64_t m_count;
9328 StringRef m_label;
9329
9330 public:
9331 constexpr pluralise(std::uint64_t count, StringRef label):
9332 m_count(count),
9333 m_label(label)
9334 {}
9335
9336 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
9337 };
9338 }
9339
9340 #endif // CATCH_STRING_MANIP_HPP_INCLUDED
9341
9342
9343 #ifndef CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
9344 #define CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
9345
9346
9347 #include <map>
9348 #include <string>
9349
9350 namespace Catch {
9351 struct SourceLineInfo;
9352
9353 class TagAliasRegistry : public ITagAliasRegistry {
9354 public:
9355 ~TagAliasRegistry() override;
9356 TagAlias const* find( std::string const& alias ) const override;
9357 std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
9358 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
9359
9360 private:
9361 std::map<std::string, TagAlias> m_registry;
9362 };
9363
9364 } // end namespace Catch
9365
9366 #endif // CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
9367
9368
9369 #ifndef CATCH_TEST_CASE_INFO_HASHER_HPP_INCLUDED
9370 #define CATCH_TEST_CASE_INFO_HASHER_HPP_INCLUDED
9371
9372 #include <cstdint>
9373
9374 namespace Catch {
9375
9376 struct TestCaseInfo;
9377
9378 class TestCaseInfoHasher {
9379 public:
9380 using hash_t = std::uint64_t;
9381 TestCaseInfoHasher( hash_t seed );
9382 uint32_t operator()( TestCaseInfo const& t ) const;
9383
9384 private:
9385 hash_t m_seed;
9386 };
9387
9388 } // namespace Catch
9389
9390 #endif /* CATCH_TEST_CASE_INFO_HASHER_HPP_INCLUDED */
9391
9392
9393 #ifndef CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
9394 #define CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
9395
9396
9397 #include <vector>
9398
9399 namespace Catch {
9400
9401 class TestCaseHandle;
9402 class IConfig;
9403 class TestSpec;
9404
9405 std::vector<TestCaseHandle> sortTests( IConfig const& config, std::vector<TestCaseHandle> const& unsortedTestCases );
9406
9407 bool isThrowSafe( TestCaseHandle const& testCase, IConfig const& config );
9408 bool matchTest( TestCaseHandle const& testCase, TestSpec const& testSpec, IConfig const& config );
9409
9410 void enforceNoDuplicateTestCases( std::vector<TestCaseHandle> const& functions );
9411
9412 std::vector<TestCaseHandle> filterTests( std::vector<TestCaseHandle> const& testCases, TestSpec const& testSpec, IConfig const& config );
9413 std::vector<TestCaseHandle> const& getAllTestCasesSorted( IConfig const& config );
9414
9415 class TestRegistry : public ITestCaseRegistry {
9416 public:
9417 ~TestRegistry() override = default;
9418
9419 void registerTest( Detail::unique_ptr<TestCaseInfo> testInfo, Detail::unique_ptr<ITestInvoker> testInvoker );
9420
9421 std::vector<TestCaseInfo*> const& getAllInfos() const override;
9422 std::vector<TestCaseHandle> const& getAllTests() const override;
9423 std::vector<TestCaseHandle> const& getAllTestsSorted( IConfig const& config ) const override;
9424
9425 private:
9426 std::vector<Detail::unique_ptr<TestCaseInfo>> m_owned_test_infos;
9427 // Keeps a materialized vector for `getAllInfos`.
9428 // We should get rid of that eventually (see interface note)
9429 std::vector<TestCaseInfo*> m_viewed_test_infos;
9430
9431 std::vector<Detail::unique_ptr<ITestInvoker>> m_invokers;
9432 std::vector<TestCaseHandle> m_handles;
9433 mutable TestRunOrder m_currentSortOrder = TestRunOrder::Declared;
9434 mutable std::vector<TestCaseHandle> m_sortedFunctions;
9435 };
9436
9437 ///////////////////////////////////////////////////////////////////////////
9438
9439 class TestInvokerAsFunction final : public ITestInvoker {
9440 using TestType = void(*)();
9441 TestType m_testAsFunction;
9442 public:
9443 TestInvokerAsFunction(TestType testAsFunction) noexcept:
9444 m_testAsFunction(testAsFunction) {}
9445
9446 void invoke() const override;
9447 };
9448
9449 ///////////////////////////////////////////////////////////////////////////
9450
9451
9452 } // end namespace Catch
9453
9454
9455 #endif // CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
9456
9457
9458 #ifndef CATCH_TEST_SPEC_PARSER_HPP_INCLUDED
9459 #define CATCH_TEST_SPEC_PARSER_HPP_INCLUDED
9460
9461 #ifdef __clang__
9462 #pragma clang diagnostic push
9463 #pragma clang diagnostic ignored "-Wpadded"
9464 #endif
9465
9466
9467 #include <vector>
9468 #include <string>
9469
9470 namespace Catch {
9471
9472 class ITagAliasRegistry;
9473
9474 class TestSpecParser {
9475 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
9476 Mode m_mode = None;
9477 Mode lastMode = None;
9478 bool m_exclusion = false;
9479 std::size_t m_pos = 0;
9480 std::size_t m_realPatternPos = 0;
9481 std::string m_arg;
9482 std::string m_substring;
9483 std::string m_patternName;
9484 std::vector<std::size_t> m_escapeChars;
9485 TestSpec::Filter m_currentFilter;
9486 TestSpec m_testSpec;
9487 ITagAliasRegistry const* m_tagAliases = nullptr;
9488
9489 public:
9490 TestSpecParser( ITagAliasRegistry const& tagAliases );
9491
9492 TestSpecParser& parse( std::string const& arg );
9493 TestSpec testSpec();
9494
9495 private:
9496 bool visitChar( char c );
9497 void startNewMode( Mode mode );
9498 bool processNoneChar( char c );
9499 void processNameChar( char c );
9500 bool processOtherChar( char c );
9501 void endMode();
9502 void escape();
9503 bool isControlChar( char c ) const;
9504 void saveLastMode();
9505 void revertBackToLastMode();
9506 void addFilter();
9507 bool separate();
9508
9509 // Handles common preprocessing of the pattern for name/tag patterns
9510 std::string preprocessPattern();
9511 // Adds the current pattern as a test name
9512 void addNamePattern();
9513 // Adds the current pattern as a tag
9514 void addTagPattern();
9515
9516 inline void addCharToPattern(char c) {
9517 m_substring += c;
9518 m_patternName += c;
9519 m_realPatternPos++;
9520 }
9521
9522 };
9523 TestSpec parseTestSpec( std::string const& arg );
9524
9525 } // namespace Catch
9526
9527 #ifdef __clang__
9528 #pragma clang diagnostic pop
9529 #endif
9530
9531 #endif // CATCH_TEST_SPEC_PARSER_HPP_INCLUDED
9532
9533
9534 #ifndef CATCH_TEXTFLOW_HPP_INCLUDED
9535 #define CATCH_TEXTFLOW_HPP_INCLUDED
9536
9537 #include <cassert>
9538 #include <string>
9539 #include <vector>
9540
9541 namespace Catch {
9542 namespace TextFlow {
9543
9544 class Columns;
9545
9546 /**
9547 * Represents a column of text with specific width and indentation
9548 *
9549 * When written out to a stream, it will perform linebreaking
9550 * of the provided text so that the written lines fit within
9551 * target width.
9552 */
9553 class Column {
9554 // String to be written out
9555 std::string m_string;
9556 // Width of the column for linebreaking
9557 size_t m_width = CATCH_CONFIG_CONSOLE_WIDTH - 1;
9558 // Indentation of other lines (including first if initial indent is unset)
9559 size_t m_indent = 0;
9560 // Indentation of the first line
9561 size_t m_initialIndent = std::string::npos;
9562
9563 public:
9564 /**
9565 * Iterates "lines" in `Column` and return sthem
9566 */
9567 class const_iterator {
9568 friend Column;
9569 struct EndTag {};
9570
9571 Column const& m_column;
9572 // Where does the current line start?
9573 size_t m_lineStart = 0;
9574 // How long should the current line be?
9575 size_t m_lineLength = 0;
9576 // How far have we checked the string to iterate?
9577 size_t m_parsedTo = 0;
9578 // Should a '-' be appended to the line?
9579 bool m_addHyphen = false;
9580
9581 const_iterator( Column const& column, EndTag ):
9582 m_column( column ), m_lineStart( m_column.m_string.size() ) {}
9583
9584 // Calculates the length of the current line
9585 void calcLength();
9586
9587 // Returns current indention width
9588 size_t indentSize() const;
9589
9590 // Creates an indented and (optionally) suffixed string from
9591 // current iterator position, indentation and length.
9592 std::string addIndentAndSuffix( size_t position,
9593 size_t length ) const;
9594
9595 public:
9596 using difference_type = std::ptrdiff_t;
9597 using value_type = std::string;
9598 using pointer = value_type*;
9599 using reference = value_type&;
9600 using iterator_category = std::forward_iterator_tag;
9601
9602 explicit const_iterator( Column const& column );
9603
9604 std::string operator*() const;
9605
9606 const_iterator& operator++();
9607 const_iterator operator++( int );
9608
9609 bool operator==( const_iterator const& other ) const {
9610 return m_lineStart == other.m_lineStart && &m_column == &other.m_column;
9611 }
9612 bool operator!=( const_iterator const& other ) const {
9613 return !operator==( other );
9614 }
9615 };
9616 using iterator = const_iterator;
9617
9618 explicit Column( std::string const& text ): m_string( text ) {}
9619
9620 Column& width( size_t newWidth ) {
9621 assert( newWidth > 0 );
9622 m_width = newWidth;
9623 return *this;
9624 }
9625 Column& indent( size_t newIndent ) {
9626 m_indent = newIndent;
9627 return *this;
9628 }
9629 Column& initialIndent( size_t newIndent ) {
9630 m_initialIndent = newIndent;
9631 return *this;
9632 }
9633
9634 size_t width() const { return m_width; }
9635 const_iterator begin() const { return const_iterator( *this ); }
9636 const_iterator end() const { return { *this, const_iterator::EndTag{} }; }
9637
9638 friend std::ostream& operator<<( std::ostream& os,
9639 Column const& col );
9640
9641 Columns operator+( Column const& other );
9642 };
9643
9644 //! Creates a column that serves as an empty space of specific width
9645 Column Spacer( size_t spaceWidth );
9646
9647 class Columns {
9648 std::vector<Column> m_columns;
9649
9650 public:
9651 class iterator {
9652 friend Columns;
9653 struct EndTag {};
9654
9655 std::vector<Column> const& m_columns;
9656 std::vector<Column::const_iterator> m_iterators;
9657 size_t m_activeIterators;
9658
9659 iterator( Columns const& columns, EndTag );
9660
9661 public:
9662 using difference_type = std::ptrdiff_t;
9663 using value_type = std::string;
9664 using pointer = value_type*;
9665 using reference = value_type&;
9666 using iterator_category = std::forward_iterator_tag;
9667
9668 explicit iterator( Columns const& columns );
9669
9670 auto operator==( iterator const& other ) const -> bool {
9671 return m_iterators == other.m_iterators;
9672 }
9673 auto operator!=( iterator const& other ) const -> bool {
9674 return m_iterators != other.m_iterators;
9675 }
9676 std::string operator*() const;
9677 iterator& operator++();
9678 iterator operator++( int );
9679 };
9680 using const_iterator = iterator;
9681
9682 iterator begin() const { return iterator( *this ); }
9683 iterator end() const { return { *this, iterator::EndTag() }; }
9684
9685 Columns& operator+=( Column const& col );
9686 Columns operator+( Column const& col );
9687
9688 friend std::ostream& operator<<( std::ostream& os,
9689 Columns const& cols );
9690 };
9691
9692 } // namespace TextFlow
9693 } // namespace Catch
9694 #endif // CATCH_TEXTFLOW_HPP_INCLUDED
9695
9696
9697 #ifndef CATCH_TO_STRING_HPP_INCLUDED
9698 #define CATCH_TO_STRING_HPP_INCLUDED
9699
9700 #include <string>
9701
9702
9703 namespace Catch {
9704 template <typename T>
9705 std::string to_string(T const& t) {
9706 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
9707 return std::to_string(t);
9708 #else
9709 ReusableStringStream rss;
9710 rss << t;
9711 return rss.str();
9712 #endif
9713 }
9714 } // end namespace Catch
9715
9716 #endif // CATCH_TO_STRING_HPP_INCLUDED
9717
9718
9719 #ifndef CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
9720 #define CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
9721
9722 namespace Catch {
9723 bool uncaught_exceptions();
9724 } // end namespace Catch
9725
9726 #endif // CATCH_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED
9727
9728
9729 #ifndef CATCH_XMLWRITER_HPP_INCLUDED
9730 #define CATCH_XMLWRITER_HPP_INCLUDED
9731
9732
9733 #include <iosfwd>
9734 #include <vector>
9735
9736 namespace Catch {
9737 enum class XmlFormatting {
9738 None = 0x00,
9739 Indent = 0x01,
9740 Newline = 0x02,
9741 };
9742
9743 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
9744 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
9745
9746 /**
9747 * Helper for XML-encoding text (escaping angle brackets, quotes, etc)
9748 *
9749 * Note: doesn't take ownership of passed strings, and thus the
9750 * encoded string must outlive the encoding instance.
9751 */
9752 class XmlEncode {
9753 public:
9754 enum ForWhat { ForTextNodes, ForAttributes };
9755
9756 XmlEncode( StringRef str, ForWhat forWhat = ForTextNodes );
9757
9758 void encodeTo( std::ostream& os ) const;
9759
9760 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
9761
9762 private:
9763 StringRef m_str;
9764 ForWhat m_forWhat;
9765 };
9766
9767 class XmlWriter {
9768 public:
9769
9770 class ScopedElement {
9771 public:
9772 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
9773
9774 ScopedElement( ScopedElement&& other ) noexcept;
9775 ScopedElement& operator=( ScopedElement&& other ) noexcept;
9776
9777 ~ScopedElement();
9778
9779 ScopedElement&
9780 writeText( StringRef text,
9781 XmlFormatting fmt = XmlFormatting::Newline |
9782 XmlFormatting::Indent );
9783
9784 ScopedElement& writeAttribute( StringRef name,
9785 StringRef attribute );
9786 template <typename T,
9787 // Without this SFINAE, this overload is a better match
9788 // for `std::string`, `char const*`, `char const[N]` args.
9789 // While it would still work, it would cause code bloat
9790 // and multiple iteration over the strings
9791 typename = typename std::enable_if_t<
9792 !std::is_convertible<T, StringRef>::value>>
9793 ScopedElement& writeAttribute( StringRef name,
9794 T const& attribute ) {
9795 m_writer->writeAttribute( name, attribute );
9796 return *this;
9797 }
9798
9799 private:
9800 XmlWriter* m_writer = nullptr;
9801 XmlFormatting m_fmt;
9802 };
9803
9804 XmlWriter( std::ostream& os );
9805 ~XmlWriter();
9806
9807 XmlWriter( XmlWriter const& ) = delete;
9808 XmlWriter& operator=( XmlWriter const& ) = delete;
9809
9810 XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
9811
9812 ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
9813
9814 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
9815
9816 //! The attribute content is XML-encoded
9817 XmlWriter& writeAttribute( StringRef name, StringRef attribute );
9818
9819 //! Writes the attribute as "true/false"
9820 XmlWriter& writeAttribute( StringRef name, bool attribute );
9821
9822 //! The attribute content is XML-encoded
9823 XmlWriter& writeAttribute( StringRef name, char const* attribute );
9824
9825 //! The attribute value must provide op<<(ostream&, T). The resulting
9826 //! serialization is XML-encoded
9827 template <typename T,
9828 // Without this SFINAE, this overload is a better match
9829 // for `std::string`, `char const*`, `char const[N]` args.
9830 // While it would still work, it would cause code bloat
9831 // and multiple iteration over the strings
9832 typename = typename std::enable_if_t<
9833 !std::is_convertible<T, StringRef>::value>>
9834 XmlWriter& writeAttribute( StringRef name, T const& attribute ) {
9835 ReusableStringStream rss;
9836 rss << attribute;
9837 return writeAttribute( name, rss.str() );
9838 }
9839
9840 //! Writes escaped `text` in a element
9841 XmlWriter& writeText( StringRef text,
9842 XmlFormatting fmt = XmlFormatting::Newline |
9843 XmlFormatting::Indent );
9844
9845 //! Writes XML comment as "<!-- text -->"
9846 XmlWriter& writeComment( StringRef text,
9847 XmlFormatting fmt = XmlFormatting::Newline |
9848 XmlFormatting::Indent );
9849
9850 void writeStylesheetRef( StringRef url );
9851
9852 void ensureTagClosed();
9853
9854 private:
9855
9856 void applyFormatting(XmlFormatting fmt);
9857
9858 void writeDeclaration();
9859
9860 void newlineIfNecessary();
9861
9862 bool m_tagIsOpen = false;
9863 bool m_needsNewline = false;
9864 std::vector<std::string> m_tags;
9865 std::string m_indent;
9866 std::ostream& m_os;
9867 };
9868
9869 }
9870
9871 #endif // CATCH_XMLWRITER_HPP_INCLUDED
9872
9873
9874 /** \file
9875 * This is a convenience header for Catch2's Matcher support. It includes
9876 * **all** of Catch2 headers related to matchers.
9877 *
9878 * Generally the Catch2 users should use specific includes they need,
9879 * but this header can be used instead for ease-of-experimentation, or
9880 * just plain convenience, at the cost of increased compilation times.
9881 *
9882 * When a new header is added to either the `matchers` folder, or to
9883 * the corresponding internal subfolder, it should be added here.
9884 */
9885
9886 #ifndef CATCH_MATCHERS_ALL_HPP_INCLUDED
9887 #define CATCH_MATCHERS_ALL_HPP_INCLUDED
9888
9889
9890
9891 #ifndef CATCH_MATCHERS_HPP_INCLUDED
9892 #define CATCH_MATCHERS_HPP_INCLUDED
9893
9894
9895
9896 #ifndef CATCH_MATCHERS_IMPL_HPP_INCLUDED
9897 #define CATCH_MATCHERS_IMPL_HPP_INCLUDED
9898
9899
9900 namespace Catch {
9901
9902 template<typename ArgT, typename MatcherT>
9903 class MatchExpr : public ITransientExpression {
9904 ArgT && m_arg;
9905 MatcherT const& m_matcher;
9906 StringRef m_matcherString;
9907 public:
9908 MatchExpr( ArgT && arg, MatcherT const& matcher, StringRef matcherString )
9909 : ITransientExpression{ true, matcher.match( arg ) }, // not forwarding arg here on purpose
9910 m_arg( CATCH_FORWARD(arg) ),
9911 m_matcher( matcher ),
9912 m_matcherString( matcherString )
9913 {}
9914
9915 void streamReconstructedExpression( std::ostream& os ) const override {
9916 os << Catch::Detail::stringify( m_arg )
9917 << ' '
9918 << m_matcher.toString();
9919 }
9920 };
9921
9922 namespace Matchers {
9923 template <typename ArgT>
9924 class MatcherBase;
9925 }
9926
9927 using StringMatcher = Matchers::MatcherBase<std::string>;
9928
9929 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
9930
9931 template<typename ArgT, typename MatcherT>
9932 auto makeMatchExpr( ArgT && arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
9933 return MatchExpr<ArgT, MatcherT>( CATCH_FORWARD(arg), matcher, matcherString );
9934 }
9935
9936 } // namespace Catch
9937
9938
9939 ///////////////////////////////////////////////////////////////////////////////
9940 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
9941 do { \
9942 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
9943 INTERNAL_CATCH_TRY { \
9944 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
9945 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
9946 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
9947 } while( false )
9948
9949
9950 ///////////////////////////////////////////////////////////////////////////////
9951 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
9952 do { \
9953 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
9954 if( catchAssertionHandler.allowThrows() ) \
9955 try { \
9956 static_cast<void>(__VA_ARGS__ ); \
9957 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
9958 } \
9959 catch( exceptionType const& ex ) { \
9960 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
9961 } \
9962 catch( ... ) { \
9963 catchAssertionHandler.handleUnexpectedInflightException(); \
9964 } \
9965 else \
9966 catchAssertionHandler.handleThrowingCallSkipped(); \
9967 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
9968 } while( false )
9969
9970
9971 #endif // CATCH_MATCHERS_IMPL_HPP_INCLUDED
9972
9973 #include <string>
9974 #include <vector>
9975
9976 namespace Catch {
9977 namespace Matchers {
9978
9979 class MatcherUntypedBase {
9980 public:
9981 MatcherUntypedBase() = default;
9982
9983 MatcherUntypedBase(MatcherUntypedBase const&) = default;
9984 MatcherUntypedBase(MatcherUntypedBase&&) = default;
9985
9986 MatcherUntypedBase& operator = (MatcherUntypedBase const&) = delete;
9987 MatcherUntypedBase& operator = (MatcherUntypedBase&&) = delete;
9988
9989 std::string toString() const;
9990
9991 protected:
9992 virtual ~MatcherUntypedBase(); // = default;
9993 virtual std::string describe() const = 0;
9994 mutable std::string m_cachedToString;
9995 };
9996
9997
9998 template<typename T>
9999 class MatcherBase : public MatcherUntypedBase {
10000 public:
10001 virtual bool match( T const& arg ) const = 0;
10002 };
10003
10004 namespace Detail {
10005
10006 template<typename ArgT>
10007 class MatchAllOf final : public MatcherBase<ArgT> {
10008 std::vector<MatcherBase<ArgT> const*> m_matchers;
10009
10010 public:
10011 MatchAllOf() = default;
10012 MatchAllOf(MatchAllOf const&) = delete;
10013 MatchAllOf& operator=(MatchAllOf const&) = delete;
10014 MatchAllOf(MatchAllOf&&) = default;
10015 MatchAllOf& operator=(MatchAllOf&&) = default;
10016
10017
10018 bool match( ArgT const& arg ) const override {
10019 for( auto matcher : m_matchers ) {
10020 if (!matcher->match(arg))
10021 return false;
10022 }
10023 return true;
10024 }
10025 std::string describe() const override {
10026 std::string description;
10027 description.reserve( 4 + m_matchers.size()*32 );
10028 description += "( ";
10029 bool first = true;
10030 for( auto matcher : m_matchers ) {
10031 if( first )
10032 first = false;
10033 else
10034 description += " and ";
10035 description += matcher->toString();
10036 }
10037 description += " )";
10038 return description;
10039 }
10040
10041 friend MatchAllOf operator&& (MatchAllOf&& lhs, MatcherBase<ArgT> const& rhs) {
10042 lhs.m_matchers.push_back(&rhs);
10043 return CATCH_MOVE(lhs);
10044 }
10045 friend MatchAllOf operator&& (MatcherBase<ArgT> const& lhs, MatchAllOf&& rhs) {
10046 rhs.m_matchers.insert(rhs.m_matchers.begin(), &lhs);
10047 return CATCH_MOVE(rhs);
10048 }
10049 };
10050
10051 //! lvalue overload is intentionally deleted, users should
10052 //! not be trying to compose stored composition matchers
10053 template<typename ArgT>
10054 MatchAllOf<ArgT> operator&& (MatchAllOf<ArgT> const& lhs, MatcherBase<ArgT> const& rhs) = delete;
10055 //! lvalue overload is intentionally deleted, users should
10056 //! not be trying to compose stored composition matchers
10057 template<typename ArgT>
10058 MatchAllOf<ArgT> operator&& (MatcherBase<ArgT> const& lhs, MatchAllOf<ArgT> const& rhs) = delete;
10059
10060 template<typename ArgT>
10061 class MatchAnyOf final : public MatcherBase<ArgT> {
10062 std::vector<MatcherBase<ArgT> const*> m_matchers;
10063 public:
10064 MatchAnyOf() = default;
10065 MatchAnyOf(MatchAnyOf const&) = delete;
10066 MatchAnyOf& operator=(MatchAnyOf const&) = delete;
10067 MatchAnyOf(MatchAnyOf&&) = default;
10068 MatchAnyOf& operator=(MatchAnyOf&&) = default;
10069
10070 bool match( ArgT const& arg ) const override {
10071 for( auto matcher : m_matchers ) {
10072 if (matcher->match(arg))
10073 return true;
10074 }
10075 return false;
10076 }
10077 std::string describe() const override {
10078 std::string description;
10079 description.reserve( 4 + m_matchers.size()*32 );
10080 description += "( ";
10081 bool first = true;
10082 for( auto matcher : m_matchers ) {
10083 if( first )
10084 first = false;
10085 else
10086 description += " or ";
10087 description += matcher->toString();
10088 }
10089 description += " )";
10090 return description;
10091 }
10092
10093 friend MatchAnyOf operator|| (MatchAnyOf&& lhs, MatcherBase<ArgT> const& rhs) {
10094 lhs.m_matchers.push_back(&rhs);
10095 return CATCH_MOVE(lhs);
10096 }
10097 friend MatchAnyOf operator|| (MatcherBase<ArgT> const& lhs, MatchAnyOf&& rhs) {
10098 rhs.m_matchers.insert(rhs.m_matchers.begin(), &lhs);
10099 return CATCH_MOVE(rhs);
10100 }
10101 };
10102
10103 //! lvalue overload is intentionally deleted, users should
10104 //! not be trying to compose stored composition matchers
10105 template<typename ArgT>
10106 MatchAnyOf<ArgT> operator|| (MatchAnyOf<ArgT> const& lhs, MatcherBase<ArgT> const& rhs) = delete;
10107 //! lvalue overload is intentionally deleted, users should
10108 //! not be trying to compose stored composition matchers
10109 template<typename ArgT>
10110 MatchAnyOf<ArgT> operator|| (MatcherBase<ArgT> const& lhs, MatchAnyOf<ArgT> const& rhs) = delete;
10111
10112 template<typename ArgT>
10113 class MatchNotOf final : public MatcherBase<ArgT> {
10114 MatcherBase<ArgT> const& m_underlyingMatcher;
10115
10116 public:
10117 explicit MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ):
10118 m_underlyingMatcher( underlyingMatcher )
10119 {}
10120
10121 bool match( ArgT const& arg ) const override {
10122 return !m_underlyingMatcher.match( arg );
10123 }
10124
10125 std::string describe() const override {
10126 return "not " + m_underlyingMatcher.toString();
10127 }
10128 };
10129
10130 } // namespace Detail
10131
10132 template <typename T>
10133 Detail::MatchAllOf<T> operator&& (MatcherBase<T> const& lhs, MatcherBase<T> const& rhs) {
10134 return Detail::MatchAllOf<T>{} && lhs && rhs;
10135 }
10136 template <typename T>
10137 Detail::MatchAnyOf<T> operator|| (MatcherBase<T> const& lhs, MatcherBase<T> const& rhs) {
10138 return Detail::MatchAnyOf<T>{} || lhs || rhs;
10139 }
10140
10141 template <typename T>
10142 Detail::MatchNotOf<T> operator! (MatcherBase<T> const& matcher) {
10143 return Detail::MatchNotOf<T>{ matcher };
10144 }
10145
10146
10147 } // namespace Matchers
10148 } // namespace Catch
10149
10150
10151 #if defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
10152 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
10153 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
10154
10155 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
10156 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
10157
10158 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
10159 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
10160
10161 #elif defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE)
10162
10163 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
10164 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
10165
10166 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
10167 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
10168
10169 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
10170 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
10171
10172 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && !defined(CATCH_CONFIG_DISABLE)
10173
10174 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
10175 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
10176
10177 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
10178 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
10179
10180 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
10181 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
10182
10183 #elif !defined(CATCH_CONFIG_PREFIX_ALL) && defined(CATCH_CONFIG_DISABLE)
10184
10185 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
10186 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
10187
10188 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
10189 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
10190
10191 #define CHECK_THAT( arg, matcher ) (void)(0)
10192 #define REQUIRE_THAT( arg, matcher ) (void)(0)
10193
10194 #endif // end of user facing macro declarations
10195
10196 #endif // CATCH_MATCHERS_HPP_INCLUDED
10197
10198
10199 #ifndef CATCH_MATCHERS_CONTAINER_PROPERTIES_HPP_INCLUDED
10200 #define CATCH_MATCHERS_CONTAINER_PROPERTIES_HPP_INCLUDED
10201
10202
10203
10204 #ifndef CATCH_MATCHERS_TEMPLATED_HPP_INCLUDED
10205 #define CATCH_MATCHERS_TEMPLATED_HPP_INCLUDED
10206
10207
10208 #include <array>
10209 #include <algorithm>
10210 #include <string>
10211 #include <type_traits>
10212
10213 namespace Catch {
10214 namespace Matchers {
10215 class MatcherGenericBase : public MatcherUntypedBase {
10216 public:
10217 MatcherGenericBase() = default;
10218 ~MatcherGenericBase() override; // = default;
10219
10220 MatcherGenericBase(MatcherGenericBase&) = default;
10221 MatcherGenericBase(MatcherGenericBase&&) = default;
10222
10223 MatcherGenericBase& operator=(MatcherGenericBase const&) = delete;
10224 MatcherGenericBase& operator=(MatcherGenericBase&&) = delete;
10225 };
10226
10227
10228 namespace Detail {
10229 template<std::size_t N, std::size_t M>
10230 std::array<void const*, N + M> array_cat(std::array<void const*, N> && lhs, std::array<void const*, M> && rhs) {
10231 std::array<void const*, N + M> arr{};
10232 std::copy_n(lhs.begin(), N, arr.begin());
10233 std::copy_n(rhs.begin(), M, arr.begin() + N);
10234 return arr;
10235 }
10236
10237 template<std::size_t N>
10238 std::array<void const*, N+1> array_cat(std::array<void const*, N> && lhs, void const* rhs) {
10239 std::array<void const*, N+1> arr{};
10240 std::copy_n(lhs.begin(), N, arr.begin());
10241 arr[N] = rhs;
10242 return arr;
10243 }
10244
10245 template<std::size_t N>
10246 std::array<void const*, N+1> array_cat(void const* lhs, std::array<void const*, N> && rhs) {
10247 std::array<void const*, N + 1> arr{ {lhs} };
10248 std::copy_n(rhs.begin(), N, arr.begin() + 1);
10249 return arr;
10250 }
10251
10252 #if defined( __cpp_lib_logical_traits ) && __cpp_lib_logical_traits >= 201510
10253
10254 using std::conjunction;
10255
10256 #else // __cpp_lib_logical_traits
10257
10258 template<typename... Cond>
10259 struct conjunction : std::true_type {};
10260
10261 template<typename Cond, typename... Rest>
10262 struct conjunction<Cond, Rest...> : std::integral_constant<bool, Cond::value && conjunction<Rest...>::value> {};
10263
10264 #endif // __cpp_lib_logical_traits
10265
10266 template<typename T>
10267 using is_generic_matcher = std::is_base_of<
10268 Catch::Matchers::MatcherGenericBase,
10269 std::remove_cv_t<std::remove_reference_t<T>>
10270 >;
10271
10272 template<typename... Ts>
10273 using are_generic_matchers = conjunction<is_generic_matcher<Ts>...>;
10274
10275 template<typename T>
10276 using is_matcher = std::is_base_of<
10277 Catch::Matchers::MatcherUntypedBase,
10278 std::remove_cv_t<std::remove_reference_t<T>>
10279 >;
10280
10281
10282 template<std::size_t N, typename Arg>
10283 bool match_all_of(Arg&&, std::array<void const*, N> const&, std::index_sequence<>) {
10284 return true;
10285 }
10286
10287 template<typename T, typename... MatcherTs, std::size_t N, typename Arg, std::size_t Idx, std::size_t... Indices>
10288 bool match_all_of(Arg&& arg, std::array<void const*, N> const& matchers, std::index_sequence<Idx, Indices...>) {
10289 return static_cast<T const*>(matchers[Idx])->match(arg) && match_all_of<MatcherTs...>(arg, matchers, std::index_sequence<Indices...>{});
10290 }
10291
10292
10293 template<std::size_t N, typename Arg>
10294 bool match_any_of(Arg&&, std::array<void const*, N> const&, std::index_sequence<>) {
10295 return false;
10296 }
10297
10298 template<typename T, typename... MatcherTs, std::size_t N, typename Arg, std::size_t Idx, std::size_t... Indices>
10299 bool match_any_of(Arg&& arg, std::array<void const*, N> const& matchers, std::index_sequence<Idx, Indices...>) {
10300 return static_cast<T const*>(matchers[Idx])->match(arg) || match_any_of<MatcherTs...>(arg, matchers, std::index_sequence<Indices...>{});
10301 }
10302
10303 std::string describe_multi_matcher(StringRef combine, std::string const* descriptions_begin, std::string const* descriptions_end);
10304
10305 template<typename... MatcherTs, std::size_t... Idx>
10306 std::string describe_multi_matcher(StringRef combine, std::array<void const*, sizeof...(MatcherTs)> const& matchers, std::index_sequence<Idx...>) {
10307 std::array<std::string, sizeof...(MatcherTs)> descriptions {{
10308 static_cast<MatcherTs const*>(matchers[Idx])->toString()...
10309 }};
10310
10311 return describe_multi_matcher(combine, descriptions.data(), descriptions.data() + descriptions.size());
10312 }
10313
10314
10315 template<typename... MatcherTs>
10316 class MatchAllOfGeneric final : public MatcherGenericBase {
10317 public:
10318 MatchAllOfGeneric(MatchAllOfGeneric const&) = delete;
10319 MatchAllOfGeneric& operator=(MatchAllOfGeneric const&) = delete;
10320 MatchAllOfGeneric(MatchAllOfGeneric&&) = default;
10321 MatchAllOfGeneric& operator=(MatchAllOfGeneric&&) = default;
10322
10323 MatchAllOfGeneric(MatcherTs const&... matchers) : m_matchers{ {std::addressof(matchers)...} } {}
10324 explicit MatchAllOfGeneric(std::array<void const*, sizeof...(MatcherTs)> matchers) : m_matchers{matchers} {}
10325
10326 template<typename Arg>
10327 bool match(Arg&& arg) const {
10328 return match_all_of<MatcherTs...>(arg, m_matchers, std::index_sequence_for<MatcherTs...>{});
10329 }
10330
10331 std::string describe() const override {
10332 return describe_multi_matcher<MatcherTs...>(" and "_sr, m_matchers, std::index_sequence_for<MatcherTs...>{});
10333 }
10334
10335 // Has to be public to enable the concatenating operators
10336 // below, because they are not friend of the RHS, only LHS,
10337 // and thus cannot access private fields of RHS
10338 std::array<void const*, sizeof...( MatcherTs )> m_matchers;
10339
10340
10341 //! Avoids type nesting for `GenericAllOf && GenericAllOf` case
10342 template<typename... MatchersRHS>
10343 friend
10344 MatchAllOfGeneric<MatcherTs..., MatchersRHS...> operator && (
10345 MatchAllOfGeneric<MatcherTs...>&& lhs,
10346 MatchAllOfGeneric<MatchersRHS...>&& rhs) {
10347 return MatchAllOfGeneric<MatcherTs..., MatchersRHS...>{array_cat(CATCH_MOVE(lhs.m_matchers), CATCH_MOVE(rhs.m_matchers))};
10348 }
10349
10350 //! Avoids type nesting for `GenericAllOf && some matcher` case
10351 template<typename MatcherRHS>
10352 friend std::enable_if_t<is_matcher<MatcherRHS>::value,
10353 MatchAllOfGeneric<MatcherTs..., MatcherRHS>> operator && (
10354 MatchAllOfGeneric<MatcherTs...>&& lhs,
10355 MatcherRHS const& rhs) {
10356 return MatchAllOfGeneric<MatcherTs..., MatcherRHS>{array_cat(CATCH_MOVE(lhs.m_matchers), static_cast<void const*>(&rhs))};
10357 }
10358
10359 //! Avoids type nesting for `some matcher && GenericAllOf` case
10360 template<typename MatcherLHS>
10361 friend std::enable_if_t<is_matcher<MatcherLHS>::value,
10362 MatchAllOfGeneric<MatcherLHS, MatcherTs...>> operator && (
10363 MatcherLHS const& lhs,
10364 MatchAllOfGeneric<MatcherTs...>&& rhs) {
10365 return MatchAllOfGeneric<MatcherLHS, MatcherTs...>{array_cat(static_cast<void const*>(std::addressof(lhs)), CATCH_MOVE(rhs.m_matchers))};
10366 }
10367 };
10368
10369
10370 template<typename... MatcherTs>
10371 class MatchAnyOfGeneric final : public MatcherGenericBase {
10372 public:
10373 MatchAnyOfGeneric(MatchAnyOfGeneric const&) = delete;
10374 MatchAnyOfGeneric& operator=(MatchAnyOfGeneric const&) = delete;
10375 MatchAnyOfGeneric(MatchAnyOfGeneric&&) = default;
10376 MatchAnyOfGeneric& operator=(MatchAnyOfGeneric&&) = default;
10377
10378 MatchAnyOfGeneric(MatcherTs const&... matchers) : m_matchers{ {std::addressof(matchers)...} } {}
10379 explicit MatchAnyOfGeneric(std::array<void const*, sizeof...(MatcherTs)> matchers) : m_matchers{matchers} {}
10380
10381 template<typename Arg>
10382 bool match(Arg&& arg) const {
10383 return match_any_of<MatcherTs...>(arg, m_matchers, std::index_sequence_for<MatcherTs...>{});
10384 }
10385
10386 std::string describe() const override {
10387 return describe_multi_matcher<MatcherTs...>(" or "_sr, m_matchers, std::index_sequence_for<MatcherTs...>{});
10388 }
10389
10390
10391 // Has to be public to enable the concatenating operators
10392 // below, because they are not friend of the RHS, only LHS,
10393 // and thus cannot access private fields of RHS
10394 std::array<void const*, sizeof...( MatcherTs )> m_matchers;
10395
10396 //! Avoids type nesting for `GenericAnyOf || GenericAnyOf` case
10397 template<typename... MatchersRHS>
10398 friend MatchAnyOfGeneric<MatcherTs..., MatchersRHS...> operator || (
10399 MatchAnyOfGeneric<MatcherTs...>&& lhs,
10400 MatchAnyOfGeneric<MatchersRHS...>&& rhs) {
10401 return MatchAnyOfGeneric<MatcherTs..., MatchersRHS...>{array_cat(CATCH_MOVE(lhs.m_matchers), CATCH_MOVE(rhs.m_matchers))};
10402 }
10403
10404 //! Avoids type nesting for `GenericAnyOf || some matcher` case
10405 template<typename MatcherRHS>
10406 friend std::enable_if_t<is_matcher<MatcherRHS>::value,
10407 MatchAnyOfGeneric<MatcherTs..., MatcherRHS>> operator || (
10408 MatchAnyOfGeneric<MatcherTs...>&& lhs,
10409 MatcherRHS const& rhs) {
10410 return MatchAnyOfGeneric<MatcherTs..., MatcherRHS>{array_cat(CATCH_MOVE(lhs.m_matchers), static_cast<void const*>(std::addressof(rhs)))};
10411 }
10412
10413 //! Avoids type nesting for `some matcher || GenericAnyOf` case
10414 template<typename MatcherLHS>
10415 friend std::enable_if_t<is_matcher<MatcherLHS>::value,
10416 MatchAnyOfGeneric<MatcherLHS, MatcherTs...>> operator || (
10417 MatcherLHS const& lhs,
10418 MatchAnyOfGeneric<MatcherTs...>&& rhs) {
10419 return MatchAnyOfGeneric<MatcherLHS, MatcherTs...>{array_cat(static_cast<void const*>(std::addressof(lhs)), CATCH_MOVE(rhs.m_matchers))};
10420 }
10421 };
10422
10423
10424 template<typename MatcherT>
10425 class MatchNotOfGeneric final : public MatcherGenericBase {
10426 MatcherT const& m_matcher;
10427
10428 public:
10429 MatchNotOfGeneric(MatchNotOfGeneric const&) = delete;
10430 MatchNotOfGeneric& operator=(MatchNotOfGeneric const&) = delete;
10431 MatchNotOfGeneric(MatchNotOfGeneric&&) = default;
10432 MatchNotOfGeneric& operator=(MatchNotOfGeneric&&) = default;
10433
10434 explicit MatchNotOfGeneric(MatcherT const& matcher) : m_matcher{matcher} {}
10435
10436 template<typename Arg>
10437 bool match(Arg&& arg) const {
10438 return !m_matcher.match(arg);
10439 }
10440
10441 std::string describe() const override {
10442 return "not " + m_matcher.toString();
10443 }
10444
10445 //! Negating negation can just unwrap and return underlying matcher
10446 friend MatcherT const& operator ! (MatchNotOfGeneric<MatcherT> const& matcher) {
10447 return matcher.m_matcher;
10448 }
10449 };
10450 } // namespace Detail
10451
10452
10453 // compose only generic matchers
10454 template<typename MatcherLHS, typename MatcherRHS>
10455 std::enable_if_t<Detail::are_generic_matchers<MatcherLHS, MatcherRHS>::value, Detail::MatchAllOfGeneric<MatcherLHS, MatcherRHS>>
10456 operator && (MatcherLHS const& lhs, MatcherRHS const& rhs) {
10457 return { lhs, rhs };
10458 }
10459
10460 template<typename MatcherLHS, typename MatcherRHS>
10461 std::enable_if_t<Detail::are_generic_matchers<MatcherLHS, MatcherRHS>::value, Detail::MatchAnyOfGeneric<MatcherLHS, MatcherRHS>>
10462 operator || (MatcherLHS const& lhs, MatcherRHS const& rhs) {
10463 return { lhs, rhs };
10464 }
10465
10466 //! Wrap provided generic matcher in generic negator
10467 template<typename MatcherT>
10468 std::enable_if_t<Detail::is_generic_matcher<MatcherT>::value, Detail::MatchNotOfGeneric<MatcherT>>
10469 operator ! (MatcherT const& matcher) {
10470 return Detail::MatchNotOfGeneric<MatcherT>{matcher};
10471 }
10472
10473
10474 // compose mixed generic and non-generic matchers
10475 template<typename MatcherLHS, typename ArgRHS>
10476 std::enable_if_t<Detail::is_generic_matcher<MatcherLHS>::value, Detail::MatchAllOfGeneric<MatcherLHS, MatcherBase<ArgRHS>>>
10477 operator && (MatcherLHS const& lhs, MatcherBase<ArgRHS> const& rhs) {
10478 return { lhs, rhs };
10479 }
10480
10481 template<typename ArgLHS, typename MatcherRHS>
10482 std::enable_if_t<Detail::is_generic_matcher<MatcherRHS>::value, Detail::MatchAllOfGeneric<MatcherBase<ArgLHS>, MatcherRHS>>
10483 operator && (MatcherBase<ArgLHS> const& lhs, MatcherRHS const& rhs) {
10484 return { lhs, rhs };
10485 }
10486
10487 template<typename MatcherLHS, typename ArgRHS>
10488 std::enable_if_t<Detail::is_generic_matcher<MatcherLHS>::value, Detail::MatchAnyOfGeneric<MatcherLHS, MatcherBase<ArgRHS>>>
10489 operator || (MatcherLHS const& lhs, MatcherBase<ArgRHS> const& rhs) {
10490 return { lhs, rhs };
10491 }
10492
10493 template<typename ArgLHS, typename MatcherRHS>
10494 std::enable_if_t<Detail::is_generic_matcher<MatcherRHS>::value, Detail::MatchAnyOfGeneric<MatcherBase<ArgLHS>, MatcherRHS>>
10495 operator || (MatcherBase<ArgLHS> const& lhs, MatcherRHS const& rhs) {
10496 return { lhs, rhs };
10497 }
10498
10499 } // namespace Matchers
10500 } // namespace Catch
10501
10502 #endif // CATCH_MATCHERS_TEMPLATED_HPP_INCLUDED
10503
10504 namespace Catch {
10505 namespace Matchers {
10506
10507 class IsEmptyMatcher final : public MatcherGenericBase {
10508 public:
10509 template <typename RangeLike>
10510 bool match(RangeLike&& rng) const {
10511 #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS)
10512 using Catch::Detail::empty;
10513 #else
10514 using std::empty;
10515 #endif
10516 return empty(rng);
10517 }
10518
10519 std::string describe() const override;
10520 };
10521
10522 class HasSizeMatcher final : public MatcherGenericBase {
10523 std::size_t m_target_size;
10524 public:
10525 explicit HasSizeMatcher(std::size_t target_size):
10526 m_target_size(target_size)
10527 {}
10528
10529 template <typename RangeLike>
10530 bool match(RangeLike&& rng) const {
10531 #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS)
10532 using Catch::Detail::size;
10533 #else
10534 using std::size;
10535 #endif
10536 return size(rng) == m_target_size;
10537 }
10538
10539 std::string describe() const override;
10540 };
10541
10542 template <typename Matcher>
10543 class SizeMatchesMatcher final : public MatcherGenericBase {
10544 Matcher m_matcher;
10545 public:
10546 explicit SizeMatchesMatcher(Matcher m):
10547 m_matcher(CATCH_MOVE(m))
10548 {}
10549
10550 template <typename RangeLike>
10551 bool match(RangeLike&& rng) const {
10552 #if defined(CATCH_CONFIG_POLYFILL_NONMEMBER_CONTAINER_ACCESS)
10553 using Catch::Detail::size;
10554 #else
10555 using std::size;
10556 #endif
10557 return m_matcher.match(size(rng));
10558 }
10559
10560 std::string describe() const override {
10561 return "size matches " + m_matcher.describe();
10562 }
10563 };
10564
10565
10566 //! Creates a matcher that accepts empty ranges/containers
10567 IsEmptyMatcher IsEmpty();
10568 //! Creates a matcher that accepts ranges/containers with specific size
10569 HasSizeMatcher SizeIs(std::size_t sz);
10570 template <typename Matcher>
10571 std::enable_if_t<Detail::is_matcher<Matcher>::value,
10572 SizeMatchesMatcher<Matcher>> SizeIs(Matcher&& m) {
10573 return SizeMatchesMatcher<Matcher>{CATCH_FORWARD(m)};
10574 }
10575
10576 } // end namespace Matchers
10577 } // end namespace Catch
10578
10579 #endif // CATCH_MATCHERS_CONTAINER_PROPERTIES_HPP_INCLUDED
10580
10581
10582 #ifndef CATCH_MATCHERS_CONTAINS_HPP_INCLUDED
10583 #define CATCH_MATCHERS_CONTAINS_HPP_INCLUDED
10584
10585
10586 #include <algorithm>
10587 #include <functional>
10588
10589 namespace Catch {
10590 namespace Matchers {
10591 //! Matcher for checking that an element in range is equal to specific element
10592 template <typename T, typename Equality>
10593 class ContainsElementMatcher final : public MatcherGenericBase {
10594 T m_desired;
10595 Equality m_eq;
10596 public:
10597 template <typename T2, typename Equality2>
10598 ContainsElementMatcher(T2&& target, Equality2&& predicate):
10599 m_desired(CATCH_FORWARD(target)),
10600 m_eq(CATCH_FORWARD(predicate))
10601 {}
10602
10603 std::string describe() const override {
10604 return "contains element " + Catch::Detail::stringify(m_desired);
10605 }
10606
10607 template <typename RangeLike>
10608 bool match(RangeLike&& rng) const {
10609 using std::begin; using std::end;
10610
10611 return end(rng) != std::find_if(begin(rng), end(rng),
10612 [&](auto const& elem) {
10613 return m_eq(elem, m_desired);
10614 });
10615 }
10616 };
10617
10618 //! Meta-matcher for checking that an element in a range matches a specific matcher
10619 template <typename Matcher>
10620 class ContainsMatcherMatcher final : public MatcherGenericBase {
10621 Matcher m_matcher;
10622 public:
10623 // Note that we do a copy+move to avoid having to SFINAE this
10624 // constructor (and also avoid some perfect forwarding failure
10625 // cases)
10626 ContainsMatcherMatcher(Matcher matcher):
10627 m_matcher(CATCH_MOVE(matcher))
10628 {}
10629
10630 template <typename RangeLike>
10631 bool match(RangeLike&& rng) const {
10632 for (auto&& elem : rng) {
10633 if (m_matcher.match(elem)) {
10634 return true;
10635 }
10636 }
10637 return false;
10638 }
10639
10640 std::string describe() const override {
10641 return "contains element matching " + m_matcher.describe();
10642 }
10643 };
10644
10645 /**
10646 * Creates a matcher that checks whether a range contains a specific element.
10647 *
10648 * Uses `std::equal_to` to do the comparison
10649 */
10650 template <typename T>
10651 std::enable_if_t<!Detail::is_matcher<T>::value,
10652 ContainsElementMatcher<T, std::equal_to<>>> Contains(T&& elem) {
10653 return { CATCH_FORWARD(elem), std::equal_to<>{} };
10654 }
10655
10656 //! Creates a matcher that checks whether a range contains element matching a matcher
10657 template <typename Matcher>
10658 std::enable_if_t<Detail::is_matcher<Matcher>::value,
10659 ContainsMatcherMatcher<Matcher>> Contains(Matcher&& matcher) {
10660 return { CATCH_FORWARD(matcher) };
10661 }
10662
10663 /**
10664 * Creates a matcher that checks whether a range contains a specific element.
10665 *
10666 * Uses `eq` to do the comparisons
10667 */
10668 template <typename T, typename Equality>
10669 ContainsElementMatcher<T, Equality> Contains(T&& elem, Equality&& eq) {
10670 return { CATCH_FORWARD(elem), CATCH_FORWARD(eq) };
10671 }
10672
10673 }
10674 }
10675
10676 #endif // CATCH_MATCHERS_CONTAINS_HPP_INCLUDED
10677
10678
10679 #ifndef CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED
10680 #define CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED
10681
10682
10683 namespace Catch {
10684 namespace Matchers {
10685
10686 class ExceptionMessageMatcher final : public MatcherBase<std::exception> {
10687 std::string m_message;
10688 public:
10689
10690 ExceptionMessageMatcher(std::string const& message):
10691 m_message(message)
10692 {}
10693
10694 bool match(std::exception const& ex) const override;
10695
10696 std::string describe() const override;
10697 };
10698
10699 //! Creates a matcher that checks whether a std derived exception has the provided message
10700 ExceptionMessageMatcher Message(std::string const& message);
10701
10702 } // namespace Matchers
10703 } // namespace Catch
10704
10705 #endif // CATCH_MATCHERS_EXCEPTION_HPP_INCLUDED
10706
10707
10708 #ifndef CATCH_MATCHERS_FLOATING_POINT_HPP_INCLUDED
10709 #define CATCH_MATCHERS_FLOATING_POINT_HPP_INCLUDED
10710
10711
10712 namespace Catch {
10713 namespace Matchers {
10714
10715 namespace Detail {
10716 enum class FloatingPointKind : uint8_t;
10717 }
10718
10719 class WithinAbsMatcher final : public MatcherBase<double> {
10720 public:
10721 WithinAbsMatcher(double target, double margin);
10722 bool match(double const& matchee) const override;
10723 std::string describe() const override;
10724 private:
10725 double m_target;
10726 double m_margin;
10727 };
10728
10729 class WithinUlpsMatcher final : public MatcherBase<double> {
10730 public:
10731 WithinUlpsMatcher( double target,
10732 uint64_t ulps,
10733 Detail::FloatingPointKind baseType );
10734 bool match(double const& matchee) const override;
10735 std::string describe() const override;
10736 private:
10737 double m_target;
10738 uint64_t m_ulps;
10739 Detail::FloatingPointKind m_type;
10740 };
10741
10742 // Given IEEE-754 format for floats and doubles, we can assume
10743 // that float -> double promotion is lossless. Given this, we can
10744 // assume that if we do the standard relative comparison of
10745 // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
10746 // the same result if we do this for floats, as if we do this for
10747 // doubles that were promoted from floats.
10748 class WithinRelMatcher final : public MatcherBase<double> {
10749 public:
10750 WithinRelMatcher( double target, double epsilon );
10751 bool match(double const& matchee) const override;
10752 std::string describe() const override;
10753 private:
10754 double m_target;
10755 double m_epsilon;
10756 };
10757
10758 //! Creates a matcher that accepts doubles within certain ULP range of target
10759 WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
10760 //! Creates a matcher that accepts floats within certain ULP range of target
10761 WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
10762 //! Creates a matcher that accepts numbers within certain range of target
10763 WithinAbsMatcher WithinAbs(double target, double margin);
10764
10765 //! Creates a matcher that accepts doubles within certain relative range of target
10766 WithinRelMatcher WithinRel(double target, double eps);
10767 //! Creates a matcher that accepts doubles within 100*DBL_EPS relative range of target
10768 WithinRelMatcher WithinRel(double target);
10769 //! Creates a matcher that accepts doubles within certain relative range of target
10770 WithinRelMatcher WithinRel(float target, float eps);
10771 //! Creates a matcher that accepts floats within 100*FLT_EPS relative range of target
10772 WithinRelMatcher WithinRel(float target);
10773
10774 } // namespace Matchers
10775 } // namespace Catch
10776
10777 #endif // CATCH_MATCHERS_FLOATING_POINT_HPP_INCLUDED
10778
10779
10780 #ifndef CATCH_MATCHERS_PREDICATE_HPP_INCLUDED
10781 #define CATCH_MATCHERS_PREDICATE_HPP_INCLUDED
10782
10783
10784 #include <string>
10785
10786 namespace Catch {
10787 namespace Matchers {
10788
10789 namespace Detail {
10790 std::string finalizeDescription(const std::string& desc);
10791 } // namespace Detail
10792
10793 template <typename T, typename Predicate>
10794 class PredicateMatcher final : public MatcherBase<T> {
10795 Predicate m_predicate;
10796 std::string m_description;
10797 public:
10798
10799 PredicateMatcher(Predicate&& elem, std::string const& descr)
10800 :m_predicate(CATCH_FORWARD(elem)),
10801 m_description(Detail::finalizeDescription(descr))
10802 {}
10803
10804 bool match( T const& item ) const override {
10805 return m_predicate(item);
10806 }
10807
10808 std::string describe() const override {
10809 return m_description;
10810 }
10811 };
10812
10813 /**
10814 * Creates a matcher that calls delegates `match` to the provided predicate.
10815 *
10816 * The user has to explicitly specify the argument type to the matcher
10817 */
10818 template<typename T, typename Pred>
10819 PredicateMatcher<T, Pred> Predicate(Pred&& predicate, std::string const& description = "") {
10820 static_assert(is_callable<Pred(T)>::value, "Predicate not callable with argument T");
10821 static_assert(std::is_same<bool, FunctionReturnType<Pred, T>>::value, "Predicate does not return bool");
10822 return PredicateMatcher<T, Pred>(CATCH_FORWARD(predicate), description);
10823 }
10824
10825 } // namespace Matchers
10826 } // namespace Catch
10827
10828 #endif // CATCH_MATCHERS_PREDICATE_HPP_INCLUDED
10829
10830
10831 #ifndef CATCH_MATCHERS_QUANTIFIERS_HPP_INCLUDED
10832 #define CATCH_MATCHERS_QUANTIFIERS_HPP_INCLUDED
10833
10834
10835 namespace Catch {
10836 namespace Matchers {
10837 // Matcher for checking that all elements in range matches a given matcher.
10838 template <typename Matcher>
10839 class AllMatchMatcher final : public MatcherGenericBase {
10840 Matcher m_matcher;
10841 public:
10842 AllMatchMatcher(Matcher matcher):
10843 m_matcher(CATCH_MOVE(matcher))
10844 {}
10845
10846 std::string describe() const override {
10847 return "all match " + m_matcher.describe();
10848 }
10849
10850 template <typename RangeLike>
10851 bool match(RangeLike&& rng) const {
10852 for (auto&& elem : rng) {
10853 if (!m_matcher.match(elem)) {
10854 return false;
10855 }
10856 }
10857 return true;
10858 }
10859 };
10860
10861 // Matcher for checking that no element in range matches a given matcher.
10862 template <typename Matcher>
10863 class NoneMatchMatcher final : public MatcherGenericBase {
10864 Matcher m_matcher;
10865 public:
10866 NoneMatchMatcher(Matcher matcher):
10867 m_matcher(CATCH_MOVE(matcher))
10868 {}
10869
10870 std::string describe() const override {
10871 return "none match " + m_matcher.describe();
10872 }
10873
10874 template <typename RangeLike>
10875 bool match(RangeLike&& rng) const {
10876 for (auto&& elem : rng) {
10877 if (m_matcher.match(elem)) {
10878 return false;
10879 }
10880 }
10881 return true;
10882 }
10883 };
10884
10885 // Matcher for checking that at least one element in range matches a given matcher.
10886 template <typename Matcher>
10887 class AnyMatchMatcher final : public MatcherGenericBase {
10888 Matcher m_matcher;
10889 public:
10890 AnyMatchMatcher(Matcher matcher):
10891 m_matcher(CATCH_MOVE(matcher))
10892 {}
10893
10894 std::string describe() const override {
10895 return "any match " + m_matcher.describe();
10896 }
10897
10898 template <typename RangeLike>
10899 bool match(RangeLike&& rng) const {
10900 for (auto&& elem : rng) {
10901 if (m_matcher.match(elem)) {
10902 return true;
10903 }
10904 }
10905 return false;
10906 }
10907 };
10908
10909 // Matcher for checking that all elements in range are true.
10910 class AllTrueMatcher final : public MatcherGenericBase {
10911 public:
10912 std::string describe() const override;
10913
10914 template <typename RangeLike>
10915 bool match(RangeLike&& rng) const {
10916 for (auto&& elem : rng) {
10917 if (!elem) {
10918 return false;
10919 }
10920 }
10921 return true;
10922 }
10923 };
10924
10925 // Matcher for checking that no element in range is true.
10926 class NoneTrueMatcher final : public MatcherGenericBase {
10927 public:
10928 std::string describe() const override;
10929
10930 template <typename RangeLike>
10931 bool match(RangeLike&& rng) const {
10932 for (auto&& elem : rng) {
10933 if (elem) {
10934 return false;
10935 }
10936 }
10937 return true;
10938 }
10939 };
10940
10941 // Matcher for checking that any element in range is true.
10942 class AnyTrueMatcher final : public MatcherGenericBase {
10943 public:
10944 std::string describe() const override;
10945
10946 template <typename RangeLike>
10947 bool match(RangeLike&& rng) const {
10948 for (auto&& elem : rng) {
10949 if (elem) {
10950 return true;
10951 }
10952 }
10953 return false;
10954 }
10955 };
10956
10957 // Creates a matcher that checks whether all elements in a range match a matcher
10958 template <typename Matcher>
10959 AllMatchMatcher<Matcher> AllMatch(Matcher&& matcher) {
10960 return { CATCH_FORWARD(matcher) };
10961 }
10962
10963 // Creates a matcher that checks whether no element in a range matches a matcher.
10964 template <typename Matcher>
10965 NoneMatchMatcher<Matcher> NoneMatch(Matcher&& matcher) {
10966 return { CATCH_FORWARD(matcher) };
10967 }
10968
10969 // Creates a matcher that checks whether any element in a range matches a matcher.
10970 template <typename Matcher>
10971 AnyMatchMatcher<Matcher> AnyMatch(Matcher&& matcher) {
10972 return { CATCH_FORWARD(matcher) };
10973 }
10974
10975 // Creates a matcher that checks whether all elements in a range are true
10976 AllTrueMatcher AllTrue();
10977
10978 // Creates a matcher that checks whether no element in a range is true
10979 NoneTrueMatcher NoneTrue();
10980
10981 // Creates a matcher that checks whether any element in a range is true
10982 AnyTrueMatcher AnyTrue();
10983 }
10984 }
10985
10986 #endif // CATCH_MATCHERS_QUANTIFIERS_HPP_INCLUDED
10987
10988
10989 #ifndef CATCH_MATCHERS_STRING_HPP_INCLUDED
10990 #define CATCH_MATCHERS_STRING_HPP_INCLUDED
10991
10992
10993 #include <string>
10994
10995 namespace Catch {
10996 namespace Matchers {
10997
10998 struct CasedString {
10999 CasedString( std::string const& str, CaseSensitive caseSensitivity );
11000 std::string adjustString( std::string const& str ) const;
11001 StringRef caseSensitivitySuffix() const;
11002
11003 CaseSensitive m_caseSensitivity;
11004 std::string m_str;
11005 };
11006
11007 class StringMatcherBase : public MatcherBase<std::string> {
11008 protected:
11009 CasedString m_comparator;
11010 StringRef m_operation;
11011
11012 public:
11013 StringMatcherBase( StringRef operation,
11014 CasedString const& comparator );
11015 std::string describe() const override;
11016 };
11017
11018 class StringEqualsMatcher final : public StringMatcherBase {
11019 public:
11020 StringEqualsMatcher( CasedString const& comparator );
11021 bool match( std::string const& source ) const override;
11022 };
11023 class StringContainsMatcher final : public StringMatcherBase {
11024 public:
11025 StringContainsMatcher( CasedString const& comparator );
11026 bool match( std::string const& source ) const override;
11027 };
11028 class StartsWithMatcher final : public StringMatcherBase {
11029 public:
11030 StartsWithMatcher( CasedString const& comparator );
11031 bool match( std::string const& source ) const override;
11032 };
11033 class EndsWithMatcher final : public StringMatcherBase {
11034 public:
11035 EndsWithMatcher( CasedString const& comparator );
11036 bool match( std::string const& source ) const override;
11037 };
11038
11039 class RegexMatcher final : public MatcherBase<std::string> {
11040 std::string m_regex;
11041 CaseSensitive m_caseSensitivity;
11042
11043 public:
11044 RegexMatcher( std::string regex, CaseSensitive caseSensitivity );
11045 bool match( std::string const& matchee ) const override;
11046 std::string describe() const override;
11047 };
11048
11049 //! Creates matcher that accepts strings that are exactly equal to `str`
11050 StringEqualsMatcher Equals( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes );
11051 //! Creates matcher that accepts strings that contain `str`
11052 StringContainsMatcher ContainsSubstring( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes );
11053 //! Creates matcher that accepts strings that _end_ with `str`
11054 EndsWithMatcher EndsWith( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes );
11055 //! Creates matcher that accepts strings that _start_ with `str`
11056 StartsWithMatcher StartsWith( std::string const& str, CaseSensitive caseSensitivity = CaseSensitive::Yes );
11057 //! Creates matcher that accepts strings matching `regex`
11058 RegexMatcher Matches( std::string const& regex, CaseSensitive caseSensitivity = CaseSensitive::Yes );
11059
11060 } // namespace Matchers
11061 } // namespace Catch
11062
11063 #endif // CATCH_MATCHERS_STRING_HPP_INCLUDED
11064
11065
11066 #ifndef CATCH_MATCHERS_VECTOR_HPP_INCLUDED
11067 #define CATCH_MATCHERS_VECTOR_HPP_INCLUDED
11068
11069
11070 #include <algorithm>
11071
11072 namespace Catch {
11073 namespace Matchers {
11074
11075 template<typename T, typename Alloc>
11076 class VectorContainsElementMatcher final : public MatcherBase<std::vector<T, Alloc>> {
11077 T const& m_comparator;
11078
11079 public:
11080 VectorContainsElementMatcher(T const& comparator):
11081 m_comparator(comparator)
11082 {}
11083
11084 bool match(std::vector<T, Alloc> const& v) const override {
11085 for (auto const& el : v) {
11086 if (el == m_comparator) {
11087 return true;
11088 }
11089 }
11090 return false;
11091 }
11092
11093 std::string describe() const override {
11094 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
11095 }
11096 };
11097
11098 template<typename T, typename AllocComp, typename AllocMatch>
11099 class ContainsMatcher final : public MatcherBase<std::vector<T, AllocMatch>> {
11100 std::vector<T, AllocComp> const& m_comparator;
11101
11102 public:
11103 ContainsMatcher(std::vector<T, AllocComp> const& comparator):
11104 m_comparator( comparator )
11105 {}
11106
11107 bool match(std::vector<T, AllocMatch> const& v) const override {
11108 // !TBD: see note in EqualsMatcher
11109 if (m_comparator.size() > v.size())
11110 return false;
11111 for (auto const& comparator : m_comparator) {
11112 auto present = false;
11113 for (const auto& el : v) {
11114 if (el == comparator) {
11115 present = true;
11116 break;
11117 }
11118 }
11119 if (!present) {
11120 return false;
11121 }
11122 }
11123 return true;
11124 }
11125 std::string describe() const override {
11126 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
11127 }
11128 };
11129
11130 template<typename T, typename AllocComp, typename AllocMatch>
11131 class EqualsMatcher final : public MatcherBase<std::vector<T, AllocMatch>> {
11132 std::vector<T, AllocComp> const& m_comparator;
11133
11134 public:
11135 EqualsMatcher(std::vector<T, AllocComp> const& comparator):
11136 m_comparator( comparator )
11137 {}
11138
11139 bool match(std::vector<T, AllocMatch> const& v) const override {
11140 // !TBD: This currently works if all elements can be compared using !=
11141 // - a more general approach would be via a compare template that defaults
11142 // to using !=. but could be specialised for, e.g. std::vector<T> etc
11143 // - then just call that directly
11144 if (m_comparator.size() != v.size())
11145 return false;
11146 for (std::size_t i = 0; i < v.size(); ++i)
11147 if (m_comparator[i] != v[i])
11148 return false;
11149 return true;
11150 }
11151 std::string describe() const override {
11152 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
11153 }
11154 };
11155
11156 template<typename T, typename AllocComp, typename AllocMatch>
11157 class ApproxMatcher final : public MatcherBase<std::vector<T, AllocMatch>> {
11158 std::vector<T, AllocComp> const& m_comparator;
11159 mutable Catch::Approx approx = Catch::Approx::custom();
11160
11161 public:
11162 ApproxMatcher(std::vector<T, AllocComp> const& comparator):
11163 m_comparator( comparator )
11164 {}
11165
11166 bool match(std::vector<T, AllocMatch> const& v) const override {
11167 if (m_comparator.size() != v.size())
11168 return false;
11169 for (std::size_t i = 0; i < v.size(); ++i)
11170 if (m_comparator[i] != approx(v[i]))
11171 return false;
11172 return true;
11173 }
11174 std::string describe() const override {
11175 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
11176 }
11177 template <typename = std::enable_if_t<std::is_constructible<double, T>::value>>
11178 ApproxMatcher& epsilon( T const& newEpsilon ) {
11179 approx.epsilon(static_cast<double>(newEpsilon));
11180 return *this;
11181 }
11182 template <typename = std::enable_if_t<std::is_constructible<double, T>::value>>
11183 ApproxMatcher& margin( T const& newMargin ) {
11184 approx.margin(static_cast<double>(newMargin));
11185 return *this;
11186 }
11187 template <typename = std::enable_if_t<std::is_constructible<double, T>::value>>
11188 ApproxMatcher& scale( T const& newScale ) {
11189 approx.scale(static_cast<double>(newScale));
11190 return *this;
11191 }
11192 };
11193
11194 template<typename T, typename AllocComp, typename AllocMatch>
11195 class UnorderedEqualsMatcher final : public MatcherBase<std::vector<T, AllocMatch>> {
11196 std::vector<T, AllocComp> const& m_target;
11197
11198 public:
11199 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target):
11200 m_target(target)
11201 {}
11202 bool match(std::vector<T, AllocMatch> const& vec) const override {
11203 if (m_target.size() != vec.size()) {
11204 return false;
11205 }
11206 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
11207 }
11208
11209 std::string describe() const override {
11210 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
11211 }
11212 };
11213
11214
11215 // The following functions create the actual matcher objects.
11216 // This allows the types to be inferred
11217
11218 //! Creates a matcher that matches vectors that contain all elements in `comparator`
11219 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
11220 ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
11221 return ContainsMatcher<T, AllocComp, AllocMatch>(comparator);
11222 }
11223
11224 //! Creates a matcher that matches vectors that contain `comparator` as an element
11225 template<typename T, typename Alloc = std::allocator<T>>
11226 VectorContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
11227 return VectorContainsElementMatcher<T, Alloc>(comparator);
11228 }
11229
11230 //! Creates a matcher that matches vectors that are exactly equal to `comparator`
11231 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
11232 EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
11233 return EqualsMatcher<T, AllocComp, AllocMatch>(comparator);
11234 }
11235
11236 //! Creates a matcher that matches vectors that `comparator` as an element
11237 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
11238 ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
11239 return ApproxMatcher<T, AllocComp, AllocMatch>(comparator);
11240 }
11241
11242 //! Creates a matcher that matches vectors that is equal to `target` modulo permutation
11243 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
11244 UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
11245 return UnorderedEqualsMatcher<T, AllocComp, AllocMatch>(target);
11246 }
11247
11248 } // namespace Matchers
11249 } // namespace Catch
11250
11251 #endif // CATCH_MATCHERS_VECTOR_HPP_INCLUDED
11252
11253 #endif // CATCH_MATCHERS_ALL_HPP_INCLUDED
11254
11255
11256 /** \file
11257 * This is a convenience header for Catch2's Reporter support. It includes
11258 * **all** of Catch2 headers related to reporters, including all reporters.
11259 *
11260 * Generally the Catch2 users should use specific includes they need,
11261 * but this header can be used instead for ease-of-experimentation, or
11262 * just plain convenience, at the cost of (significantly) increased
11263 * compilation times.
11264 *
11265 * When a new header (reporter) is added to either the `reporter` folder,
11266 * or to the corresponding internal subfolder, it should be added here.
11267 */
11268
11269 #ifndef CATCH_REPORTERS_ALL_HPP_INCLUDED
11270 #define CATCH_REPORTERS_ALL_HPP_INCLUDED
11271
11272
11273
11274 #ifndef CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
11275 #define CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
11276
11277
11278
11279 #ifndef CATCH_REPORTER_STREAMING_BASE_HPP_INCLUDED
11280 #define CATCH_REPORTER_STREAMING_BASE_HPP_INCLUDED
11281
11282
11283
11284 #ifndef CATCH_REPORTER_COMMON_BASE_HPP_INCLUDED
11285 #define CATCH_REPORTER_COMMON_BASE_HPP_INCLUDED
11286
11287
11288 #include <map>
11289 #include <string>
11290
11291 namespace Catch {
11292 class ColourImpl;
11293
11294 /**
11295 * This is the base class for all reporters.
11296 *
11297 * If are writing a reporter, you must derive from this type, or one
11298 * of the helper reporter bases that are derived from this type.
11299 *
11300 * ReporterBase centralizes handling of various common tasks in reporters,
11301 * like storing the right stream for the reporters to write to, and
11302 * providing the default implementation of the different listing events.
11303 */
11304 class ReporterBase : public IEventListener {
11305 protected:
11306 //! The stream wrapper as passed to us by outside code
11307 Detail::unique_ptr<IStream> m_wrapped_stream;
11308 //! Cached output stream from `m_wrapped_stream` to reduce
11309 //! number of indirect calls needed to write output.
11310 std::ostream& m_stream;
11311 //! Colour implementation this reporter was configured for
11312 Detail::unique_ptr<ColourImpl> m_colour;
11313 //! The custom reporter options user passed down to the reporter
11314 std::map<std::string, std::string> m_customOptions;
11315
11316 public:
11317 ReporterBase( ReporterConfig&& config );
11318 ~ReporterBase() override; // = default;
11319
11320 /**
11321 * Provides a simple default listing of reporters.
11322 *
11323 * Should look roughly like the reporter listing in v2 and earlier
11324 * versions of Catch2.
11325 */
11326 void listReporters(
11327 std::vector<ReporterDescription> const& descriptions ) override;
11328 /**
11329 * Provides a simple default listing of listeners
11330 *
11331 * Looks similarly to listing of reporters, but with listener type
11332 * instead of reporter name.
11333 */
11334 void listListeners(
11335 std::vector<ListenerDescription> const& descriptions ) override;
11336 /**
11337 * Provides a simple default listing of tests.
11338 *
11339 * Should look roughly like the test listing in v2 and earlier versions
11340 * of Catch2. Especially supports low-verbosity listing that mimics the
11341 * old `--list-test-names-only` output.
11342 */
11343 void listTests( std::vector<TestCaseHandle> const& tests ) override;
11344 /**
11345 * Provides a simple default listing of tags.
11346 *
11347 * Should look roughly like the tag listing in v2 and earlier versions
11348 * of Catch2.
11349 */
11350 void listTags( std::vector<TagInfo> const& tags ) override;
11351 };
11352 } // namespace Catch
11353
11354 #endif // CATCH_REPORTER_COMMON_BASE_HPP_INCLUDED
11355
11356 #include <vector>
11357
11358 namespace Catch {
11359
11360 class StreamingReporterBase : public ReporterBase {
11361 public:
11362 // GCC5 compat: we cannot use inherited constructor, because it
11363 // doesn't implement backport of P0136
11364 StreamingReporterBase(ReporterConfig&& _config):
11365 ReporterBase(CATCH_MOVE(_config))
11366 {}
11367 ~StreamingReporterBase() override;
11368
11369 void benchmarkPreparing( StringRef ) override {}
11370 void benchmarkStarting( BenchmarkInfo const& ) override {}
11371 void benchmarkEnded( BenchmarkStats<> const& ) override {}
11372 void benchmarkFailed( StringRef ) override {}
11373
11374 void fatalErrorEncountered( StringRef /*error*/ ) override {}
11375 void noMatchingTestCases( StringRef /*unmatchedSpec*/ ) override {}
11376 void reportInvalidTestSpec( StringRef /*invalidArgument*/ ) override {}
11377
11378 void testRunStarting( TestRunInfo const& _testRunInfo ) override;
11379
11380 void testCaseStarting(TestCaseInfo const& _testInfo) override {
11381 currentTestCaseInfo = &_testInfo;
11382 }
11383 void testCasePartialStarting( TestCaseInfo const&, uint64_t ) override {}
11384 void sectionStarting(SectionInfo const& _sectionInfo) override {
11385 m_sectionStack.push_back(_sectionInfo);
11386 }
11387
11388 void assertionStarting( AssertionInfo const& ) override {}
11389 void assertionEnded( AssertionStats const& ) override {}
11390
11391 void sectionEnded(SectionStats const& /* _sectionStats */) override {
11392 m_sectionStack.pop_back();
11393 }
11394 void testCasePartialEnded( TestCaseStats const&, uint64_t ) override {}
11395 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
11396 currentTestCaseInfo = nullptr;
11397 }
11398 void testRunEnded( TestRunStats const& /* _testRunStats */ ) override;
11399
11400 void skipTest(TestCaseInfo const&) override {
11401 // Don't do anything with this by default.
11402 // It can optionally be overridden in the derived class.
11403 }
11404
11405 protected:
11406 TestRunInfo currentTestRunInfo{ "test run has not started yet"_sr };
11407 TestCaseInfo const* currentTestCaseInfo = nullptr;
11408
11409 //! Stack of all _active_ sections in the _current_ test case
11410 std::vector<SectionInfo> m_sectionStack;
11411 };
11412
11413 } // end namespace Catch
11414
11415 #endif // CATCH_REPORTER_STREAMING_BASE_HPP_INCLUDED
11416
11417 #include <string>
11418
11419 namespace Catch {
11420
11421 class AutomakeReporter final : public StreamingReporterBase {
11422 public:
11423 // GCC5 compat: we cannot use inherited constructor, because it
11424 // doesn't implement backport of P0136
11425 AutomakeReporter(ReporterConfig&& _config):
11426 StreamingReporterBase(CATCH_MOVE(_config))
11427 {}
11428 ~AutomakeReporter() override;
11429
11430 static std::string getDescription() {
11431 using namespace std::string_literals;
11432 return "Reports test results in the format of Automake .trs files"s;
11433 }
11434
11435 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
11436 void skipTest(TestCaseInfo const& testInfo) override;
11437 };
11438
11439 } // end namespace Catch
11440
11441 #endif // CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
11442
11443
11444 #ifndef CATCH_REPORTER_COMPACT_HPP_INCLUDED
11445 #define CATCH_REPORTER_COMPACT_HPP_INCLUDED
11446
11447
11448
11449
11450 namespace Catch {
11451
11452 class CompactReporter final : public StreamingReporterBase {
11453 public:
11454 using StreamingReporterBase::StreamingReporterBase;
11455
11456 ~CompactReporter() override;
11457
11458 static std::string getDescription();
11459
11460 void noMatchingTestCases( StringRef unmatchedSpec ) override;
11461
11462 void testRunStarting( TestRunInfo const& _testInfo ) override;
11463
11464 void assertionEnded(AssertionStats const& _assertionStats) override;
11465
11466 void sectionEnded(SectionStats const& _sectionStats) override;
11467
11468 void testRunEnded(TestRunStats const& _testRunStats) override;
11469
11470 };
11471
11472 } // end namespace Catch
11473
11474 #endif // CATCH_REPORTER_COMPACT_HPP_INCLUDED
11475
11476
11477 #ifndef CATCH_REPORTER_CONSOLE_HPP_INCLUDED
11478 #define CATCH_REPORTER_CONSOLE_HPP_INCLUDED
11479
11480
11481 namespace Catch {
11482 // Fwd decls
11483 struct SummaryColumn;
11484 class TablePrinter;
11485
11486 class ConsoleReporter final : public StreamingReporterBase {
11487 Detail::unique_ptr<TablePrinter> m_tablePrinter;
11488
11489 public:
11490 ConsoleReporter(ReporterConfig&& config);
11491 ~ConsoleReporter() override;
11492 static std::string getDescription();
11493
11494 void noMatchingTestCases( StringRef unmatchedSpec ) override;
11495 void reportInvalidTestSpec( StringRef arg ) override;
11496
11497 void assertionStarting(AssertionInfo const&) override;
11498
11499 void assertionEnded(AssertionStats const& _assertionStats) override;
11500
11501 void sectionStarting(SectionInfo const& _sectionInfo) override;
11502 void sectionEnded(SectionStats const& _sectionStats) override;
11503
11504 void benchmarkPreparing( StringRef name ) override;
11505 void benchmarkStarting(BenchmarkInfo const& info) override;
11506 void benchmarkEnded(BenchmarkStats<> const& stats) override;
11507 void benchmarkFailed( StringRef error ) override;
11508
11509 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
11510 void testRunEnded(TestRunStats const& _testRunStats) override;
11511 void testRunStarting(TestRunInfo const& _testRunInfo) override;
11512
11513 private:
11514 void lazyPrint();
11515
11516 void lazyPrintWithoutClosingBenchmarkTable();
11517 void lazyPrintRunInfo();
11518 void printTestCaseAndSectionHeader();
11519
11520 void printClosedHeader(std::string const& _name);
11521 void printOpenHeader(std::string const& _name);
11522
11523 // if string has a : in first line will set indent to follow it on
11524 // subsequent lines
11525 void printHeaderString(std::string const& _string, std::size_t indent = 0);
11526
11527
11528 void printTotals(Totals const& totals);
11529 void printSummaryRow(StringRef label, std::vector<SummaryColumn> const& cols, std::size_t row);
11530
11531 void printTotalsDivider(Totals const& totals);
11532 void printSummaryDivider();
11533
11534 bool m_headerPrinted = false;
11535 bool m_testRunInfoPrinted = false;
11536 };
11537
11538 } // end namespace Catch
11539
11540 #endif // CATCH_REPORTER_CONSOLE_HPP_INCLUDED
11541
11542
11543 #ifndef CATCH_REPORTER_CUMULATIVE_BASE_HPP_INCLUDED
11544 #define CATCH_REPORTER_CUMULATIVE_BASE_HPP_INCLUDED
11545
11546
11547 #include <string>
11548 #include <vector>
11549
11550 namespace Catch {
11551
11552 namespace Detail {
11553
11554 //! Represents either an assertion or a benchmark result to be handled by cumulative reporter later
11555 class AssertionOrBenchmarkResult {
11556 // This should really be a variant, but this is much faster
11557 // to write and the data layout here is already terrible
11558 // enough that we do not have to care about the object size.
11559 Optional<AssertionStats> m_assertion;
11560 Optional<BenchmarkStats<>> m_benchmark;
11561 public:
11562 AssertionOrBenchmarkResult(AssertionStats const& assertion);
11563 AssertionOrBenchmarkResult(BenchmarkStats<> const& benchmark);
11564
11565 bool isAssertion() const;
11566 bool isBenchmark() const;
11567
11568 AssertionStats const& asAssertion() const;
11569 BenchmarkStats<> const& asBenchmark() const;
11570 };
11571 }
11572
11573 /**
11574 * Utility base for reporters that need to handle all results at once
11575 *
11576 * It stores tree of all test cases, sections and assertions, and after the
11577 * test run is finished, calls into `testRunEndedCumulative` to pass the
11578 * control to the deriving class.
11579 *
11580 * If you are deriving from this class and override any testing related
11581 * member functions, you should first call into the base's implementation to
11582 * avoid breaking the tree construction.
11583 *
11584 * Due to the way this base functions, it has to expand assertions up-front,
11585 * even if they are later unused (e.g. because the deriving reporter does
11586 * not report successful assertions, or because the deriving reporter does
11587 * not use assertion expansion at all). Derived classes can use two
11588 * customization points, `m_shouldStoreSuccesfulAssertions` and
11589 * `m_shouldStoreFailedAssertions`, to disable the expansion and gain extra
11590 * performance. **Accessing the assertion expansions if it wasn't stored is
11591 * UB.**
11592 */
11593 class CumulativeReporterBase : public ReporterBase {
11594 public:
11595 template<typename T, typename ChildNodeT>
11596 struct Node {
11597 explicit Node( T const& _value ) : value( _value ) {}
11598
11599 using ChildNodes = std::vector<Detail::unique_ptr<ChildNodeT>>;
11600 T value;
11601 ChildNodes children;
11602 };
11603 struct SectionNode {
11604 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
11605
11606 bool operator == (SectionNode const& other) const {
11607 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
11608 }
11609
11610 bool hasAnyAssertions() const;
11611
11612 SectionStats stats;
11613 std::vector<Detail::unique_ptr<SectionNode>> childSections;
11614 std::vector<Detail::AssertionOrBenchmarkResult> assertionsAndBenchmarks;
11615 std::string stdOut;
11616 std::string stdErr;
11617 };
11618
11619
11620 using TestCaseNode = Node<TestCaseStats, SectionNode>;
11621 using TestRunNode = Node<TestRunStats, TestCaseNode>;
11622
11623 // GCC5 compat: we cannot use inherited constructor, because it
11624 // doesn't implement backport of P0136
11625 CumulativeReporterBase(ReporterConfig&& _config):
11626 ReporterBase(CATCH_MOVE(_config))
11627 {}
11628 ~CumulativeReporterBase() override;
11629
11630 void benchmarkPreparing( StringRef ) override {}
11631 void benchmarkStarting( BenchmarkInfo const& ) override {}
11632 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11633 void benchmarkFailed( StringRef ) override {}
11634
11635 void noMatchingTestCases( StringRef ) override {}
11636 void reportInvalidTestSpec( StringRef ) override {}
11637 void fatalErrorEncountered( StringRef /*error*/ ) override {}
11638
11639 void testRunStarting( TestRunInfo const& ) override {}
11640
11641 void testCaseStarting( TestCaseInfo const& ) override {}
11642 void testCasePartialStarting( TestCaseInfo const&, uint64_t ) override {}
11643 void sectionStarting( SectionInfo const& sectionInfo ) override;
11644
11645 void assertionStarting( AssertionInfo const& ) override {}
11646
11647 void assertionEnded( AssertionStats const& assertionStats ) override;
11648 void sectionEnded( SectionStats const& sectionStats ) override;
11649 void testCasePartialEnded( TestCaseStats const&, uint64_t ) override {}
11650 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11651 void testRunEnded( TestRunStats const& testRunStats ) override;
11652 //! Customization point: called after last test finishes (testRunEnded has been handled)
11653 virtual void testRunEndedCumulative() = 0;
11654
11655 void skipTest(TestCaseInfo const&) override {}
11656
11657 protected:
11658 //! Should the cumulative base store the assertion expansion for succesful assertions?
11659 bool m_shouldStoreSuccesfulAssertions = true;
11660 //! Should the cumulative base store the assertion expansion for failed assertions?
11661 bool m_shouldStoreFailedAssertions = true;
11662
11663 // We need lazy construction here. We should probably refactor it
11664 // later, after the events are redone.
11665 //! The root node of the test run tree.
11666 Detail::unique_ptr<TestRunNode> m_testRun;
11667
11668 private:
11669 // Note: We rely on pointer identity being stable, which is why
11670 // we store pointers to the nodes rather than the values.
11671 std::vector<Detail::unique_ptr<TestCaseNode>> m_testCases;
11672 // Root section of the _current_ test case
11673 Detail::unique_ptr<SectionNode> m_rootSection;
11674 // Deepest section of the _current_ test case
11675 SectionNode* m_deepestSection = nullptr;
11676 // Stack of _active_ sections in the _current_ test case
11677 std::vector<SectionNode*> m_sectionStack;
11678 };
11679
11680 } // end namespace Catch
11681
11682 #endif // CATCH_REPORTER_CUMULATIVE_BASE_HPP_INCLUDED
11683
11684
11685 #ifndef CATCH_REPORTER_EVENT_LISTENER_HPP_INCLUDED
11686 #define CATCH_REPORTER_EVENT_LISTENER_HPP_INCLUDED
11687
11688
11689 namespace Catch {
11690
11691 /**
11692 * Base class to simplify implementing listeners.
11693 *
11694 * Provides empty default implementation for all IEventListener member
11695 * functions, so that a listener implementation can pick which
11696 * member functions it actually cares about.
11697 */
11698 class EventListenerBase : public IEventListener {
11699 public:
11700 using IEventListener::IEventListener;
11701
11702 void reportInvalidTestSpec( StringRef unmatchedSpec ) override;
11703 void fatalErrorEncountered( StringRef error ) override;
11704
11705 void benchmarkPreparing( StringRef name ) override;
11706 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
11707 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11708 void benchmarkFailed( StringRef error ) override;
11709
11710 void assertionStarting( AssertionInfo const& assertionInfo ) override;
11711 void assertionEnded( AssertionStats const& assertionStats ) override;
11712
11713 void listReporters(
11714 std::vector<ReporterDescription> const& descriptions ) override;
11715 void listListeners(
11716 std::vector<ListenerDescription> const& descriptions ) override;
11717 void listTests( std::vector<TestCaseHandle> const& tests ) override;
11718 void listTags( std::vector<TagInfo> const& tagInfos ) override;
11719
11720 void noMatchingTestCases( StringRef unmatchedSpec ) override;
11721 void testRunStarting( TestRunInfo const& testRunInfo ) override;
11722 void testCaseStarting( TestCaseInfo const& testInfo ) override;
11723 void testCasePartialStarting( TestCaseInfo const& testInfo,
11724 uint64_t partNumber ) override;
11725 void sectionStarting( SectionInfo const& sectionInfo ) override;
11726 void sectionEnded( SectionStats const& sectionStats ) override;
11727 void testCasePartialEnded( TestCaseStats const& testCaseStats,
11728 uint64_t partNumber ) override;
11729 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11730 void testRunEnded( TestRunStats const& testRunStats ) override;
11731 void skipTest( TestCaseInfo const& testInfo ) override;
11732 };
11733
11734 } // end namespace Catch
11735
11736 #endif // CATCH_REPORTER_EVENT_LISTENER_HPP_INCLUDED
11737
11738
11739 #ifndef CATCH_REPORTER_HELPERS_HPP_INCLUDED
11740 #define CATCH_REPORTER_HELPERS_HPP_INCLUDED
11741
11742 #include <iosfwd>
11743 #include <string>
11744 #include <vector>
11745
11746
11747 namespace Catch {
11748
11749 class IConfig;
11750 class TestCaseHandle;
11751 class ColourImpl;
11752
11753 // Returns double formatted as %.3f (format expected on output)
11754 std::string getFormattedDuration( double duration );
11755
11756 //! Should the reporter show duration of test given current configuration?
11757 bool shouldShowDuration( IConfig const& config, double duration );
11758
11759 std::string serializeFilters( std::vector<std::string> const& filters );
11760
11761 struct lineOfChars {
11762 char c;
11763 constexpr lineOfChars( char c_ ): c( c_ ) {}
11764
11765 friend std::ostream& operator<<( std::ostream& out, lineOfChars value );
11766 };
11767
11768 /**
11769 * Lists reporter descriptions to the provided stream in user-friendly
11770 * format
11771 *
11772 * Used as the default listing implementation by the first party reporter
11773 * bases. The output should be backwards compatible with the output of
11774 * Catch2 v2 binaries.
11775 */
11776 void
11777 defaultListReporters( std::ostream& out,
11778 std::vector<ReporterDescription> const& descriptions,
11779 Verbosity verbosity );
11780
11781 /**
11782 * Lists listeners descriptions to the provided stream in user-friendly
11783 * format
11784 */
11785 void defaultListListeners( std::ostream& out,
11786 std::vector<ListenerDescription> const& descriptions );
11787
11788 /**
11789 * Lists tag information to the provided stream in user-friendly format
11790 *
11791 * Used as the default listing implementation by the first party reporter
11792 * bases. The output should be backwards compatible with the output of
11793 * Catch2 v2 binaries.
11794 */
11795 void defaultListTags( std::ostream& out, std::vector<TagInfo> const& tags, bool isFiltered );
11796
11797 /**
11798 * Lists test case information to the provided stream in user-friendly
11799 * format
11800 *
11801 * Used as the default listing implementation by the first party reporter
11802 * bases. The output is backwards compatible with the output of Catch2
11803 * v2 binaries, and also supports the format specific to the old
11804 * `--list-test-names-only` option, for people who used it in integrations.
11805 */
11806 void defaultListTests( std::ostream& out,
11807 ColourImpl* streamColour,
11808 std::vector<TestCaseHandle> const& tests,
11809 bool isFiltered,
11810 Verbosity verbosity );
11811
11812 } // end namespace Catch
11813
11814 #endif // CATCH_REPORTER_HELPERS_HPP_INCLUDED
11815
11816
11817 #ifndef CATCH_REPORTER_JUNIT_HPP_INCLUDED
11818 #define CATCH_REPORTER_JUNIT_HPP_INCLUDED
11819
11820
11821
11822 namespace Catch {
11823
11824 class JunitReporter final : public CumulativeReporterBase {
11825 public:
11826 JunitReporter(ReporterConfig&& _config);
11827
11828 ~JunitReporter() override = default;
11829
11830 static std::string getDescription();
11831
11832 void testRunStarting(TestRunInfo const& runInfo) override;
11833
11834 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
11835 void assertionEnded(AssertionStats const& assertionStats) override;
11836
11837 void testCaseEnded(TestCaseStats const& testCaseStats) override;
11838
11839 void testRunEndedCumulative() override;
11840
11841 private:
11842 void writeRun(TestRunNode const& testRunNode, double suiteTime);
11843
11844 void writeTestCase(TestCaseNode const& testCaseNode);
11845
11846 void writeSection( std::string const& className,
11847 std::string const& rootName,
11848 SectionNode const& sectionNode,
11849 bool testOkToFail );
11850
11851 void writeAssertions(SectionNode const& sectionNode);
11852 void writeAssertion(AssertionStats const& stats);
11853
11854 XmlWriter xml;
11855 Timer suiteTimer;
11856 std::string stdOutForSuite;
11857 std::string stdErrForSuite;
11858 unsigned int unexpectedExceptions = 0;
11859 bool m_okToFail = false;
11860 };
11861
11862 } // end namespace Catch
11863
11864 #endif // CATCH_REPORTER_JUNIT_HPP_INCLUDED
11865
11866
11867 #ifndef CATCH_REPORTER_MULTI_HPP_INCLUDED
11868 #define CATCH_REPORTER_MULTI_HPP_INCLUDED
11869
11870
11871 namespace Catch {
11872
11873 class MultiReporter final : public IEventListener {
11874 /*
11875 * Stores all added reporters and listeners
11876 *
11877 * All Listeners are stored before all reporters, and individual
11878 * listeners/reporters are stored in order of insertion.
11879 */
11880 std::vector<IEventListenerPtr> m_reporterLikes;
11881 bool m_haveNoncapturingReporters = false;
11882
11883 // Keep track of how many listeners we have already inserted,
11884 // so that we can insert them into the main vector at the right place
11885 size_t m_insertedListeners = 0;
11886
11887 void updatePreferences(IEventListener const& reporterish);
11888
11889 public:
11890 using IEventListener::IEventListener;
11891
11892 void addListener( IEventListenerPtr&& listener );
11893 void addReporter( IEventListenerPtr&& reporter );
11894
11895 public: // IEventListener
11896
11897 void noMatchingTestCases( StringRef unmatchedSpec ) override;
11898 void fatalErrorEncountered( StringRef error ) override;
11899 void reportInvalidTestSpec( StringRef arg ) override;
11900
11901 void benchmarkPreparing( StringRef name ) override;
11902 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
11903 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11904 void benchmarkFailed( StringRef error ) override;
11905
11906 void testRunStarting( TestRunInfo const& testRunInfo ) override;
11907 void testCaseStarting( TestCaseInfo const& testInfo ) override;
11908 void testCasePartialStarting(TestCaseInfo const& testInfo, uint64_t partNumber) override;
11909 void sectionStarting( SectionInfo const& sectionInfo ) override;
11910 void assertionStarting( AssertionInfo const& assertionInfo ) override;
11911
11912 void assertionEnded( AssertionStats const& assertionStats ) override;
11913 void sectionEnded( SectionStats const& sectionStats ) override;
11914 void testCasePartialEnded(TestCaseStats const& testInfo, uint64_t partNumber) override;
11915 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11916 void testRunEnded( TestRunStats const& testRunStats ) override;
11917
11918 void skipTest( TestCaseInfo const& testInfo ) override;
11919
11920 void listReporters(std::vector<ReporterDescription> const& descriptions) override;
11921 void listListeners(std::vector<ListenerDescription> const& descriptions) override;
11922 void listTests(std::vector<TestCaseHandle> const& tests) override;
11923 void listTags(std::vector<TagInfo> const& tags) override;
11924
11925
11926 };
11927
11928 } // end namespace Catch
11929
11930 #endif // CATCH_REPORTER_MULTI_HPP_INCLUDED
11931
11932
11933 #ifndef CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
11934 #define CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
11935
11936
11937 #include <type_traits>
11938
11939 namespace Catch {
11940
11941 namespace Detail {
11942
11943 template <typename T, typename = void>
11944 struct has_description : std::false_type {};
11945
11946 template <typename T>
11947 struct has_description<
11948 T,
11949 void_t<decltype( T::getDescription() )>>
11950 : std::true_type {};
11951
11952 //! Indirection for reporter registration, so that the error handling is
11953 //! independent on the reporter's concrete type
11954 void registerReporterImpl( std::string const& name,
11955 IReporterFactoryPtr reporterPtr );
11956
11957 } // namespace Detail
11958
11959 class IEventListener;
11960 using IEventListenerPtr = Detail::unique_ptr<IEventListener>;
11961
11962 template <typename T>
11963 class ReporterFactory : public IReporterFactory {
11964
11965 IEventListenerPtr create( ReporterConfig&& config ) const override {
11966 return Detail::make_unique<T>( CATCH_MOVE(config) );
11967 }
11968
11969 std::string getDescription() const override {
11970 return T::getDescription();
11971 }
11972 };
11973
11974
11975 template<typename T>
11976 class ReporterRegistrar {
11977 public:
11978 explicit ReporterRegistrar( std::string const& name ) {
11979 registerReporterImpl( name,
11980 Detail::make_unique<ReporterFactory<T>>() );
11981 }
11982 };
11983
11984 template<typename T>
11985 class ListenerRegistrar {
11986
11987 class TypedListenerFactory : public EventListenerFactory {
11988 StringRef m_listenerName;
11989
11990 std::string getDescriptionImpl( std::true_type ) const {
11991 return T::getDescription();
11992 }
11993
11994 std::string getDescriptionImpl( std::false_type ) const {
11995 return "(No description provided)";
11996 }
11997
11998 public:
11999 TypedListenerFactory( StringRef listenerName ):
12000 m_listenerName( listenerName ) {}
12001
12002 IEventListenerPtr create( IConfig const* config ) const override {
12003 return Detail::make_unique<T>( config );
12004 }
12005
12006 StringRef getName() const override {
12007 return m_listenerName;
12008 }
12009
12010 std::string getDescription() const override {
12011 return getDescriptionImpl( Detail::has_description<T>{} );
12012 }
12013 };
12014
12015 public:
12016 ListenerRegistrar(StringRef listenerName) {
12017 getMutableRegistryHub().registerListener( Detail::make_unique<TypedListenerFactory>(listenerName) );
12018 }
12019 };
12020 }
12021
12022 #if !defined(CATCH_CONFIG_DISABLE)
12023
12024 # define CATCH_REGISTER_REPORTER( name, reporterType ) \
12025 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
12026 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
12027 namespace { \
12028 Catch::ReporterRegistrar<reporterType> INTERNAL_CATCH_UNIQUE_NAME( \
12029 catch_internal_RegistrarFor )( name ); \
12030 } \
12031 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
12032
12033 # define CATCH_REGISTER_LISTENER( listenerType ) \
12034 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
12035 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
12036 namespace { \
12037 Catch::ListenerRegistrar<listenerType> INTERNAL_CATCH_UNIQUE_NAME( \
12038 catch_internal_RegistrarFor )( #listenerType ); \
12039 } \
12040 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
12041
12042 #else // CATCH_CONFIG_DISABLE
12043
12044 #define CATCH_REGISTER_REPORTER(name, reporterType)
12045 #define CATCH_REGISTER_LISTENER(listenerType)
12046
12047 #endif // CATCH_CONFIG_DISABLE
12048
12049 #endif // CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
12050
12051
12052 #ifndef CATCH_REPORTER_SONARQUBE_HPP_INCLUDED
12053 #define CATCH_REPORTER_SONARQUBE_HPP_INCLUDED
12054
12055
12056
12057 namespace Catch {
12058
12059 class SonarQubeReporter final : public CumulativeReporterBase {
12060 public:
12061 SonarQubeReporter(ReporterConfig&& config)
12062 : CumulativeReporterBase(CATCH_MOVE(config))
12063 , xml(m_stream) {
12064 m_preferences.shouldRedirectStdOut = true;
12065 m_preferences.shouldReportAllAssertions = true;
12066 m_shouldStoreSuccesfulAssertions = false;
12067 }
12068
12069 ~SonarQubeReporter() override = default;
12070
12071 static std::string getDescription() {
12072 using namespace std::string_literals;
12073 return "Reports test results in the Generic Test Data SonarQube XML format"s;
12074 }
12075
12076 void testRunStarting( TestRunInfo const& testRunInfo ) override;
12077
12078 void testRunEndedCumulative() override {
12079 writeRun( *m_testRun );
12080 xml.endElement();
12081 }
12082
12083 void writeRun( TestRunNode const& groupNode );
12084
12085 void writeTestFile(std::string const& filename, std::vector<TestCaseNode const*> const& testCaseNodes);
12086
12087 void writeTestCase(TestCaseNode const& testCaseNode);
12088
12089 void writeSection(std::string const& rootName, SectionNode const& sectionNode, bool okToFail);
12090
12091 void writeAssertions(SectionNode const& sectionNode, bool okToFail);
12092
12093 void writeAssertion(AssertionStats const& stats, bool okToFail);
12094
12095 private:
12096 XmlWriter xml;
12097 };
12098
12099
12100 } // end namespace Catch
12101
12102 #endif // CATCH_REPORTER_SONARQUBE_HPP_INCLUDED
12103
12104
12105 #ifndef CATCH_REPORTER_TAP_HPP_INCLUDED
12106 #define CATCH_REPORTER_TAP_HPP_INCLUDED
12107
12108
12109 namespace Catch {
12110
12111 class TAPReporter final : public StreamingReporterBase {
12112 public:
12113 TAPReporter( ReporterConfig&& config ):
12114 StreamingReporterBase( CATCH_MOVE(config) ) {
12115 m_preferences.shouldReportAllAssertions = true;
12116 }
12117 ~TAPReporter() override = default;
12118
12119 static std::string getDescription() {
12120 using namespace std::string_literals;
12121 return "Reports test results in TAP format, suitable for test harnesses"s;
12122 }
12123
12124 void testRunStarting( TestRunInfo const& testInfo ) override;
12125
12126 void noMatchingTestCases( StringRef unmatchedSpec ) override;
12127
12128 void assertionEnded(AssertionStats const& _assertionStats) override;
12129
12130 void testRunEnded(TestRunStats const& _testRunStats) override;
12131
12132 private:
12133 std::size_t counter = 0;
12134 };
12135
12136 } // end namespace Catch
12137
12138 #endif // CATCH_REPORTER_TAP_HPP_INCLUDED
12139
12140
12141 #ifndef CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
12142 #define CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
12143
12144
12145 #include <cstring>
12146
12147 #ifdef __clang__
12148 # pragma clang diagnostic push
12149 # pragma clang diagnostic ignored "-Wpadded"
12150 #endif
12151
12152 namespace Catch {
12153
12154 class TeamCityReporter final : public StreamingReporterBase {
12155 public:
12156 TeamCityReporter( ReporterConfig&& _config )
12157 : StreamingReporterBase( CATCH_MOVE(_config) )
12158 {
12159 m_preferences.shouldRedirectStdOut = true;
12160 }
12161
12162 ~TeamCityReporter() override;
12163
12164 static std::string getDescription() {
12165 using namespace std::string_literals;
12166 return "Reports test results as TeamCity service messages"s;
12167 }
12168
12169 void testRunStarting( TestRunInfo const& groupInfo ) override;
12170 void testRunEnded( TestRunStats const& testGroupStats ) override;
12171
12172
12173 void assertionEnded(AssertionStats const& assertionStats) override;
12174
12175 void sectionStarting(SectionInfo const& sectionInfo) override {
12176 m_headerPrintedForThisSection = false;
12177 StreamingReporterBase::sectionStarting( sectionInfo );
12178 }
12179
12180 void testCaseStarting(TestCaseInfo const& testInfo) override;
12181
12182 void testCaseEnded(TestCaseStats const& testCaseStats) override;
12183
12184 private:
12185 void printSectionHeader(std::ostream& os);
12186
12187 bool m_headerPrintedForThisSection = false;
12188 Timer m_testTimer;
12189 };
12190
12191 } // end namespace Catch
12192
12193 #ifdef __clang__
12194 # pragma clang diagnostic pop
12195 #endif
12196
12197 #endif // CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
12198
12199
12200 #ifndef CATCH_REPORTER_XML_HPP_INCLUDED
12201 #define CATCH_REPORTER_XML_HPP_INCLUDED
12202
12203
12204
12205
12206 namespace Catch {
12207 class XmlReporter : public StreamingReporterBase {
12208 public:
12209 XmlReporter(ReporterConfig&& _config);
12210
12211 ~XmlReporter() override;
12212
12213 static std::string getDescription();
12214
12215 virtual std::string getStylesheetRef() const;
12216
12217 void writeSourceInfo(SourceLineInfo const& sourceInfo);
12218
12219 public: // StreamingReporterBase
12220
12221 void testRunStarting(TestRunInfo const& testInfo) override;
12222
12223 void testCaseStarting(TestCaseInfo const& testInfo) override;
12224
12225 void sectionStarting(SectionInfo const& sectionInfo) override;
12226
12227 void assertionStarting(AssertionInfo const&) override;
12228
12229 void assertionEnded(AssertionStats const& assertionStats) override;
12230
12231 void sectionEnded(SectionStats const& sectionStats) override;
12232
12233 void testCaseEnded(TestCaseStats const& testCaseStats) override;
12234
12235 void testRunEnded(TestRunStats const& testRunStats) override;
12236
12237 void benchmarkPreparing( StringRef name ) override;
12238 void benchmarkStarting(BenchmarkInfo const&) override;
12239 void benchmarkEnded(BenchmarkStats<> const&) override;
12240 void benchmarkFailed( StringRef error ) override;
12241
12242 void listReporters(std::vector<ReporterDescription> const& descriptions) override;
12243 void listListeners(std::vector<ListenerDescription> const& descriptions) override;
12244 void listTests(std::vector<TestCaseHandle> const& tests) override;
12245 void listTags(std::vector<TagInfo> const& tags) override;
12246
12247 private:
12248 Timer m_testCaseTimer;
12249 XmlWriter m_xml;
12250 int m_sectionDepth = 0;
12251 };
12252
12253 } // end namespace Catch
12254
12255 #endif // CATCH_REPORTER_XML_HPP_INCLUDED
12256
12257 #endif // CATCH_REPORTERS_ALL_HPP_INCLUDED
12258
12259 #endif // CATCH_ALL_HPP_INCLUDED
12260 #endif // CATCH_AMALGAMATED_HPP_INCLUDED