AlgoPlus v0.1.0
Loading...
Searching...
No Matches
catch.hpp
1/*
2 * Catch v2.13.9
3 * Generated: 2022-04-12 22:37:23.260201
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it
6 * directly Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved.
7 *
8 * Distributed under the Boost Software License, Version 1.0. (See accompanying
9 * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
10 */
11#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
13// start catch.hpp
14
15#define CATCH_VERSION_MAJOR 2
16#define CATCH_VERSION_MINOR 13
17#define CATCH_VERSION_PATCH 9
18
19#ifdef __clang__
20#pragma clang system_header
21#elif defined __GNUC__
22#pragma GCC system_header
23#endif
24
25// start catch_suppress_warnings.h
26
27#ifdef __clang__
28#ifdef __ICC // icpc defines the __clang__ macro
29#pragma warning(push)
30#pragma warning(disable : 161 1682)
31#else // __ICC
32#pragma clang diagnostic push
33#pragma clang diagnostic ignored "-Wpadded"
34#pragma clang diagnostic ignored "-Wswitch-enum"
35#pragma clang diagnostic ignored "-Wcovered-switch-default"
36#endif
37#elif defined __GNUC__
38// Because REQUIREs trigger GCC's -Wparentheses, and because still
39// supported version of g++ have only buggy support for _Pragmas,
40// Wparentheses have to be suppressed globally.
41#pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
42
43#pragma GCC diagnostic push
44#pragma GCC diagnostic ignored "-Wunused-variable"
45#pragma GCC diagnostic ignored "-Wpadded"
46#endif
47// end catch_suppress_warnings.h
48#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
49#define CATCH_IMPL
50#define CATCH_CONFIG_ALL_PARTS
51#endif
52
53// In the impl file, we want to have access to all parts of the headers
54// Can also be used to sanely support PCHs
55#if defined(CATCH_CONFIG_ALL_PARTS)
56#define CATCH_CONFIG_EXTERNAL_INTERFACES
57#if defined(CATCH_CONFIG_DISABLE_MATCHERS)
58#undef CATCH_CONFIG_DISABLE_MATCHERS
59#endif
60#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
61#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
62#endif
63#endif
64
65#if !defined(CATCH_CONFIG_IMPL_ONLY)
66// start catch_platform.h
67
68// See e.g.:
69// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
70#ifdef __APPLE__
71#include <TargetConditionals.h>
72#if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
73#define CATCH_PLATFORM_MAC
74#elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
75#define CATCH_PLATFORM_IPHONE
76#endif
77
78#elif defined(linux) || defined(__linux) || defined(__linux__)
79#define CATCH_PLATFORM_LINUX
80
81#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || \
82 defined(__MINGW32__)
83#define CATCH_PLATFORM_WINDOWS
84#endif
85
86// end catch_platform.h
87
88#ifdef CATCH_IMPL
89#ifndef CLARA_CONFIG_MAIN
90#define CLARA_CONFIG_MAIN_NOT_DEFINED
91#define CLARA_CONFIG_MAIN
92#endif
93#endif
94
95// start catch_user_interfaces.h
96
97namespace Catch {
98unsigned int rngSeed();
99}
100
101// end catch_user_interfaces.h
102// start catch_tag_alias_autoregistrar.h
103
104// start catch_common.h
105
106// start catch_compiler_capabilities.h
107
108// Detect a number of compiler features - by compiler
109// The following features are defined:
110//
111// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
112// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
113// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
114// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
115// ****************
116// Note to maintainers: if new toggles are added please document them
117// in configuration.md, too
118// ****************
119
120// In general each macro has a _NO_<feature name> form
121// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
122// Many features, at point of detection, define an _INTERNAL_ macro, so they
123// can be combined, en-mass, with the _NO_ forms later.
124
125#ifdef __cplusplus
126
127#if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
128#define CATCH_CPP14_OR_GREATER
129#endif
130
131#if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
132#define CATCH_CPP17_OR_GREATER
133#endif
134
135#endif
136
137// Only GCC compiler should be used in this block, so other compilers trying to
138// mask themselves as GCC should be ignored.
139#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && \
140 !defined(__LCC__)
141#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic push")
142#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic pop")
143
144#define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
145
146#endif
147
148#if defined(__clang__)
149
150#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("clang diagnostic push")
151#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("clang diagnostic pop")
152
153// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
154// which results in calls to destructors being emitted for each temporary,
155// without a matching initialization. In practice, this can result in something
156// like `std::string::~string` being called on an uninitialized value.
157//
158// For example, this code will likely segfault under IBM XL:
159// ```
160// REQUIRE(std::string("12") + "34" == "1234")
161// ```
162//
163// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
164#if !defined(__ibmxl__) && !defined(__CUDACC__)
165#define CATCH_INTERNAL_IGNORE_BUT_WARN(...) \
166 (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, \
167 hicpp-vararg) */
168#endif
169
170#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
171 _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
172 _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"")
173
174#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
175 _Pragma("clang diagnostic ignored \"-Wparentheses\"")
176
177#define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
178 _Pragma("clang diagnostic ignored \"-Wunused-variable\"")
179
180#define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
181 _Pragma("clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"")
182
183#define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
184 _Pragma("clang diagnostic ignored \"-Wunused-template\"")
185
186#endif // __clang__
187
189// Assume that non-Windows platforms support posix signals by default
190#if !defined(CATCH_PLATFORM_WINDOWS)
191#define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
192#endif
193
195// We know some environments not to support full POSIX signals
196#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
197#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
198#endif
199
200#ifdef __OS400__
201#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
202#define CATCH_CONFIG_COLOUR_NONE
203#endif
204
206// Android somehow still does not support std::to_string
207#if defined(__ANDROID__)
208#define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
209#define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
210#endif
211
213// Not all Windows environments support SEH properly
214#if defined(__MINGW32__)
215#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
216#endif
217
219// PS4
220#if defined(__ORBIS__)
221#define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
222#endif
223
225// Cygwin
226#ifdef __CYGWIN__
227
228// Required for some versions of Cygwin to declare gettimeofday
229// see:
230// http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
231#define _BSD_SOURCE
232// some versions of cygwin (most) do not support std::to_string. Use the libstd
233// check.
234// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html
235// line 2812-2813
236#if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) && \
237 !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
238
239#define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
240
241#endif
242#endif // __CYGWIN__
243
245// Visual C++
246#if defined(_MSC_VER)
247
248// Universal Windows platform does not support SEH
249// Or console colours (or console at all...)
250#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
251#define CATCH_CONFIG_COLOUR_NONE
252#else
253#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
254#endif
255
256#if !defined(__clang__) // Handle Clang masquerading for msvc
257
258// MSVC traditional preprocessor needs some workaround for __VA_ARGS__
259// _MSVC_TRADITIONAL == 0 means new conformant preprocessor
260// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
261#if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
262#define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
263#endif // MSVC_TRADITIONAL
264
265// Only do this if we're not using clang on Windows, which uses `diagnostic
266// push` & `diagnostic pop`
267#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma(warning(push))
268#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma(warning(pop))
269#endif // __clang__
270
271#endif // _MSC_VER
272
273#if defined(_REENTRANT) || defined(_MSC_VER)
274// Enable async processing, as -pthread is specified or no additional linking is
275// required
276#define CATCH_INTERNAL_CONFIG_USE_ASYNC
277#endif // _MSC_VER
278
280// Check if we are compiled with -fno-exceptions or equivalent
281#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
282#define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
283#endif
284
286// DJGPP
287#ifdef __DJGPP__
288#define CATCH_INTERNAL_CONFIG_NO_WCHAR
289#endif // __DJGPP__
290
292// Embarcadero C++Build
293#if defined(__BORLANDC__)
294#define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
295#endif
296
298
299// Use of __COUNTER__ is suppressed during code analysis in
300// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
301// handled by it.
302// Otherwise all supported compilers support COUNTER macro,
303// but user still might want to turn it off
304#if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L)
305#define CATCH_INTERNAL_CONFIG_COUNTER
306#endif
307
309
310// RTX is a special version of Windows that is real time.
311// This means that it is detected as Windows, but does not provide
312// the same set of capabilities as real Windows does.
313#if defined(UNDER_RTSS) || defined(RTX64_BUILD)
314#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
315#define CATCH_INTERNAL_CONFIG_NO_ASYNC
316#define CATCH_CONFIG_COLOUR_NONE
317#endif
318
319#if !defined(_GLIBCXX_USE_C99_MATH_TR1)
320#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
321#endif
322
323// Various stdlib support checks that require __has_include
324#if defined(__has_include)
325// Check if string_view is available and usable
326#if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
327#define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
328#endif
329
330// Check if optional is available and usable
331#if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
332#define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
333#endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
334
335// Check if byte is available and usable
336#if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
337#include <cstddef>
338#if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
339#define CATCH_INTERNAL_CONFIG_CPP17_BYTE
340#endif
341#endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
342
343// Check if variant is available and usable
344#if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
345#if defined(__clang__) && (__clang_major__ < 8)
346// work around clang bug with libstdc++
347// https://bugs.llvm.org/show_bug.cgi?id=31852 fix should be in clang 8,
348// workaround in libstdc++ 8.2
349#include <ciso646>
350#if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
351#define CATCH_CONFIG_NO_CPP17_VARIANT
352#else
353#define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
354#endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE
355 // < 9)
356#else
357#define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
358#endif // defined(__clang__) && (__clang_major__ < 8)
359#endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
360#endif // defined(__has_include)
361
362#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && \
363 !defined(CATCH_CONFIG_COUNTER)
364#define CATCH_CONFIG_COUNTER
365#endif
366#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && \
367 !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
368#define CATCH_CONFIG_WINDOWS_SEH
369#endif
370// This is set by default, because we assume that unix compilers are
371// posix-signal-compatible by default.
372#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && \
373 !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && \
374 !defined(CATCH_CONFIG_POSIX_SIGNALS)
375#define CATCH_CONFIG_POSIX_SIGNALS
376#endif
377// This is set by default, because we assume that compilers with no wchar_t
378// support are just rare exceptions.
379#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && \
380 !defined(CATCH_CONFIG_WCHAR)
381#define CATCH_CONFIG_WCHAR
382#endif
383
384#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && \
385 !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
386#define CATCH_CONFIG_CPP11_TO_STRING
387#endif
388
389#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && \
390 !defined(CATCH_CONFIG_CPP17_OPTIONAL)
391#define CATCH_CONFIG_CPP17_OPTIONAL
392#endif
393
394#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && \
395 !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
396#define CATCH_CONFIG_CPP17_STRING_VIEW
397#endif
398
399#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && \
400 !defined(CATCH_CONFIG_CPP17_VARIANT)
401#define CATCH_CONFIG_CPP17_VARIANT
402#endif
403
404#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && \
405 !defined(CATCH_CONFIG_CPP17_BYTE)
406#define CATCH_CONFIG_CPP17_BYTE
407#endif
408
409#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
410#define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
411#endif
412
413#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && \
414 !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && \
415 !defined(CATCH_CONFIG_NEW_CAPTURE)
416#define CATCH_CONFIG_NEW_CAPTURE
417#endif
418
419#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
420#define CATCH_CONFIG_DISABLE_EXCEPTIONS
421#endif
422
423#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && \
424 !defined(CATCH_CONFIG_POLYFILL_ISNAN)
425#define CATCH_CONFIG_POLYFILL_ISNAN
426#endif
427
428#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && \
429 !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
430#define CATCH_CONFIG_USE_ASYNC
431#endif
432
433#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && \
434 !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
435#define CATCH_CONFIG_ANDROID_LOGWRITE
436#endif
437
438#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && \
439 !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
440#define CATCH_CONFIG_GLOBAL_NEXTAFTER
441#endif
442
443// Even if we do not think the compiler has that warning, we still have
444// to provide a macro that can be used by the code.
445#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
446#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
447#endif
448#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
449#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
450#endif
451#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
452#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
453#endif
454#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
455#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
456#endif
457#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
458#define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
459#endif
460#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
461#define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
462#endif
463
464// The goal of this macro is to avoid evaluation of the arguments, but
465// still have the compiler warn on problems inside...
466#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
467#define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
468#endif
469
470#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
471#undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
472#elif defined(__clang__) && (__clang_major__ < 5)
473#undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
474#endif
475
476#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
477#define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
478#endif
479
480#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
481#define CATCH_TRY if ((true))
482#define CATCH_CATCH_ALL if ((false))
483#define CATCH_CATCH_ANON(type) if ((false))
484#else
485#define CATCH_TRY try
486#define CATCH_CATCH_ALL catch (...)
487#define CATCH_CATCH_ANON(type) catch (type)
488#endif
489
490#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && \
491 !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && \
492 !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
493#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
494#endif
495
496// end catch_compiler_capabilities.h
497#define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line
498#define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line)
499#ifdef CATCH_CONFIG_COUNTER
500#define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__)
501#else
502#define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__)
503#endif
504
505#include <cstdint>
506#include <iosfwd>
507#include <string>
508
509// We need a dummy global operator<< so we can bring it into Catch namespace
510// later
512std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
513
514namespace Catch {
515
517 enum Choice { Yes, No };
518};
519
520class NonCopyable {
521 NonCopyable(NonCopyable const&) = delete;
522 NonCopyable(NonCopyable&&) = delete;
523 NonCopyable& operator=(NonCopyable const&) = delete;
524 NonCopyable& operator=(NonCopyable&&) = delete;
525
526 protected:
527 NonCopyable();
528 virtual ~NonCopyable();
529};
530
531struct SourceLineInfo {
532
533 SourceLineInfo() = delete;
534 SourceLineInfo(char const* _file, std::size_t _line) noexcept : file(_file), line(_line) {}
535
536 SourceLineInfo(SourceLineInfo const& other) = default;
537 SourceLineInfo& operator=(SourceLineInfo const&) = default;
538 SourceLineInfo(SourceLineInfo&&) noexcept = default;
539 SourceLineInfo& operator=(SourceLineInfo&&) noexcept = default;
540
541 bool empty() const noexcept { return file[0] == '\0'; }
542 bool operator==(SourceLineInfo const& other) const noexcept;
543 bool operator<(SourceLineInfo const& other) const noexcept;
544
545 char const* file;
546 std::size_t line;
547};
548
549std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info);
550
551// Bring in operator<< from global namespace into Catch namespace
552// This is necessary because the overload of operator<< above makes
553// lookup stop at namespace Catch
554using ::operator<<;
555
556// Use this in variadic streaming macros to allow
557// >> +StreamEndStop
558// as well as
559// >> stuff +StreamEndStop
561 std::string operator+() const;
562};
563template <typename T> T const& operator+(T const& value, StreamEndStop) {
564 return value;
565}
566} // namespace Catch
567
568#define CATCH_INTERNAL_LINEINFO \
569 ::Catch::SourceLineInfo(__FILE__, static_cast<std::size_t>(__LINE__))
570
571// end catch_common.h
572namespace Catch {
573
574struct RegistrarForTagAliases {
575 RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo);
576};
577
578} // end namespace Catch
579
580#define CATCH_REGISTER_TAG_ALIAS(alias, spec) \
581 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
582 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
583 namespace { \
584 Catch::RegistrarForTagAliases \
585 INTERNAL_CATCH_UNIQUE_NAME(AutoRegisterTagAlias)(alias, spec, CATCH_INTERNAL_LINEINFO); \
586 } \
587 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
588
589// end catch_tag_alias_autoregistrar.h
590// start catch_test_registry.h
591
592// start catch_interfaces_testcase.h
593
594#include <vector>
595
596namespace Catch {
597
598class TestSpec;
599
601 virtual void invoke() const = 0;
602 virtual ~ITestInvoker();
603};
604
605class TestCase;
606struct IConfig;
607
609 virtual ~ITestCaseRegistry();
610 virtual std::vector<TestCase> const& getAllTests() const = 0;
611 virtual std::vector<TestCase> const& getAllTestsSorted(IConfig const& config) const = 0;
612};
613
614bool isThrowSafe(TestCase const& testCase, IConfig const& config);
615bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config);
616std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases, TestSpec const& testSpec,
617 IConfig const& config);
618std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config);
619
620} // namespace Catch
621
622// end catch_interfaces_testcase.h
623// start catch_stringref.h
624
625#include <cassert>
626#include <cstddef>
627#include <iosfwd>
628#include <string>
629
630namespace Catch {
631
635class StringRef {
636 public:
637 using size_type = std::size_t;
638 using const_iterator = const char*;
639
640 private:
641 static constexpr char const* const s_empty = "";
642
643 char const* m_start = s_empty;
644 size_type m_size = 0;
645
646 public: // construction
647 constexpr StringRef() noexcept = default;
648
649 StringRef(char const* rawChars) noexcept;
650
651 constexpr StringRef(char const* rawChars, size_type size) noexcept
652 : m_start(rawChars), m_size(size) {}
653
654 StringRef(std::string const& stdString) noexcept
655 : m_start(stdString.c_str()), m_size(stdString.size()) {}
656
657 explicit operator std::string() const { return std::string(m_start, m_size); }
658
659 public: // operators
660 auto operator==(StringRef const& other) const noexcept -> bool;
661 auto operator!=(StringRef const& other) const noexcept -> bool { return !(*this == other); }
662
663 auto operator[](size_type index) const noexcept -> char {
664 assert(index < m_size);
665 return m_start[index];
666 }
667
668 public: // named queries
669 constexpr auto empty() const noexcept -> bool { return m_size == 0; }
670 constexpr auto size() const noexcept -> size_type { return m_size; }
671
672 // Returns the current start pointer. If the StringRef is not
673 // null-terminated, throws std::domain_exception
674 auto c_str() const -> char const*;
675
676 public: // substrings and searches
677 // Returns a substring of [start, start + length).
678 // If start + length > size(), then the substring is [start, size()).
679 // If start > size(), then the substring is empty.
680 auto substr(size_type start, size_type length) const noexcept -> StringRef;
681
682 // Returns the current start pointer. May not be null-terminated.
683 auto data() const noexcept -> char const*;
684
685 constexpr auto isNullTerminated() const noexcept -> bool { return m_start[m_size] == '\0'; }
686
687 public: // iterators
688 constexpr const_iterator begin() const { return m_start; }
689 constexpr const_iterator end() const { return m_start + m_size; }
690};
691
692auto operator+=(std::string& lhs, StringRef const& sr) -> std::string&;
693auto operator<<(std::ostream& os, StringRef const& sr) -> std::ostream&;
694
695constexpr auto operator"" _sr(char const* rawChars, std::size_t size) noexcept -> StringRef {
696 return StringRef(rawChars, size);
697}
698} // namespace Catch
699
700constexpr auto operator"" _catch_sr(char const* rawChars, std::size_t size) noexcept
702 return Catch::StringRef(rawChars, size);
703}
704
705// end catch_stringref.h
706// start catch_preprocessor.hpp
707
708#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
709#define CATCH_RECURSION_LEVEL1(...) \
710 CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
711#define CATCH_RECURSION_LEVEL2(...) \
712 CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
713#define CATCH_RECURSION_LEVEL3(...) \
714 CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
715#define CATCH_RECURSION_LEVEL4(...) \
716 CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
717#define CATCH_RECURSION_LEVEL5(...) \
718 CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
719
720#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
721#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
722// MSVC needs more evaluations
723#define CATCH_RECURSION_LEVEL6(...) \
724 CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
725#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
726#else
727#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
728#endif
729
730#define CATCH_REC_END(...)
731#define CATCH_REC_OUT
732
733#define CATCH_EMPTY()
734#define CATCH_DEFER(id) id CATCH_EMPTY()
735
736#define CATCH_REC_GET_END2() 0, CATCH_REC_END
737#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
738#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
739#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
740#define CATCH_REC_NEXT1(test, next) CATCH_DEFER(CATCH_REC_NEXT0)(test, next, 0)
741#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
742
743#define CATCH_REC_LIST0(f, x, peek, ...) \
744 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
745#define CATCH_REC_LIST1(f, x, peek, ...) \
746 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0))(f, peek, __VA_ARGS__)
747#define CATCH_REC_LIST2(f, x, peek, ...) \
748 f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
749
750#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) \
751 , f(userdata, x) \
752 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
753#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) \
754 , f(userdata, x) \
755 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD))(f, userdata, peek, __VA_ARGS__)
756#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) \
757 f(userdata, x) \
758 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
759
760// Applies the function macro `f` to each of the remaining parameters, inserts
761// commas between the results, and passes userdata as the first parameter to
762// each invocation, e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a),
763// f(x, b), f(x, c)
764#define CATCH_REC_LIST_UD(f, userdata, ...) \
765 CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
766
767#define CATCH_REC_LIST(f, ...) \
768 CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
769
770#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
771#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO##__VA_ARGS__
772#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
773#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
774#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
775#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
776#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
777#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
778 INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
779#else
780// MSVC is adding extra space and needs another indirection to expand
781// INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
782#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
783#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
784#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
785 (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
786#endif
787
788#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
789#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
790
791#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
792
793#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
794#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
795 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
796#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
797 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
798#else
799#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
800 INTERNAL_CATCH_EXPAND_VARGS( \
801 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
802#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
803 INTERNAL_CATCH_EXPAND_VARGS( \
804 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
805#endif
806
807#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...) \
808 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST, __VA_ARGS__)
809
810#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
811#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) \
812 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
813#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) \
814 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
815#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) \
816 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
817#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) \
818 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
819#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) \
820 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
821#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) \
822 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
823#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) \
824 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
825#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) \
826 INTERNAL_CATCH_REMOVE_PARENS(_0), \
827 INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
828#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \
829 INTERNAL_CATCH_REMOVE_PARENS(_0), \
830 INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
831#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \
832 INTERNAL_CATCH_REMOVE_PARENS(_0), \
833 INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
834
835#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
836
837#define INTERNAL_CATCH_TYPE_GEN \
838 template <typename...> struct TypeList {}; \
839 template <typename... Ts> constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { \
840 return {}; \
841 } \
842 template <template <typename...> class...> struct TemplateTypeList {}; \
843 template <template <typename...> class... Cs> \
844 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { \
845 return {}; \
846 } \
847 template <typename...> struct append; \
848 template <typename...> struct rewrap; \
849 template <template <typename...> class, typename...> struct create; \
850 template <template <typename...> class, typename> struct convert; \
851 \
852 template <typename T> struct append<T> { \
853 using type = T; \
854 }; \
855 template <template <typename...> class L1, typename... E1, template <typename...> class L2, \
856 typename... E2, typename... Rest> \
857 struct append<L1<E1...>, L2<E2...>, Rest...> { \
858 using type = typename append<L1<E1..., E2...>, Rest...>::type; \
859 }; \
860 template <template <typename...> class L1, typename... E1, typename... Rest> \
861 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { \
862 using type = L1<E1...>; \
863 }; \
864 \
865 template <template <typename...> class Container, template <typename...> class List, \
866 typename... elems> \
867 struct rewrap<TemplateTypeList<Container>, List<elems...>> { \
868 using type = TypeList<Container<elems...>>; \
869 }; \
870 template <template <typename...> class Container, template <typename...> class List, \
871 class... Elems, typename... Elements> \
872 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { \
873 using type = typename append< \
874 TypeList<Container<Elems...>>, \
875 typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; \
876 }; \
877 \
878 template <template <typename...> class Final, template <typename...> class... Containers, \
879 typename... Types> \
880 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { \
881 using type = typename append< \
882 Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; \
883 }; \
884 template <template <typename...> class Final, template <typename...> class List, \
885 typename... Ts> \
886 struct convert<Final, List<Ts...>> { \
887 using type = typename append<Final<>, TypeList<Ts>...>::type; \
888 };
889
890#define INTERNAL_CATCH_NTTP_1(signature, ...) \
891 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp {}; \
892 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
893 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { \
894 return {}; \
895 } \
896 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> \
897 struct NttpTemplateTypeList {}; \
898 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Cs> \
899 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { \
900 return {}; \
901 } \
902 \
903 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
904 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, \
905 INTERNAL_CATCH_REMOVE_PARENS(signature)> \
906 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { \
907 using type = TypeList<Container<__VA_ARGS__>>; \
908 }; \
909 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
910 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, \
911 INTERNAL_CATCH_REMOVE_PARENS(signature), typename... Elements> \
912 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { \
913 using type = typename append< \
914 TypeList<Container<__VA_ARGS__>>, \
915 typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; \
916 }; \
917 template <template <typename...> class Final, \
918 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Containers, \
919 typename... Types> \
920 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { \
921 using type = typename append< \
922 Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; \
923 };
924
925#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
926#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature) \
927 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
928#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...) \
929 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
930
931#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
932#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature) \
933 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
934#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...) \
935 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
936
937#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature) \
938 template <typename Type> void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags) { \
939 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, \
940 Catch::StringRef(), nameAndTags); \
941 }
942
943#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...) \
944 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
945 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags) { \
946 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, \
947 Catch::StringRef(), nameAndTags); \
948 }
949
950#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...) \
951 template <typename Type> \
952 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
953 Catch::AutoReg(Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, \
954 className, nameAndTags); \
955 }
956
957#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...) \
958 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
959 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
960 Catch::AutoReg(Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), \
961 CATCH_INTERNAL_LINEINFO, className, nameAndTags); \
962 }
963
964#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
965#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature) \
966 template <typename TestType> \
967 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
968 void test(); \
969 }
970
971#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...) \
972 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
973 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
974 void test(); \
975 }
976
977#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
978#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature) \
979 template <typename TestType> \
980 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
981#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...) \
982 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
983 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
984
985#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
986#define INTERNAL_CATCH_NTTP_0
987#define INTERNAL_CATCH_NTTP_GEN(...) \
988 INTERNAL_CATCH_VA_NARGS_IMPL( \
989 __VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
990 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
991 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
992 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
993 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
994 INTERNAL_CATCH_NTTP_0)
995#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
996 INTERNAL_CATCH_VA_NARGS_IMPL( \
997 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
998 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
999 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1000 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1001 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1002 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1003 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
1004#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1005 INTERNAL_CATCH_VA_NARGS_IMPL( \
1006 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1007 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1008 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1009 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1010 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1011 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1012 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
1013#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1014 INTERNAL_CATCH_VA_NARGS_IMPL( \
1015 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1016 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1017 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1018 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1019 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1020 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1021 INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
1022#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1023 INTERNAL_CATCH_VA_NARGS_IMPL( \
1024 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1025 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1026 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1027 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, \
1028 INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
1029#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1030 INTERNAL_CATCH_VA_NARGS_IMPL( \
1031 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1032 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1033 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1034 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1035 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1036 INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
1037#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1038 INTERNAL_CATCH_VA_NARGS_IMPL( \
1039 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1040 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1041 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1042 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1043 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1044 INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
1045#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1046 INTERNAL_CATCH_VA_NARGS_IMPL( \
1047 __VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG, INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1048 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1049 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1050 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1051 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1052 INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
1053#else
1054#define INTERNAL_CATCH_NTTP_0(signature)
1055#define INTERNAL_CATCH_NTTP_GEN(...) \
1056 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1057 __VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1058 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1059 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1060 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)(__VA_ARGS__))
1061#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
1062 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1063 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1064 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1065 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1066 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1067 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1068 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1069 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
1070#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1071 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1072 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1073 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1074 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1075 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1076 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1077 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1078 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
1079#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1080 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1081 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1082 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1083 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1084 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1085 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1086 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1087 INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
1088#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1089 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1090 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1091 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1092 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1093 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, \
1094 INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
1095#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1096 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1097 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1098 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1099 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1100 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1101 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1102 INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
1103#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1104 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1105 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1106 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1107 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1108 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1109 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1110 INTERNAL_CATCH_DECLARE_SIG_TEST1, \
1111 INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
1112#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1113 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1114 __VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG, INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1115 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1116 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1117 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1118 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1119 INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
1120#endif
1121
1122// end catch_preprocessor.hpp
1123// start catch_meta.hpp
1124
1125#include <type_traits>
1126
1127namespace Catch {
1128template <typename T> struct always_false : std::false_type {};
1129
1130template <typename> struct true_given : std::true_type {};
1132 template <typename Fun, typename... Args>
1133 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
1134 template <typename...> std::false_type static test(...);
1135};
1136
1137template <typename T> struct is_callable;
1138
1139template <typename Fun, typename... Args>
1140struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
1141
1142#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
1143// std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
1144// replaced with std::invoke_result here.
1145template <typename Func, typename... U>
1146using FunctionReturnType =
1147 std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
1148#else
1149// Keep ::type here because we still support C++11
1150template <typename Func, typename... U>
1151using FunctionReturnType = typename std::remove_reference<
1152 typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
1153#endif
1154
1155} // namespace Catch
1156
1157namespace mpl_ {
1158struct na;
1159}
1160
1161// end catch_meta.hpp
1162namespace Catch {
1163
1164template <typename C> class TestInvokerAsMethod : public ITestInvoker {
1165 void (C::*m_testAsMethod)();
1166
1167 public:
1168 TestInvokerAsMethod(void (C::*testAsMethod)()) noexcept : m_testAsMethod(testAsMethod) {}
1169
1170 void invoke() const override {
1171 C obj;
1172 (obj.*m_testAsMethod)();
1173 }
1174};
1175
1176auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker*;
1177
1178template <typename C> auto makeTestInvoker(void (C::*testAsMethod)()) noexcept -> ITestInvoker* {
1179 return new (std::nothrow) TestInvokerAsMethod<C>(testAsMethod);
1180}
1181
1182struct NameAndTags {
1183 NameAndTags(StringRef const& name_ = StringRef(),
1184 StringRef const& tags_ = StringRef()) noexcept;
1185 StringRef name;
1186 StringRef tags;
1187};
1188
1189struct AutoReg : NonCopyable {
1190 AutoReg(ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod,
1191 NameAndTags const& nameAndTags) noexcept;
1192 ~AutoReg();
1193};
1194
1195} // end namespace Catch
1196
1197#if defined(CATCH_CONFIG_DISABLE)
1198#define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(TestName, ...) static void TestName()
1199#define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(TestName, ClassName, ...) \
1200 namespace { \
1201 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1202 void test(); \
1203 }; \
1204 } \
1205 void TestName::test()
1206#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(TestName, TestFunc, Name, Tags, \
1207 Signature, ...) \
1208 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1209#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1210 TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
1211 namespace { \
1212 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1213 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, \
1214 INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1215 } \
1216 } \
1217 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1218
1219#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1220#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1221 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1222 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1223 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1224 typename TestType, __VA_ARGS__)
1225#else
1226#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1227 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1228 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1229 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1230 typename TestType, __VA_ARGS__))
1231#endif
1232
1233#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1234#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1235 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1236 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1237 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1238 Signature, __VA_ARGS__)
1239#else
1240#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1241 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1242 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1243 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1244 Signature, __VA_ARGS__))
1245#endif
1246
1247#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1248#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1249 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1250 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1251 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1252 typename T, __VA_ARGS__)
1253#else
1254#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1255 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1256 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1257 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1258 typename T, __VA_ARGS__))
1259#endif
1260
1261#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1262#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(ClassName, Name, Tags, \
1263 Signature, ...) \
1264 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1265 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1266 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1267 Signature, __VA_ARGS__)
1268#else
1269#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(ClassName, Name, Tags, \
1270 Signature, ...) \
1271 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1272 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1273 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1274 Signature, __VA_ARGS__))
1275#endif
1276#endif
1277
1279#define INTERNAL_CATCH_TESTCASE2(TestName, ...) \
1280 static void TestName(); \
1281 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1282 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1283 namespace { \
1284 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName), \
1285 CATCH_INTERNAL_LINEINFO, \
1286 Catch::StringRef(), \
1287 Catch::NameAndTags{__VA_ARGS__}); \
1288 } /* NOLINT */ \
1289 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1290 static void TestName()
1291#define INTERNAL_CATCH_TESTCASE(...) \
1292 INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), __VA_ARGS__)
1293
1295#define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \
1296 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1297 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1298 namespace { \
1299 Catch::AutoReg \
1300 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&QualifiedMethod), \
1301 CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, \
1302 Catch::NameAndTags{__VA_ARGS__}); \
1303 } /* NOLINT */ \
1304 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1305
1307#define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...) \
1308 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1309 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1310 namespace { \
1311 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1312 void test(); \
1313 }; \
1314 Catch::AutoReg \
1315 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName::test), \
1316 CATCH_INTERNAL_LINEINFO, #ClassName, \
1317 Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \
1318 } \
1319 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1320 void TestName::test()
1321#define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \
1322 INTERNAL_CATCH_TEST_CASE_METHOD2(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), ClassName, \
1323 __VA_ARGS__)
1324
1326#define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \
1327 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1328 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1329 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \
1330 Catch::makeTestInvoker(Function), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), \
1331 Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \
1332 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1333
1335#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...) \
1336 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1337 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1338 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1339 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1340 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1341 namespace { \
1342 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1343 INTERNAL_CATCH_TYPE_GEN \
1344 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1345 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1346 template <typename... Types> struct TestName { \
1347 TestName() { \
1348 int index = 0; \
1349 constexpr char const* tmpl_types[] = { \
1350 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1351 using expander = int[]; \
1352 (void)expander{ \
1353 (reg_test(Types{}, \
1354 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), Tags}), \
1355 index++)...}; /* NOLINT */ \
1356 } \
1357 }; \
1358 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1359 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1360 return 0; \
1361 }(); \
1362 } \
1363 } \
1364 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1365 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1366
1367#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1368#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1369 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1370 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1371 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1372 typename TestType, __VA_ARGS__)
1373#else
1374#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1375 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1376 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1377 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1378 typename TestType, __VA_ARGS__))
1379#endif
1380
1381#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1382#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1383 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1384 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1385 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1386 Signature, __VA_ARGS__)
1387#else
1388#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1389 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1390 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1391 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1392 Signature, __VA_ARGS__))
1393#endif
1394
1395#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, \
1396 TmplTypes, TypesList) \
1397 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1398 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1399 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1400 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1401 template <typename TestType> static void TestFuncName(); \
1402 namespace { \
1403 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1404 INTERNAL_CATCH_TYPE_GEN \
1405 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1406 template <typename... Types> struct TestName { \
1407 void reg_tests() { \
1408 int index = 0; \
1409 using expander = int[]; \
1410 constexpr char const* tmpl_types[] = { \
1411 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1412 INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1413 constexpr char const* types_list[] = { \
1414 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1415 INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1416 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1417 (void)expander{ \
1418 (Catch::AutoReg(Catch::makeTestInvoker(&TestFuncName<Types>), \
1419 CATCH_INTERNAL_LINEINFO, Catch::StringRef(), \
1420 Catch::NameAndTags{ \
1421 Name " - " + std::string(tmpl_types[index / num_types]) + \
1422 "<" + std::string(types_list[index % num_types]) + ">", \
1423 Tags}), \
1424 index++)...}; /* NOLINT */ \
1425 } \
1426 }; \
1427 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1428 using TestInit = \
1429 typename create<TestName, \
1430 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1431 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1432 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1433 TestInit t; \
1434 t.reg_tests(); \
1435 return 0; \
1436 }(); \
1437 } \
1438 } \
1439 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1440 template <typename TestType> static void TestFuncName()
1441
1442#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1443#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1444 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1445 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1446 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1447 typename T, __VA_ARGS__)
1448#else
1449#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1450 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1451 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1452 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1453 typename T, __VA_ARGS__))
1454#endif
1455
1456#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1457#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1458 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1459 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1460 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1461 Signature, __VA_ARGS__)
1462#else
1463#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1464 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1465 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1466 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1467 Signature, __VA_ARGS__))
1468#endif
1469
1470#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList) \
1471 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1472 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1473 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1474 template <typename TestType> static void TestFunc(); \
1475 namespace { \
1476 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1477 INTERNAL_CATCH_TYPE_GEN \
1478 template <typename... Types> struct TestName { \
1479 void reg_tests() { \
1480 int index = 0; \
1481 using expander = int[]; \
1482 (void)expander{ \
1483 (Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Types>), CATCH_INTERNAL_LINEINFO, \
1484 Catch::StringRef(), \
1485 Catch::NameAndTags{ \
1486 Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1487 " - " + std::to_string(index), \
1488 Tags}), \
1489 index++)...}; /* NOLINT */ \
1490 } \
1491 }; \
1492 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1493 using TestInit = typename convert<TestName, TmplList>::type; \
1494 TestInit t; \
1495 t.reg_tests(); \
1496 return 0; \
1497 }(); \
1498 } \
1499 } \
1500 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1501 template <typename TestType> static void TestFunc()
1502
1503#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1504 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( \
1505 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1506 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), Name, Tags, \
1507 TmplList)
1508
1509#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, \
1510 Signature, ...) \
1511 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1512 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1513 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1514 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1515 namespace { \
1516 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1517 INTERNAL_CATCH_TYPE_GEN \
1518 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1519 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, \
1520 INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1521 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1522 template <typename... Types> struct TestNameClass { \
1523 TestNameClass() { \
1524 int index = 0; \
1525 constexpr char const* tmpl_types[] = { \
1526 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1527 using expander = int[]; \
1528 (void)expander{ \
1529 (reg_test(Types{}, #ClassName, \
1530 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), Tags}), \
1531 index++)...}; /* NOLINT */ \
1532 } \
1533 }; \
1534 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1535 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1536 return 0; \
1537 }(); \
1538 } \
1539 } \
1540 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1541 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1542
1543#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1544#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1545 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1546 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1547 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1548 typename T, __VA_ARGS__)
1549#else
1550#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1551 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1552 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1553 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1554 typename T, __VA_ARGS__))
1555#endif
1556
1557#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1558#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1559 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1560 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1561 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1562 Signature, __VA_ARGS__)
1563#else
1564#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1565 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1566 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_), \
1567 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1568 Signature, __VA_ARGS__))
1569#endif
1570
1571#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1572 TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList) \
1573 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1574 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1575 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1576 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1577 template <typename TestType> \
1578 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \
1579 void test(); \
1580 }; \
1581 namespace { \
1582 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) { \
1583 INTERNAL_CATCH_TYPE_GEN \
1584 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1585 template <typename... Types> struct TestNameClass { \
1586 void reg_tests() { \
1587 int index = 0; \
1588 using expander = int[]; \
1589 constexpr char const* tmpl_types[] = { \
1590 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1591 INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1592 constexpr char const* types_list[] = { \
1593 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1594 INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1595 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1596 (void)expander{ \
1597 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1598 CATCH_INTERNAL_LINEINFO, #ClassName, \
1599 Catch::NameAndTags{ \
1600 Name " - " + std::string(tmpl_types[index / num_types]) + \
1601 "<" + std::string(types_list[index % num_types]) + ">", \
1602 Tags}), \
1603 index++)...}; /* NOLINT */ \
1604 } \
1605 }; \
1606 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1607 using TestInit = \
1608 typename create<TestNameClass, \
1609 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1610 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1611 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1612 TestInit t; \
1613 t.reg_tests(); \
1614 return 0; \
1615 }(); \
1616 } \
1617 } \
1618 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1619 template <typename TestType> void TestName<TestType>::test()
1620
1621#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1622#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1623 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1624 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1625 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), ClassName, Name, \
1626 Tags, typename T, __VA_ARGS__)
1627#else
1628#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1629 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1630 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1631 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), ClassName, Name, \
1632 Tags, typename T, __VA_ARGS__))
1633#endif
1634
1635#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1636#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, \
1637 ...) \
1638 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1639 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1640 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), ClassName, Name, \
1641 Tags, Signature, __VA_ARGS__)
1642#else
1643#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, \
1644 ...) \
1645 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1646 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1647 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), ClassName, Name, \
1648 Tags, Signature, __VA_ARGS__))
1649#endif
1650
1651#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, \
1652 Tags, TmplList) \
1653 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1654 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1655 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1656 template <typename TestType> \
1657 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \
1658 void test(); \
1659 }; \
1660 namespace { \
1661 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1662 INTERNAL_CATCH_TYPE_GEN \
1663 template <typename... Types> struct TestNameClass { \
1664 void reg_tests() { \
1665 int index = 0; \
1666 using expander = int[]; \
1667 (void)expander{ \
1668 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1669 CATCH_INTERNAL_LINEINFO, #ClassName, \
1670 Catch::NameAndTags{ \
1671 Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1672 " - " + std::to_string(index), \
1673 Tags}), \
1674 index++)...}; /* NOLINT */ \
1675 } \
1676 }; \
1677 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1678 using TestInit = typename convert<TestNameClass, TmplList>::type; \
1679 TestInit t; \
1680 t.reg_tests(); \
1681 return 0; \
1682 }(); \
1683 } \
1684 } \
1685 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1686 template <typename TestType> void TestName<TestType>::test()
1687
1688#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1689 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \
1690 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1691 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_), ClassName, Name, \
1692 Tags, TmplList)
1693
1694// end catch_test_registry.h
1695// start catch_capture.hpp
1696
1697// start catch_assertionhandler.h
1698
1699// start catch_assertioninfo.h
1700
1701// start catch_result_type.h
1702
1703namespace Catch {
1704
1705// ResultWas::OfType enum
1707 enum OfType {
1708 Unknown = -1,
1709 Ok = 0,
1710 Info = 1,
1711 Warning = 2,
1712
1713 FailureBit = 0x10,
1714
1715 ExpressionFailed = FailureBit | 1,
1716 ExplicitFailure = FailureBit | 2,
1717
1718 Exception = 0x100 | FailureBit,
1719
1720 ThrewException = Exception | 1,
1721 DidntThrowException = Exception | 2,
1722
1723 FatalErrorCondition = 0x200 | FailureBit
1724
1725 };
1726};
1727
1728bool isOk(ResultWas::OfType resultType);
1729bool isJustInfo(int flags);
1730
1731// ResultDisposition::Flags enum
1733 enum Flags {
1734 Normal = 0x01,
1735
1736 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1737 FalseTest = 0x04, // Prefix expression with !
1738 SuppressFail = 0x08 // Failures are reported but do not fail the test
1739 };
1740};
1741
1742ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
1743
1744bool shouldContinueOnFailure(int flags);
1745inline bool isFalseTest(int flags) {
1746 return (flags & ResultDisposition::FalseTest) != 0;
1747}
1748bool shouldSuppressFailure(int flags);
1749
1750} // end namespace Catch
1751
1752// end catch_result_type.h
1753namespace Catch {
1754
1756 StringRef macroName;
1757 SourceLineInfo lineInfo;
1758 StringRef capturedExpression;
1759 ResultDisposition::Flags resultDisposition;
1760
1761 // We want to delete this constructor but a compiler bug in 4.8 means
1762 // the struct is then treated as non-aggregate
1763 // AssertionInfo() = delete;
1764};
1765
1766} // end namespace Catch
1767
1768// end catch_assertioninfo.h
1769// start catch_decomposer.h
1770
1771// start catch_tostring.h
1772
1773#include <cstddef>
1774#include <string>
1775#include <type_traits>
1776#include <vector>
1777// start catch_stream.h
1778
1779#include <cstddef>
1780#include <iosfwd>
1781#include <ostream>
1782
1783namespace Catch {
1784
1785std::ostream& cout();
1786std::ostream& cerr();
1787std::ostream& clog();
1788
1789class StringRef;
1790
1791struct IStream {
1792 virtual ~IStream();
1793 virtual std::ostream& stream() const = 0;
1794};
1795
1796auto makeStream(StringRef const& filename) -> IStream const*;
1797
1798class ReusableStringStream : NonCopyable {
1799 std::size_t m_index;
1800 std::ostream* m_oss;
1801
1802 public:
1803 ReusableStringStream();
1804 ~ReusableStringStream();
1805
1806 auto str() const -> std::string;
1807
1808 template <typename T> auto operator<<(T const& value) -> ReusableStringStream& {
1809 *m_oss << value;
1810 return *this;
1811 }
1812 auto get() -> std::ostream& { return *m_oss; }
1813};
1814} // namespace Catch
1815
1816// end catch_stream.h
1817// start catch_interfaces_enum_values_registry.h
1818
1819#include <vector>
1820
1821namespace Catch {
1822
1823namespace Detail {
1824struct EnumInfo {
1825 StringRef m_name;
1826 std::vector<std::pair<int, StringRef>> m_values;
1827
1828 ~EnumInfo();
1829
1830 StringRef lookup(int value) const;
1831};
1832} // namespace Detail
1833
1836
1837 virtual Detail::EnumInfo const& registerEnum(StringRef enumName, StringRef allEnums,
1838 std::vector<int> const& values) = 0;
1839
1840 template <typename E>
1841 Detail::EnumInfo const& registerEnum(StringRef enumName, StringRef allEnums,
1842 std::initializer_list<E> values) {
1843 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1844 std::vector<int> intValues;
1845 intValues.reserve(values.size());
1846 for (auto enumValue : values)
1847 intValues.push_back(static_cast<int>(enumValue));
1848 return registerEnum(enumName, allEnums, intValues);
1849 }
1850};
1851
1852} // namespace Catch
1853
1854// end catch_interfaces_enum_values_registry.h
1855
1856#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1857#include <string_view>
1858#endif
1859
1860#ifdef __OBJC__
1861// start catch_objc_arc.hpp
1862
1863#import <Foundation/Foundation.h>
1864
1865#ifdef __has_feature
1866#define CATCH_ARC_ENABLED __has_feature(objc_arc)
1867#else
1868#define CATCH_ARC_ENABLED 0
1869#endif
1870
1871void arcSafeRelease(NSObject* obj);
1872id performOptionalSelector(id obj, SEL sel);
1873
1874#if !CATCH_ARC_ENABLED
1875inline void arcSafeRelease(NSObject* obj) {
1876 [obj release];
1877}
1878inline id performOptionalSelector(id obj, SEL sel) {
1879 if ([obj respondsToSelector:sel])
1880 return [obj performSelector:sel];
1881 return nil;
1882}
1883#define CATCH_UNSAFE_UNRETAINED
1884#define CATCH_ARC_STRONG
1885#else
1886inline void arcSafeRelease(NSObject*) {}
1887inline id performOptionalSelector(id obj, SEL sel) {
1888#ifdef __clang__
1889#pragma clang diagnostic push
1890#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1891#endif
1892 if ([obj respondsToSelector:sel])
1893 return [obj performSelector:sel];
1894#ifdef __clang__
1895#pragma clang diagnostic pop
1896#endif
1897 return nil;
1898}
1899#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1900#define CATCH_ARC_STRONG __strong
1901#endif
1902
1903// end catch_objc_arc.hpp
1904#endif
1905
1906#ifdef _MSC_VER
1907#pragma warning(push)
1908#pragma warning(disable : 4180) // We attempt to stream a function (address) by const&,
1909 // which MSVC complains about but is harmless
1910#endif
1911
1912namespace Catch {
1913namespace Detail {
1914
1915extern const std::string unprintableString;
1916
1917std::string rawMemoryToString(const void* object, std::size_t size);
1918
1919template <typename T> std::string rawMemoryToString(const T& object) {
1920 return rawMemoryToString(&object, sizeof(object));
1921}
1922
1923template <typename T> class IsStreamInsertable {
1924 template <typename Stream, typename U>
1925 static auto test(int)
1926 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1927
1928 template <typename, typename> static auto test(...) -> std::false_type;
1929
1930 public:
1931 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1932};
1933
1934template <typename E> std::string convertUnknownEnumToString(E e);
1935
1936template <typename T>
1937typename std::enable_if<!std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1938 std::string>::type
1939convertUnstreamable(T const&) {
1940 return Detail::unprintableString;
1941}
1942template <typename T>
1943typename std::enable_if<!std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1944 std::string>::type
1945convertUnstreamable(T const& ex) {
1946 return ex.what();
1947}
1948
1949template <typename T>
1950typename std::enable_if<std::is_enum<T>::value, std::string>::type
1951convertUnstreamable(T const& value) {
1952 return convertUnknownEnumToString(value);
1953}
1954
1955#if defined(_MANAGED)
1957template <typename T> std::string clrReferenceToString(T ^ ref) {
1958 if (ref == nullptr)
1959 return std::string("null");
1960 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1961 cli::pin_ptr<System::Byte> p = &bytes[0];
1962 return std::string(reinterpret_cast<char const*>(p), bytes->Length);
1963}
1964#endif
1965
1966} // namespace Detail
1967
1968// If we decide for C++14, change these to enable_if_ts
1969template <typename T, typename = void> struct StringMaker {
1970 template <typename Fake = T>
1971 static
1972 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1973 convert(const Fake& value) {
1975 // NB: call using the function-like syntax to avoid ambiguity with
1976 // user-defined templated operator<< under clang.
1977 rss.operator<<(value);
1978 return rss.str();
1979 }
1980
1981 template <typename Fake = T>
1982 static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value,
1983 std::string>::type
1984 convert(const Fake& value) {
1985#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1986 return Detail::convertUnstreamable(value);
1987#else
1988 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1989#endif
1990 }
1991};
1992
1993namespace Detail {
1994
1995// This function dispatches all stringification requests inside of Catch.
1996// Should be preferably called fully qualified, like ::Catch::Detail::stringify
1997template <typename T> std::string stringify(const T& e) {
1998 return ::Catch::StringMaker<
1999 typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
2000}
2001
2002template <typename E> std::string convertUnknownEnumToString(E e) {
2003 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
2004}
2005
2006#if defined(_MANAGED)
2007template <typename T> std::string stringify(T ^ e) {
2008 return ::Catch::StringMaker<T ^>::convert(e);
2009}
2010#endif
2011
2012} // namespace Detail
2013
2014// Some predefined specializations
2015
2016template <> struct StringMaker<std::string> {
2017 static std::string convert(const std::string& str);
2018};
2019
2020#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2021template <> struct StringMaker<std::string_view> {
2022 static std::string convert(std::string_view str);
2023};
2024#endif
2025
2026template <> struct StringMaker<char const*> {
2027 static std::string convert(char const* str);
2028};
2029template <> struct StringMaker<char*> {
2030 static std::string convert(char* str);
2031};
2032
2033#ifdef CATCH_CONFIG_WCHAR
2034template <> struct StringMaker<std::wstring> {
2035 static std::string convert(const std::wstring& wstr);
2036};
2037
2038#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2039template <> struct StringMaker<std::wstring_view> {
2040 static std::string convert(std::wstring_view str);
2041};
2042#endif
2043
2044template <> struct StringMaker<wchar_t const*> {
2045 static std::string convert(wchar_t const* str);
2046};
2047template <> struct StringMaker<wchar_t*> {
2048 static std::string convert(wchar_t* str);
2049};
2050#endif
2051
2052// TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
2053// while keeping string semantics?
2054template <int SZ> struct StringMaker<char[SZ]> {
2055 static std::string convert(char const* str) {
2056 return ::Catch::Detail::stringify(std::string{str});
2057 }
2058};
2059template <int SZ> struct StringMaker<signed char[SZ]> {
2060 static std::string convert(signed char const* str) {
2061 return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const*>(str)});
2062 }
2063};
2064template <int SZ> struct StringMaker<unsigned char[SZ]> {
2065 static std::string convert(unsigned char const* str) {
2066 return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const*>(str)});
2067 }
2068};
2069
2070#if defined(CATCH_CONFIG_CPP17_BYTE)
2071template <> struct StringMaker<std::byte> {
2072 static std::string convert(std::byte value);
2073};
2074#endif // defined(CATCH_CONFIG_CPP17_BYTE)
2075template <> struct StringMaker<int> {
2076 static std::string convert(int value);
2077};
2078template <> struct StringMaker<long> {
2079 static std::string convert(long value);
2080};
2081template <> struct StringMaker<long long> {
2082 static std::string convert(long long value);
2083};
2084template <> struct StringMaker<unsigned int> {
2085 static std::string convert(unsigned int value);
2086};
2087template <> struct StringMaker<unsigned long> {
2088 static std::string convert(unsigned long value);
2089};
2090template <> struct StringMaker<unsigned long long> {
2091 static std::string convert(unsigned long long value);
2092};
2093
2094template <> struct StringMaker<bool> {
2095 static std::string convert(bool b);
2096};
2097
2098template <> struct StringMaker<char> {
2099 static std::string convert(char c);
2100};
2101template <> struct StringMaker<signed char> {
2102 static std::string convert(signed char c);
2103};
2104template <> struct StringMaker<unsigned char> {
2105 static std::string convert(unsigned char c);
2106};
2107
2108template <> struct StringMaker<std::nullptr_t> {
2109 static std::string convert(std::nullptr_t);
2110};
2111
2112template <> struct StringMaker<float> {
2113 static std::string convert(float value);
2114 static int precision;
2115};
2116
2117template <> struct StringMaker<double> {
2118 static std::string convert(double value);
2119 static int precision;
2120};
2121
2122template <typename T> struct StringMaker<T*> {
2123 template <typename U> static std::string convert(U* p) {
2124 if (p) {
2125 return ::Catch::Detail::rawMemoryToString(p);
2126 } else {
2127 return "nullptr";
2128 }
2129 }
2130};
2131
2132template <typename R, typename C> struct StringMaker<R C::*> {
2133 static std::string convert(R C::* p) {
2134 if (p) {
2135 return ::Catch::Detail::rawMemoryToString(p);
2136 } else {
2137 return "nullptr";
2138 }
2139 }
2140};
2141
2142#if defined(_MANAGED)
2143template <typename T> struct StringMaker<T ^> {
2144 static std::string convert(T ^ ref) { return ::Catch::Detail::clrReferenceToString(ref); }
2145};
2146#endif
2147
2148namespace Detail {
2149template <typename InputIterator, typename Sentinel = InputIterator>
2150std::string rangeToString(InputIterator first, Sentinel last) {
2151 ReusableStringStream rss;
2152 rss << "{ ";
2153 if (first != last) {
2154 rss << ::Catch::Detail::stringify(*first);
2155 for (++first; first != last; ++first)
2156 rss << ", " << ::Catch::Detail::stringify(*first);
2157 }
2158 rss << " }";
2159 return rss.str();
2160}
2161} // namespace Detail
2162
2163#ifdef __OBJC__
2164template <> struct StringMaker<NSString*> {
2165 static std::string convert(NSString* nsstring) {
2166 if (!nsstring)
2167 return "nil";
2168 return std::string("@") + [nsstring UTF8String];
2169 }
2170};
2171template <> struct StringMaker<NSObject*> {
2172 static std::string convert(NSObject* nsObject) {
2173 return ::Catch::Detail::stringify([nsObject description]);
2174 }
2175};
2176namespace Detail {
2177inline std::string stringify(NSString* nsstring) {
2178 return StringMaker<NSString*>::convert(nsstring);
2179}
2180
2181} // namespace Detail
2182#endif // __OBJC__
2183
2184} // namespace Catch
2185
2187// Separate std-lib types stringification, so it can be selectively enabled
2188// This means that we do not bring in
2189
2190#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
2191#define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2192#define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2193#define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2194#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2195#define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2196#endif
2197
2198// Separate std::pair specialization
2199#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
2200#include <utility>
2201namespace Catch {
2202template <typename T1, typename T2> struct StringMaker<std::pair<T1, T2>> {
2203 static std::string convert(const std::pair<T1, T2>& pair) {
2204 ReusableStringStream rss;
2205 rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", "
2206 << ::Catch::Detail::stringify(pair.second) << " }";
2207 return rss.str();
2208 }
2209};
2210} // namespace Catch
2211#endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2212
2213#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
2214#include <optional>
2215namespace Catch {
2216template <typename T> struct StringMaker<std::optional<T>> {
2217 static std::string convert(const std::optional<T>& optional) {
2218 ReusableStringStream rss;
2219 if (optional.has_value()) {
2220 rss << ::Catch::Detail::stringify(*optional);
2221 } else {
2222 rss << "{ }";
2223 }
2224 return rss.str();
2225 }
2226};
2227} // namespace Catch
2228#endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2229
2230// Separate std::tuple specialization
2231#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
2232#include <tuple>
2233namespace Catch {
2234namespace Detail {
2235template <typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value)>
2236struct TupleElementPrinter {
2237 static void print(const Tuple& tuple, std::ostream& os) {
2238 os << (N ? ", " : " ") << ::Catch::Detail::stringify(std::get<N>(tuple));
2239 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
2240 }
2241};
2242
2243template <typename Tuple, std::size_t N> struct TupleElementPrinter<Tuple, N, false> {
2244 static void print(const Tuple&, std::ostream&) {}
2245};
2246
2247} // namespace Detail
2248
2249template <typename... Types> struct StringMaker<std::tuple<Types...>> {
2250 static std::string convert(const std::tuple<Types...>& tuple) {
2251 ReusableStringStream rss;
2252 rss << '{';
2253 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
2254 rss << " }";
2255 return rss.str();
2256 }
2257};
2258} // namespace Catch
2259#endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2260
2261#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
2262#include <variant>
2263namespace Catch {
2264template <> struct StringMaker<std::monostate> {
2265 static std::string convert(const std::monostate&) { return "{ }"; }
2266};
2267
2268template <typename... Elements> struct StringMaker<std::variant<Elements...>> {
2269 static std::string convert(const std::variant<Elements...>& variant) {
2270 if (variant.valueless_by_exception()) {
2271 return "{valueless variant}";
2272 } else {
2273 return std::visit([](const auto& value) { return ::Catch::Detail::stringify(value); },
2274 variant);
2275 }
2276 }
2277};
2278} // namespace Catch
2279#endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2280
2281namespace Catch {
2282// Import begin/ end from std here
2283using std::begin;
2284using std::end;
2285
2286namespace detail {
2287template <typename...> struct void_type {
2288 using type = void;
2289};
2290
2291template <typename T, typename = void> struct is_range_impl : std::false_type {};
2292
2293template <typename T>
2296} // namespace detail
2297
2298template <typename T> struct is_range : detail::is_range_impl<T> {};
2299
2300#if defined(_MANAGED) // Managed types are never ranges
2301template <typename T> struct is_range<T ^> {
2302 static const bool value = false;
2303};
2304#endif
2305
2306template <typename Range> std::string rangeToString(Range const& range) {
2307 return ::Catch::Detail::rangeToString(begin(range), end(range));
2308}
2309
2310// Handle vector<bool> specially
2311template <typename Allocator> std::string rangeToString(std::vector<bool, Allocator> const& v) {
2313 rss << "{ ";
2314 bool first = true;
2315 for (bool b : v) {
2316 if (first)
2317 first = false;
2318 else
2319 rss << ", ";
2320 rss << ::Catch::Detail::stringify(b);
2321 }
2322 rss << " }";
2323 return rss.str();
2324}
2325
2326template <typename R>
2328 typename std::enable_if<is_range<R>::value &&
2329 !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2330 static std::string convert(R const& range) { return rangeToString(range); }
2331};
2332
2333template <typename T, int SZ> struct StringMaker<T[SZ]> {
2334 static std::string convert(T const (&arr)[SZ]) { return rangeToString(arr); }
2335};
2336
2337} // namespace Catch
2338
2339// Separate std::chrono::duration specialization
2340#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2341#include <chrono>
2342#include <ctime>
2343#include <ratio>
2344
2345namespace Catch {
2346
2347template <class Ratio> struct ratio_string {
2348 static std::string symbol();
2349};
2350
2351template <class Ratio> std::string ratio_string<Ratio>::symbol() {
2352 Catch::ReusableStringStream rss;
2353 rss << '[' << Ratio::num << '/' << Ratio::den << ']';
2354 return rss.str();
2355}
2356template <> struct ratio_string<std::atto> {
2357 static std::string symbol();
2358};
2359template <> struct ratio_string<std::femto> {
2360 static std::string symbol();
2361};
2362template <> struct ratio_string<std::pico> {
2363 static std::string symbol();
2364};
2365template <> struct ratio_string<std::nano> {
2366 static std::string symbol();
2367};
2368template <> struct ratio_string<std::micro> {
2369 static std::string symbol();
2370};
2371template <> struct ratio_string<std::milli> {
2372 static std::string symbol();
2373};
2374
2376// std::chrono::duration specializations
2377template <typename Value, typename Ratio> struct StringMaker<std::chrono::duration<Value, Ratio>> {
2378 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2379 ReusableStringStream rss;
2380 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2381 return rss.str();
2382 }
2383};
2384template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2385 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2386 ReusableStringStream rss;
2387 rss << duration.count() << " s";
2388 return rss.str();
2389 }
2390};
2391template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2392 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2393 ReusableStringStream rss;
2394 rss << duration.count() << " m";
2395 return rss.str();
2396 }
2397};
2398template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2399 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2400 ReusableStringStream rss;
2401 rss << duration.count() << " h";
2402 return rss.str();
2403 }
2404};
2405
2407// std::chrono::time_point specialization
2408// Generic time_point cannot be specialized, only
2409// std::chrono::time_point<system_clock>
2410template <typename Clock, typename Duration>
2411struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2412 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2413 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2414 }
2415};
2416// std::chrono::time_point<system_clock> specialization
2417template <typename Duration>
2418struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2419 static std::string
2420 convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2421 auto converted = std::chrono::system_clock::to_time_t(time_point);
2422
2423#ifdef _MSC_VER
2424 std::tm timeInfo = {};
2425 gmtime_s(&timeInfo, &converted);
2426#else
2427 std::tm* timeInfo = std::gmtime(&converted);
2428#endif
2429
2430 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2431 char timeStamp[timeStampSize];
2432 const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
2433
2434#ifdef _MSC_VER
2435 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2436#else
2437 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2438#endif
2439 return std::string(timeStamp);
2440 }
2441};
2442} // namespace Catch
2443#endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2444
2445#define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \
2446 namespace Catch { \
2447 template <> struct StringMaker<enumName> { \
2448 static std::string convert(enumName value) { \
2449 static const auto& enumInfo = \
2450 ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( \
2451 #enumName, #__VA_ARGS__, {__VA_ARGS__}); \
2452 return static_cast<std::string>(enumInfo.lookup(static_cast<int>(value))); \
2453 } \
2454 }; \
2455 }
2456
2457#define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM(enumName, __VA_ARGS__)
2458
2459#ifdef _MSC_VER
2460#pragma warning(pop)
2461#endif
2462
2463// end catch_tostring.h
2464#include <iosfwd>
2465
2466#ifdef _MSC_VER
2467#pragma warning(push)
2468#pragma warning(disable : 4389) // '==' : signed/unsigned mismatch
2469#pragma warning(disable : 4018) // more "signed/unsigned mismatch"
2470#pragma warning(disable : 4312) // Converting int to T* using reinterpret_cast
2471 // (issue on x64 platform)
2472#pragma warning(disable : 4180) // qualifier applied to function type has no meaning
2473#pragma warning(disable : 4800) // Forcing result to true or false
2474#endif
2475
2476namespace Catch {
2477
2478struct ITransientExpression {
2479 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2480 auto getResult() const -> bool { return m_result; }
2481 virtual void streamReconstructedExpression(std::ostream& os) const = 0;
2482
2483 ITransientExpression(bool isBinaryExpression, bool result)
2484 : m_isBinaryExpression(isBinaryExpression), m_result(result) {}
2485
2486 // We don't actually need a virtual destructor, but many static analysers
2487 // complain if it's not here :-(
2488 virtual ~ITransientExpression();
2489
2490 bool m_isBinaryExpression;
2491 bool m_result;
2492};
2493
2494void formatReconstructedExpression(std::ostream& os, std::string const& lhs, StringRef op,
2495 std::string const& rhs);
2496
2497template <typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression {
2498 LhsT m_lhs;
2499 StringRef m_op;
2500 RhsT m_rhs;
2501
2502 void streamReconstructedExpression(std::ostream& os) const override {
2503 formatReconstructedExpression(os, Catch::Detail::stringify(m_lhs), m_op,
2504 Catch::Detail::stringify(m_rhs));
2505 }
2506
2507 public:
2508 BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
2509 : ITransientExpression{true, comparisonResult}, m_lhs(lhs), m_op(op), m_rhs(rhs) {}
2510
2511 template <typename T> auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2512 static_assert(always_false<T>::value,
2513 "chained comparisons are not supported inside assertions, "
2514 "wrap the expression inside parentheses, or decompose it");
2515 }
2516
2517 template <typename T> auto operator||(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2518 static_assert(always_false<T>::value,
2519 "chained comparisons are not supported inside assertions, "
2520 "wrap the expression inside parentheses, or decompose it");
2521 }
2522
2523 template <typename T> auto operator==(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2524 static_assert(always_false<T>::value,
2525 "chained comparisons are not supported inside assertions, "
2526 "wrap the expression inside parentheses, or decompose it");
2527 }
2528
2529 template <typename T> auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2530 static_assert(always_false<T>::value,
2531 "chained comparisons are not supported inside assertions, "
2532 "wrap the expression inside parentheses, or decompose it");
2533 }
2534
2535 template <typename T> auto operator>(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2536 static_assert(always_false<T>::value,
2537 "chained comparisons are not supported inside assertions, "
2538 "wrap the expression inside parentheses, or decompose it");
2539 }
2540
2541 template <typename T> auto operator<(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2542 static_assert(always_false<T>::value,
2543 "chained comparisons are not supported inside assertions, "
2544 "wrap the expression inside parentheses, or decompose it");
2545 }
2546
2547 template <typename T> auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2548 static_assert(always_false<T>::value,
2549 "chained comparisons are not supported inside assertions, "
2550 "wrap the expression inside parentheses, or decompose it");
2551 }
2552
2553 template <typename T> auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2554 static_assert(always_false<T>::value,
2555 "chained comparisons are not supported inside assertions, "
2556 "wrap the expression inside parentheses, or decompose it");
2557 }
2558};
2559
2560template <typename LhsT> class UnaryExpr : public ITransientExpression {
2561 LhsT m_lhs;
2562
2563 void streamReconstructedExpression(std::ostream& os) const override {
2564 os << Catch::Detail::stringify(m_lhs);
2565 }
2566
2567 public:
2568 explicit UnaryExpr(LhsT lhs)
2569 : ITransientExpression{false, static_cast<bool>(lhs)}, m_lhs(lhs) {}
2570};
2571
2572// Specialised comparison functions to handle equality comparisons between ints
2573// and pointers (NULL deduces as an int)
2574template <typename LhsT, typename RhsT>
2575auto compareEqual(LhsT const& lhs, RhsT const& rhs) -> bool {
2576 return static_cast<bool>(lhs == rhs);
2577}
2578template <typename T> auto compareEqual(T* const& lhs, int rhs) -> bool {
2579 return lhs == reinterpret_cast<void const*>(rhs);
2580}
2581template <typename T> auto compareEqual(T* const& lhs, long rhs) -> bool {
2582 return lhs == reinterpret_cast<void const*>(rhs);
2583}
2584template <typename T> auto compareEqual(int lhs, T* const& rhs) -> bool {
2585 return reinterpret_cast<void const*>(lhs) == rhs;
2586}
2587template <typename T> auto compareEqual(long lhs, T* const& rhs) -> bool {
2588 return reinterpret_cast<void const*>(lhs) == rhs;
2589}
2590
2591template <typename LhsT, typename RhsT> auto compareNotEqual(LhsT const& lhs, RhsT&& rhs) -> bool {
2592 return static_cast<bool>(lhs != rhs);
2593}
2594template <typename T> auto compareNotEqual(T* const& lhs, int rhs) -> bool {
2595 return lhs != reinterpret_cast<void const*>(rhs);
2596}
2597template <typename T> auto compareNotEqual(T* const& lhs, long rhs) -> bool {
2598 return lhs != reinterpret_cast<void const*>(rhs);
2599}
2600template <typename T> auto compareNotEqual(int lhs, T* const& rhs) -> bool {
2601 return reinterpret_cast<void const*>(lhs) != rhs;
2602}
2603template <typename T> auto compareNotEqual(long lhs, T* const& rhs) -> bool {
2604 return reinterpret_cast<void const*>(lhs) != rhs;
2605}
2606
2607template <typename LhsT> class ExprLhs {
2608 LhsT m_lhs;
2609
2610 public:
2611 explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {}
2612
2613 template <typename RhsT>
2614 auto operator==(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2615 return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs};
2616 }
2617 auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const {
2618 return {m_lhs == rhs, m_lhs, "==", rhs};
2619 }
2620
2621 template <typename RhsT>
2622 auto operator!=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2623 return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs};
2624 }
2625 auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const {
2626 return {m_lhs != rhs, m_lhs, "!=", rhs};
2627 }
2628
2629 template <typename RhsT>
2630 auto operator>(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2631 return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs};
2632 }
2633 template <typename RhsT>
2634 auto operator<(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2635 return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs};
2636 }
2637 template <typename RhsT>
2638 auto operator>=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2639 return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs};
2640 }
2641 template <typename RhsT>
2642 auto operator<=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2643 return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs};
2644 }
2645 template <typename RhsT>
2646 auto operator|(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2647 return {static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs};
2648 }
2649 template <typename RhsT>
2650 auto operator&(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2651 return {static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs};
2652 }
2653 template <typename RhsT>
2654 auto operator^(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2655 return {static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs};
2656 }
2657
2658 template <typename RhsT> auto operator&&(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const {
2659 static_assert(always_false<RhsT>::value,
2660 "operator&& is not supported inside assertions, "
2661 "wrap the expression inside parentheses, or decompose it");
2662 }
2663
2664 template <typename RhsT> auto operator||(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const {
2665 static_assert(always_false<RhsT>::value,
2666 "operator|| is not supported inside assertions, "
2667 "wrap the expression inside parentheses, or decompose it");
2668 }
2669
2670 auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{m_lhs}; }
2671};
2672
2673void handleExpression(ITransientExpression const& expr);
2674
2675template <typename T> void handleExpression(ExprLhs<T> const& expr) {
2676 handleExpression(expr.makeUnaryExpr());
2677}
2678
2680 template <typename T> auto operator<=(T const& lhs) -> ExprLhs<T const&> {
2681 return ExprLhs<T const&>{lhs};
2682 }
2683
2684 auto operator<=(bool value) -> ExprLhs<bool> { return ExprLhs<bool>{value}; }
2685};
2686
2687} // end namespace Catch
2688
2689#ifdef _MSC_VER
2690#pragma warning(pop)
2691#endif
2692
2693// end catch_decomposer.h
2694// start catch_interfaces_capture.h
2695
2696#include <chrono>
2697#include <string>
2698
2699namespace Catch {
2700
2701class AssertionResult;
2702struct AssertionInfo;
2703struct SectionInfo;
2704struct SectionEndInfo;
2705struct MessageInfo;
2706struct MessageBuilder;
2707struct Counts;
2708struct AssertionReaction;
2709struct SourceLineInfo;
2710
2711struct ITransientExpression;
2712struct IGeneratorTracker;
2713
2714#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2715struct BenchmarkInfo;
2716template <typename Duration = std::chrono::duration<double, std::nano>> struct BenchmarkStats;
2717#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2718
2720
2721 virtual ~IResultCapture();
2722
2723 virtual bool sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) = 0;
2724 virtual void sectionEnded(SectionEndInfo const& endInfo) = 0;
2725 virtual void sectionEndedEarly(SectionEndInfo const& endInfo) = 0;
2726
2727 virtual auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
2728 -> IGeneratorTracker& = 0;
2729
2730#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2731 virtual void benchmarkPreparing(std::string const& name) = 0;
2732 virtual void benchmarkStarting(BenchmarkInfo const& info) = 0;
2733 virtual void benchmarkEnded(BenchmarkStats<> const& stats) = 0;
2734 virtual void benchmarkFailed(std::string const& error) = 0;
2735#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2736
2737 virtual void pushScopedMessage(MessageInfo const& message) = 0;
2738 virtual void popScopedMessage(MessageInfo const& message) = 0;
2739
2740 virtual void emplaceUnscopedMessage(MessageBuilder const& builder) = 0;
2741
2742 virtual void handleFatalErrorCondition(StringRef message) = 0;
2743
2744 virtual void handleExpr(AssertionInfo const& info, ITransientExpression const& expr,
2745 AssertionReaction& reaction) = 0;
2746 virtual void handleMessage(AssertionInfo const& info, ResultWas::OfType resultType,
2747 StringRef const& message, AssertionReaction& reaction) = 0;
2748 virtual void handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
2749 AssertionReaction& reaction) = 0;
2750 virtual void handleUnexpectedInflightException(AssertionInfo const& info,
2751 std::string const& message,
2752 AssertionReaction& reaction) = 0;
2753 virtual void handleIncomplete(AssertionInfo const& info) = 0;
2754 virtual void handleNonExpr(AssertionInfo const& info, ResultWas::OfType resultType,
2755 AssertionReaction& reaction) = 0;
2756
2757 virtual bool lastAssertionPassed() = 0;
2758 virtual void assertionPassed() = 0;
2759
2760 // Deprecated, do not use:
2761 virtual std::string getCurrentTestName() const = 0;
2762 virtual const AssertionResult* getLastResult() const = 0;
2763 virtual void exceptionEarlyReported() = 0;
2764};
2765
2766IResultCapture& getResultCapture();
2767} // namespace Catch
2768
2769// end catch_interfaces_capture.h
2770namespace Catch {
2771
2773struct AssertionResultData;
2774struct IResultCapture;
2775class RunContext;
2776
2777class LazyExpression {
2778 friend class AssertionHandler;
2779 friend struct AssertionStats;
2780 friend class RunContext;
2781
2782 ITransientExpression const* m_transientExpression = nullptr;
2783 bool m_isNegated;
2784
2785 public:
2786 LazyExpression(bool isNegated);
2787 LazyExpression(LazyExpression const& other);
2788 LazyExpression& operator=(LazyExpression const&) = delete;
2789
2790 explicit operator bool() const;
2791
2792 friend auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream&;
2793};
2794
2796 bool shouldDebugBreak = false;
2797 bool shouldThrow = false;
2798};
2799
2800class AssertionHandler {
2801 AssertionInfo m_assertionInfo;
2802 AssertionReaction m_reaction;
2803 bool m_completed = false;
2804 IResultCapture& m_resultCapture;
2805
2806 public:
2807 AssertionHandler(StringRef const& macroName, SourceLineInfo const& lineInfo,
2808 StringRef capturedExpression, ResultDisposition::Flags resultDisposition);
2809 ~AssertionHandler() {
2810 if (!m_completed) {
2811 m_resultCapture.handleIncomplete(m_assertionInfo);
2812 }
2813 }
2814
2815 template <typename T> void handleExpr(ExprLhs<T> const& expr) {
2816 handleExpr(expr.makeUnaryExpr());
2817 }
2818 void handleExpr(ITransientExpression const& expr);
2819
2820 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2821
2822 void handleExceptionThrownAsExpected();
2823 void handleUnexpectedExceptionNotThrown();
2824 void handleExceptionNotThrownAsExpected();
2825 void handleThrowingCallSkipped();
2826 void handleUnexpectedInflightException();
2827
2828 void complete();
2829 void setCompleted();
2830
2831 // query
2832 auto allowThrows() const -> bool;
2833};
2834
2835void handleExceptionMatchExpr(AssertionHandler& handler, std::string const& str,
2836 StringRef const& matcherString);
2837
2838} // namespace Catch
2839
2840// end catch_assertionhandler.h
2841// start catch_message.h
2842
2843#include <string>
2844#include <vector>
2845
2846namespace Catch {
2847
2848struct MessageInfo {
2849 MessageInfo(StringRef const& _macroName, SourceLineInfo const& _lineInfo,
2850 ResultWas::OfType _type);
2851
2852 StringRef macroName;
2853 std::string message;
2854 SourceLineInfo lineInfo;
2855 ResultWas::OfType type;
2856 unsigned int sequence;
2857
2858 bool operator==(MessageInfo const& other) const;
2859 bool operator<(MessageInfo const& other) const;
2860
2861 private:
2862 static unsigned int globalCount;
2863};
2864
2866
2867 template <typename T> MessageStream& operator<<(T const& value) {
2868 m_stream << value;
2869 return *this;
2870 }
2871
2872 ReusableStringStream m_stream;
2873};
2874
2875struct MessageBuilder : MessageStream {
2876 MessageBuilder(StringRef const& macroName, SourceLineInfo const& lineInfo,
2877 ResultWas::OfType type);
2878
2879 template <typename T> MessageBuilder& operator<<(T const& value) {
2880 m_stream << value;
2881 return *this;
2882 }
2883
2884 MessageInfo m_info;
2885};
2886
2887class ScopedMessage {
2888 public:
2889 explicit ScopedMessage(MessageBuilder const& builder);
2890 ScopedMessage(ScopedMessage& duplicate) = delete;
2891 ScopedMessage(ScopedMessage&& old);
2892 ~ScopedMessage();
2893
2894 MessageInfo m_info;
2895 bool m_moved;
2896};
2897
2898class Capturer {
2899 std::vector<MessageInfo> m_messages;
2900 IResultCapture& m_resultCapture = getResultCapture();
2901 size_t m_captured = 0;
2902
2903 public:
2904 Capturer(StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType,
2905 StringRef names);
2906 ~Capturer();
2907
2908 void captureValue(size_t index, std::string const& value);
2909
2910 template <typename T> void captureValues(size_t index, T const& value) {
2911 captureValue(index, Catch::Detail::stringify(value));
2912 }
2913
2914 template <typename T, typename... Ts>
2915 void captureValues(size_t index, T const& value, Ts const&... values) {
2916 captureValue(index, Catch::Detail::stringify(value));
2917 captureValues(index + 1, values...);
2918 }
2919};
2920
2921} // end namespace Catch
2922
2923// end catch_message.h
2924#if !defined(CATCH_CONFIG_DISABLE)
2925
2926#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2927#define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2928#else
2929#define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2930#endif
2931
2932#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2933
2935// Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2936// macros.
2937#define INTERNAL_CATCH_TRY
2938#define INTERNAL_CATCH_CATCH(capturer)
2939
2940#else // CATCH_CONFIG_FAST_COMPILE
2941
2942#define INTERNAL_CATCH_TRY try
2943#define INTERNAL_CATCH_CATCH(handler) \
2944 catch (...) { \
2945 handler.handleUnexpectedInflightException(); \
2946 }
2947
2948#endif
2949
2950#define INTERNAL_CATCH_REACT(handler) handler.complete();
2951
2953#define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \
2954 do { \
2955 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2956 Catch::AssertionHandler catchAssertionHandler( \
2957 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
2958 resultDisposition); \
2959 INTERNAL_CATCH_TRY { \
2960 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2961 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2962 catchAssertionHandler.handleExpr(Catch::Decomposer() <= __VA_ARGS__); \
2963 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2964 } \
2965 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
2966 INTERNAL_CATCH_REACT(catchAssertionHandler) \
2967 } while ((void)0, (false) && static_cast<bool>(!!(__VA_ARGS__)))
2968
2970#define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \
2971 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
2972 if (Catch::getResultCapture().lastAssertionPassed())
2973
2975#define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \
2976 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
2977 if (!Catch::getResultCapture().lastAssertionPassed())
2978
2980#define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \
2981 do { \
2982 Catch::AssertionHandler catchAssertionHandler( \
2983 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
2984 resultDisposition); \
2985 try { \
2986 static_cast<void>(__VA_ARGS__); \
2987 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2988 } catch (...) { \
2989 catchAssertionHandler.handleUnexpectedInflightException(); \
2990 } \
2991 INTERNAL_CATCH_REACT(catchAssertionHandler) \
2992 } while (false)
2993
2995#define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \
2996 do { \
2997 Catch::AssertionHandler catchAssertionHandler( \
2998 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
2999 resultDisposition); \
3000 if (catchAssertionHandler.allowThrows()) \
3001 try { \
3002 static_cast<void>(__VA_ARGS__); \
3003 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3004 } catch (...) { \
3005 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3006 } \
3007 else \
3008 catchAssertionHandler.handleThrowingCallSkipped(); \
3009 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3010 } while (false)
3011
3013#define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr) \
3014 do { \
3015 Catch::AssertionHandler catchAssertionHandler( \
3016 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3017 CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), \
3018 resultDisposition); \
3019 if (catchAssertionHandler.allowThrows()) \
3020 try { \
3021 static_cast<void>(expr); \
3022 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3023 } catch (exceptionType const&) { \
3024 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3025 } catch (...) { \
3026 catchAssertionHandler.handleUnexpectedInflightException(); \
3027 } \
3028 else \
3029 catchAssertionHandler.handleThrowingCallSkipped(); \
3030 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3031 } while (false)
3032
3034#define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \
3035 do { \
3036 Catch::AssertionHandler catchAssertionHandler( \
3037 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition); \
3038 catchAssertionHandler.handleMessage( \
3039 messageType, \
3040 (Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop()).m_stream.str()); \
3041 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3042 } while (false)
3043
3045#define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \
3046 auto varName = \
3047 Catch::Capturer(macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__); \
3048 varName.captureValues(0, __VA_ARGS__)
3049
3051#define INTERNAL_CATCH_INFO(macroName, log) \
3052 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage)( \
3053 Catch::MessageBuilder(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3054 Catch::ResultWas::Info) \
3055 << log);
3056
3058#define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \
3059 Catch::getResultCapture().emplaceUnscopedMessage( \
3060 Catch::MessageBuilder(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3061 Catch::ResultWas::Info) \
3062 << log)
3063
3065// Although this is matcher-based, it can be used with just a string
3066#define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...) \
3067 do { \
3068 Catch::AssertionHandler catchAssertionHandler( \
3069 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3070 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
3071 resultDisposition); \
3072 if (catchAssertionHandler.allowThrows()) \
3073 try { \
3074 static_cast<void>(__VA_ARGS__); \
3075 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3076 } catch (...) { \
3077 Catch::handleExceptionMatchExpr(catchAssertionHandler, matcher, \
3078 #matcher##_catch_sr); \
3079 } \
3080 else \
3081 catchAssertionHandler.handleThrowingCallSkipped(); \
3082 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3083 } while (false)
3084
3085#endif // CATCH_CONFIG_DISABLE
3086
3087// end catch_capture.hpp
3088// start catch_section.h
3089
3090// start catch_section_info.h
3091
3092// start catch_totals.h
3093
3094#include <cstddef>
3095
3096namespace Catch {
3097
3098struct Counts {
3099 Counts operator-(Counts const& other) const;
3100 Counts& operator+=(Counts const& other);
3101
3102 std::size_t total() const;
3103 bool allPassed() const;
3104 bool allOk() const;
3105
3106 std::size_t passed = 0;
3107 std::size_t failed = 0;
3108 std::size_t failedButOk = 0;
3109};
3110
3111struct Totals {
3112
3113 Totals operator-(Totals const& other) const;
3114 Totals& operator+=(Totals const& other);
3115
3116 Totals delta(Totals const& prevTotals) const;
3117
3118 int error = 0;
3119 Counts assertions;
3120 Counts testCases;
3121};
3122} // namespace Catch
3123
3124// end catch_totals.h
3125#include <string>
3126
3127namespace Catch {
3128
3129struct SectionInfo {
3130 SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name);
3131
3132 // Deprecated
3133 SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name, std::string const&)
3134 : SectionInfo(_lineInfo, _name) {}
3135
3136 std::string name;
3137 std::string description; // !Deprecated: this will always be empty
3138 SourceLineInfo lineInfo;
3139};
3140
3142 SectionInfo sectionInfo;
3143 Counts prevAssertions;
3144 double durationInSeconds;
3145};
3146
3147} // end namespace Catch
3148
3149// end catch_section_info.h
3150// start catch_timer.h
3151
3152#include <cstdint>
3153
3154namespace Catch {
3155
3156auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
3157auto getEstimatedClockResolution() -> uint64_t;
3158
3159class Timer {
3160 uint64_t m_nanoseconds = 0;
3161
3162 public:
3163 void start();
3164 auto getElapsedNanoseconds() const -> uint64_t;
3165 auto getElapsedMicroseconds() const -> uint64_t;
3166 auto getElapsedMilliseconds() const -> unsigned int;
3167 auto getElapsedSeconds() const -> double;
3168};
3169
3170} // namespace Catch
3171
3172// end catch_timer.h
3173#include <string>
3174
3175namespace Catch {
3176
3177class Section : NonCopyable {
3178 public:
3179 Section(SectionInfo const& info);
3180 ~Section();
3181
3182 // This indicates whether the section should be executed or not
3183 explicit operator bool() const;
3184
3185 private:
3186 SectionInfo m_info;
3187
3188 std::string m_name;
3189 Counts m_assertions;
3190 bool m_sectionIncluded;
3191 Timer m_timer;
3192};
3193
3194} // end namespace Catch
3195
3196#define INTERNAL_CATCH_SECTION(...) \
3197 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3198 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3199 if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3200 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__)) \
3201 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3202
3203#define INTERNAL_CATCH_DYNAMIC_SECTION(...) \
3204 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3205 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3206 if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3207 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, \
3208 (Catch::ReusableStringStream() << __VA_ARGS__).str())) \
3209 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3210
3211// end catch_section.h
3212// start catch_interfaces_exception.h
3213
3214// start catch_interfaces_registry_hub.h
3215
3216#include <memory>
3217#include <string>
3218
3219namespace Catch {
3220
3221class TestCase;
3222struct ITestCaseRegistry;
3223struct IExceptionTranslatorRegistry;
3224struct IExceptionTranslator;
3225struct IReporterRegistry;
3226struct IReporterFactory;
3227struct ITagAliasRegistry;
3228struct IMutableEnumValuesRegistry;
3229
3230class StartupExceptionRegistry;
3231
3232using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
3233
3235 virtual ~IRegistryHub();
3236
3237 virtual IReporterRegistry const& getReporterRegistry() const = 0;
3238 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
3239 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
3240 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
3241
3242 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
3243};
3244
3246 virtual ~IMutableRegistryHub();
3247 virtual void registerReporter(std::string const& name, IReporterFactoryPtr const& factory) = 0;
3248 virtual void registerListener(IReporterFactoryPtr const& factory) = 0;
3249 virtual void registerTest(TestCase const& testInfo) = 0;
3250 virtual void registerTranslator(const IExceptionTranslator* translator) = 0;
3251 virtual void registerTagAlias(std::string const& alias, std::string const& tag,
3252 SourceLineInfo const& lineInfo) = 0;
3253 virtual void registerStartupException() noexcept = 0;
3254 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
3255};
3256
3257IRegistryHub const& getRegistryHub();
3258IMutableRegistryHub& getMutableRegistryHub();
3259void cleanUp();
3260std::string translateActiveException();
3261
3262} // namespace Catch
3263
3264// end catch_interfaces_registry_hub.h
3265#if defined(CATCH_CONFIG_DISABLE)
3266#define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(translatorName, signature) \
3267 static std::string translatorName(signature)
3268#endif
3269
3270#include <exception>
3271#include <string>
3272#include <vector>
3273
3274namespace Catch {
3275using exceptionTranslateFunction = std::string (*)();
3276
3277struct IExceptionTranslator;
3278using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3279
3281 virtual ~IExceptionTranslator();
3282 virtual std::string translate(ExceptionTranslators::const_iterator it,
3283 ExceptionTranslators::const_iterator itEnd) const = 0;
3284};
3285
3288
3289 virtual std::string translateActiveException() const = 0;
3290};
3291
3292class ExceptionTranslatorRegistrar {
3293 template <typename T> class ExceptionTranslator : public IExceptionTranslator {
3294 public:
3295 ExceptionTranslator(std::string (*translateFunction)(T&))
3296 : m_translateFunction(translateFunction) {}
3297
3298 std::string translate(ExceptionTranslators::const_iterator it,
3299 ExceptionTranslators::const_iterator itEnd) const override {
3300#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3301 return "";
3302#else
3303 try {
3304 if (it == itEnd)
3305 std::rethrow_exception(std::current_exception());
3306 else
3307 return (*it)->translate(it + 1, itEnd);
3308 } catch (T& ex) {
3309 return m_translateFunction(ex);
3310 }
3311#endif
3312 }
3313
3314 protected:
3315 std::string (*m_translateFunction)(T&);
3316 };
3317
3318 public:
3319 template <typename T> ExceptionTranslatorRegistrar(std::string (*translateFunction)(T&)) {
3320 getMutableRegistryHub().registerTranslator(new ExceptionTranslator<T>(translateFunction));
3321 }
3322};
3323} // namespace Catch
3324
3326#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \
3327 static std::string translatorName(signature); \
3328 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3329 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3330 namespace { \
3331 Catch::ExceptionTranslatorRegistrar \
3332 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionRegistrar)(&translatorName); \
3333 } \
3334 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3335 static std::string translatorName(signature)
3336
3337#define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) \
3338 INTERNAL_CATCH_TRANSLATE_EXCEPTION2( \
3339 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
3340
3341// end catch_interfaces_exception.h
3342// start catch_approx.h
3343
3344#include <type_traits>
3345
3346namespace Catch {
3347namespace Detail {
3348
3349class Approx {
3350 private:
3351 bool equalityComparisonImpl(double other) const;
3352 // Validates the new margin (margin >= 0)
3353 // out-of-line to avoid including stdexcept in the header
3354 void setMargin(double margin);
3355 // Validates the new epsilon (0 < epsilon < 1)
3356 // out-of-line to avoid including stdexcept in the header
3357 void setEpsilon(double epsilon);
3358
3359 public:
3360 explicit Approx(double value);
3361
3362 static Approx custom();
3363
3364 Approx operator-() const;
3365
3366 template <typename T,
3367 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3368 Approx operator()(T const& value) const {
3369 Approx approx(static_cast<double>(value));
3370 approx.m_epsilon = m_epsilon;
3371 approx.m_margin = m_margin;
3372 approx.m_scale = m_scale;
3373 return approx;
3374 }
3375
3376 template <typename T,
3377 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3378 explicit Approx(T const& value) : Approx(static_cast<double>(value)) {}
3379
3380 template <typename T,
3381 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3382 friend bool operator==(const T& lhs, Approx const& rhs) {
3383 auto lhs_v = static_cast<double>(lhs);
3384 return rhs.equalityComparisonImpl(lhs_v);
3385 }
3386
3387 template <typename T,
3388 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3389 friend bool operator==(Approx const& lhs, const T& rhs) {
3390 return operator==(rhs, lhs);
3391 }
3392
3393 template <typename T,
3394 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3395 friend bool operator!=(T const& lhs, Approx const& rhs) {
3396 return !operator==(lhs, rhs);
3397 }
3398
3399 template <typename T,
3400 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3401 friend bool operator!=(Approx const& lhs, T const& rhs) {
3402 return !operator==(rhs, lhs);
3403 }
3404
3405 template <typename T,
3406 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3407 friend bool operator<=(T const& lhs, Approx const& rhs) {
3408 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3409 }
3410
3411 template <typename T,
3412 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3413 friend bool operator<=(Approx const& lhs, T const& rhs) {
3414 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3415 }
3416
3417 template <typename T,
3418 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3419 friend bool operator>=(T const& lhs, Approx const& rhs) {
3420 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3421 }
3422
3423 template <typename T,
3424 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3425 friend bool operator>=(Approx const& lhs, T const& rhs) {
3426 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3427 }
3428
3429 template <typename T,
3430 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3431 Approx& epsilon(T const& newEpsilon) {
3432 double epsilonAsDouble = static_cast<double>(newEpsilon);
3433 setEpsilon(epsilonAsDouble);
3434 return *this;
3435 }
3436
3437 template <typename T,
3438 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3439 Approx& margin(T const& newMargin) {
3440 double marginAsDouble = static_cast<double>(newMargin);
3441 setMargin(marginAsDouble);
3442 return *this;
3443 }
3444
3445 template <typename T,
3446 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3447 Approx& scale(T const& newScale) {
3448 m_scale = static_cast<double>(newScale);
3449 return *this;
3450 }
3451
3452 std::string toString() const;
3453
3454 private:
3455 double m_epsilon;
3456 double m_margin;
3457 double m_scale;
3458 double m_value;
3459};
3460} // end namespace Detail
3461
3462namespace literals {
3463Detail::Approx operator"" _a(long double val);
3464Detail::Approx operator"" _a(unsigned long long val);
3465} // end namespace literals
3466
3467template <> struct StringMaker<Catch::Detail::Approx> {
3468 static std::string convert(Catch::Detail::Approx const& value);
3469};
3470
3471} // end namespace Catch
3472
3473// end catch_approx.h
3474// start catch_string_manip.h
3475
3476#include <iosfwd>
3477#include <string>
3478#include <vector>
3479
3480namespace Catch {
3481
3482bool startsWith(std::string const& s, std::string const& prefix);
3483bool startsWith(std::string const& s, char prefix);
3484bool endsWith(std::string const& s, std::string const& suffix);
3485bool endsWith(std::string const& s, char suffix);
3486bool contains(std::string const& s, std::string const& infix);
3487void toLowerInPlace(std::string& s);
3488std::string toLower(std::string const& s);
3490std::string trim(std::string const& str);
3493StringRef trim(StringRef ref);
3494
3495// !!! Be aware, returns refs into original string - make sure original string
3496// outlives them
3497std::vector<StringRef> splitStringRef(StringRef str, char delimiter);
3498bool replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis);
3499
3500struct pluralise {
3501 pluralise(std::size_t count, std::string const& label);
3502
3503 friend std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser);
3504
3505 std::size_t m_count;
3506 std::string m_label;
3507};
3508} // namespace Catch
3509
3510// end catch_string_manip.h
3511#ifndef CATCH_CONFIG_DISABLE_MATCHERS
3512// start catch_capture_matchers.h
3513
3514// start catch_matchers.h
3515
3516#include <string>
3517#include <vector>
3518
3519namespace Catch {
3520namespace Matchers {
3521namespace Impl {
3522
3523template <typename ArgT> struct MatchAllOf;
3524template <typename ArgT> struct MatchAnyOf;
3525template <typename ArgT> struct MatchNotOf;
3526
3527class MatcherUntypedBase {
3528 public:
3529 MatcherUntypedBase() = default;
3530 MatcherUntypedBase(MatcherUntypedBase const&) = default;
3531 MatcherUntypedBase& operator=(MatcherUntypedBase const&) = delete;
3532 std::string toString() const;
3533
3534 protected:
3535 virtual ~MatcherUntypedBase();
3536 virtual std::string describe() const = 0;
3537 mutable std::string m_cachedToString;
3538};
3539
3540#ifdef __clang__
3541#pragma clang diagnostic push
3542#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3543#endif
3544
3545template <typename ObjectT> struct MatcherMethod {
3546 virtual bool match(ObjectT const& arg) const = 0;
3547};
3548
3549#if defined(__OBJC__)
3550// Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3551// use of const for Object pointers is very uncommon and under ARC it causes
3552// some kind of signature mismatch that breaks compilation
3553template <> struct MatcherMethod<NSString*> {
3554 virtual bool match(NSString* arg) const = 0;
3555};
3556#endif
3557
3558#ifdef __clang__
3559#pragma clang diagnostic pop
3560#endif
3561
3562template <typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3563
3564 MatchAllOf<T> operator&&(MatcherBase const& other) const;
3565 MatchAnyOf<T> operator||(MatcherBase const& other) const;
3566 MatchNotOf<T> operator!() const;
3567};
3568
3569template <typename ArgT> struct MatchAllOf : MatcherBase<ArgT> {
3570 bool match(ArgT const& arg) const override {
3571 for (auto matcher : m_matchers) {
3572 if (!matcher->match(arg))
3573 return false;
3574 }
3575 return true;
3576 }
3577 std::string describe() const override {
3578 std::string description;
3579 description.reserve(4 + m_matchers.size() * 32);
3580 description += "( ";
3581 bool first = true;
3582 for (auto matcher : m_matchers) {
3583 if (first)
3584 first = false;
3585 else
3586 description += " and ";
3587 description += matcher->toString();
3588 }
3589 description += " )";
3590 return description;
3591 }
3592
3593 MatchAllOf<ArgT> operator&&(MatcherBase<ArgT> const& other) {
3594 auto copy(*this);
3595 copy.m_matchers.push_back(&other);
3596 return copy;
3597 }
3598
3599 std::vector<MatcherBase<ArgT> const*> m_matchers;
3600};
3601template <typename ArgT> struct MatchAnyOf : MatcherBase<ArgT> {
3602
3603 bool match(ArgT const& arg) const override {
3604 for (auto matcher : m_matchers) {
3605 if (matcher->match(arg))
3606 return true;
3607 }
3608 return false;
3609 }
3610 std::string describe() const override {
3611 std::string description;
3612 description.reserve(4 + m_matchers.size() * 32);
3613 description += "( ";
3614 bool first = true;
3615 for (auto matcher : m_matchers) {
3616 if (first)
3617 first = false;
3618 else
3619 description += " or ";
3620 description += matcher->toString();
3621 }
3622 description += " )";
3623 return description;
3624 }
3625
3626 MatchAnyOf<ArgT> operator||(MatcherBase<ArgT> const& other) {
3627 auto copy(*this);
3628 copy.m_matchers.push_back(&other);
3629 return copy;
3630 }
3631
3632 std::vector<MatcherBase<ArgT> const*> m_matchers;
3633};
3634
3635template <typename ArgT> struct MatchNotOf : MatcherBase<ArgT> {
3636
3637 MatchNotOf(MatcherBase<ArgT> const& underlyingMatcher)
3638 : m_underlyingMatcher(underlyingMatcher) {}
3639
3640 bool match(ArgT const& arg) const override { return !m_underlyingMatcher.match(arg); }
3641
3642 std::string describe() const override { return "not " + m_underlyingMatcher.toString(); }
3643 MatcherBase<ArgT> const& m_underlyingMatcher;
3644};
3645
3646template <typename T> MatchAllOf<T> MatcherBase<T>::operator&&(MatcherBase const& other) const {
3647 return MatchAllOf<T>() && *this && other;
3648}
3649template <typename T> MatchAnyOf<T> MatcherBase<T>::operator||(MatcherBase const& other) const {
3650 return MatchAnyOf<T>() || *this || other;
3651}
3652template <typename T> MatchNotOf<T> MatcherBase<T>::operator!() const {
3653 return MatchNotOf<T>(*this);
3654}
3655
3656} // namespace Impl
3657
3658} // namespace Matchers
3659
3660using namespace Matchers;
3662
3663} // namespace Catch
3664
3665// end catch_matchers.h
3666// start catch_matchers_exception.hpp
3667
3668namespace Catch {
3669namespace Matchers {
3670namespace Exception {
3671
3672class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3673 std::string m_message;
3674
3675 public:
3676 ExceptionMessageMatcher(std::string const& message) : m_message(message) {}
3677
3678 bool match(std::exception const& ex) const override;
3679
3680 std::string describe() const override;
3681};
3682
3683} // namespace Exception
3684
3685Exception::ExceptionMessageMatcher Message(std::string const& message);
3686
3687} // namespace Matchers
3688} // namespace Catch
3689
3690// end catch_matchers_exception.hpp
3691// start catch_matchers_floating.h
3692
3693namespace Catch {
3694namespace Matchers {
3695
3696namespace Floating {
3697
3698enum class FloatingPointKind : uint8_t;
3699
3700struct WithinAbsMatcher : MatcherBase<double> {
3701 WithinAbsMatcher(double target, double margin);
3702 bool match(double const& matchee) const override;
3703 std::string describe() const override;
3704
3705 private:
3706 double m_target;
3707 double m_margin;
3708};
3709
3710struct WithinUlpsMatcher : MatcherBase<double> {
3711 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3712 bool match(double const& matchee) const override;
3713 std::string describe() const override;
3714
3715 private:
3716 double m_target;
3717 uint64_t m_ulps;
3718 FloatingPointKind m_type;
3719};
3720
3721// Given IEEE-754 format for floats and doubles, we can assume
3722// that float -> double promotion is lossless. Given this, we can
3723// assume that if we do the standard relative comparison of
3724// |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3725// the same result if we do this for floats, as if we do this for
3726// doubles that were promoted from floats.
3727struct WithinRelMatcher : MatcherBase<double> {
3728 WithinRelMatcher(double target, double epsilon);
3729 bool match(double const& matchee) const override;
3730 std::string describe() const override;
3731
3732 private:
3733 double m_target;
3734 double m_epsilon;
3735};
3736
3737} // namespace Floating
3738
3739// The following functions create the actual matcher objects.
3740// This allows the types to be inferred
3741Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3742Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3743Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3744Floating::WithinRelMatcher WithinRel(double target, double eps);
3745// defaults epsilon to 100*numeric_limits<double>::epsilon()
3746Floating::WithinRelMatcher WithinRel(double target);
3747Floating::WithinRelMatcher WithinRel(float target, float eps);
3748// defaults epsilon to 100*numeric_limits<float>::epsilon()
3749Floating::WithinRelMatcher WithinRel(float target);
3750
3751} // namespace Matchers
3752} // namespace Catch
3753
3754// end catch_matchers_floating.h
3755// start catch_matchers_generic.hpp
3756
3757#include <functional>
3758#include <string>
3759
3760namespace Catch {
3761namespace Matchers {
3762namespace Generic {
3763
3764namespace Detail {
3765std::string finalizeDescription(const std::string& desc);
3766}
3767
3768template <typename T> class PredicateMatcher : public MatcherBase<T> {
3769 std::function<bool(T const&)> m_predicate;
3770 std::string m_description;
3771
3772 public:
3773 PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3774 : m_predicate(std::move(elem)), m_description(Detail::finalizeDescription(descr)) {}
3775
3776 bool match(T const& item) const override { return m_predicate(item); }
3777
3778 std::string describe() const override { return m_description; }
3779};
3780
3781} // namespace Generic
3782
3783// The following functions create the actual matcher objects.
3784// The user has to explicitly specify type to the function, because
3785// inferring std::function<bool(T const&)> is hard (but possible) and
3786// requires a lot of TMP.
3787template <typename T>
3788Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate,
3789 std::string const& description = "") {
3790 return Generic::PredicateMatcher<T>(predicate, description);
3791}
3792
3793} // namespace Matchers
3794} // namespace Catch
3795
3796// end catch_matchers_generic.hpp
3797// start catch_matchers_string.h
3798
3799#include <string>
3800
3801namespace Catch {
3802namespace Matchers {
3803
3804namespace StdString {
3805
3806struct CasedString {
3807 CasedString(std::string const& str, CaseSensitive::Choice caseSensitivity);
3808 std::string adjustString(std::string const& str) const;
3809 std::string caseSensitivitySuffix() const;
3810
3811 CaseSensitive::Choice m_caseSensitivity;
3812 std::string m_str;
3813};
3814
3815struct StringMatcherBase : MatcherBase<std::string> {
3816 StringMatcherBase(std::string const& operation, CasedString const& comparator);
3817 std::string describe() const override;
3818
3819 CasedString m_comparator;
3820 std::string m_operation;
3821};
3822
3823struct EqualsMatcher : StringMatcherBase {
3824 EqualsMatcher(CasedString const& comparator);
3825 bool match(std::string const& source) const override;
3826};
3827struct ContainsMatcher : StringMatcherBase {
3828 ContainsMatcher(CasedString const& comparator);
3829 bool match(std::string const& source) const override;
3830};
3831struct StartsWithMatcher : StringMatcherBase {
3832 StartsWithMatcher(CasedString const& comparator);
3833 bool match(std::string const& source) const override;
3834};
3835struct EndsWithMatcher : StringMatcherBase {
3836 EndsWithMatcher(CasedString const& comparator);
3837 bool match(std::string const& source) const override;
3838};
3839
3840struct RegexMatcher : MatcherBase<std::string> {
3841 RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
3842 bool match(std::string const& matchee) const override;
3843 std::string describe() const override;
3844
3845 private:
3846 std::string m_regex;
3847 CaseSensitive::Choice m_caseSensitivity;
3848};
3849
3850} // namespace StdString
3851
3852// The following functions create the actual matcher objects.
3853// This allows the types to be inferred
3854
3855StdString::EqualsMatcher Equals(std::string const& str,
3856 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3857StdString::ContainsMatcher Contains(std::string const& str,
3858 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3859StdString::EndsWithMatcher EndsWith(std::string const& str,
3860 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3861StdString::StartsWithMatcher StartsWith(std::string const& str,
3862 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3863StdString::RegexMatcher Matches(std::string const& regex,
3864 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3865
3866} // namespace Matchers
3867} // namespace Catch
3868
3869// end catch_matchers_string.h
3870// start catch_matchers_vector.h
3871
3872#include <algorithm>
3873
3874namespace Catch {
3875namespace Matchers {
3876
3877namespace Vector {
3878template <typename T, typename Alloc>
3879struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
3880
3881 ContainsElementMatcher(T const& comparator) : m_comparator(comparator) {}
3882
3883 bool match(std::vector<T, Alloc> const& v) const override {
3884 for (auto const& el : v) {
3885 if (el == m_comparator) {
3886 return true;
3887 }
3888 }
3889 return false;
3890 }
3891
3892 std::string describe() const override {
3893 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
3894 }
3895
3896 T const& m_comparator;
3897};
3898
3899template <typename T, typename AllocComp, typename AllocMatch>
3900struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3901
3902 ContainsMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator(comparator) {}
3903
3904 bool match(std::vector<T, AllocMatch> const& v) const override {
3905 // !TBD: see note in EqualsMatcher
3906 if (m_comparator.size() > v.size())
3907 return false;
3908 for (auto const& comparator : m_comparator) {
3909 auto present = false;
3910 for (const auto& el : v) {
3911 if (el == comparator) {
3912 present = true;
3913 break;
3914 }
3915 }
3916 if (!present) {
3917 return false;
3918 }
3919 }
3920 return true;
3921 }
3922 std::string describe() const override {
3923 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
3924 }
3925
3926 std::vector<T, AllocComp> const& m_comparator;
3927};
3928
3929template <typename T, typename AllocComp, typename AllocMatch>
3930struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3931
3932 EqualsMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator(comparator) {}
3933
3934 bool match(std::vector<T, AllocMatch> const& v) const override {
3935 // !TBD: This currently works if all elements can be compared using !=
3936 // - a more general approach would be via a compare template that defaults
3937 // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
3938 // - then just call that directly
3939 if (m_comparator.size() != v.size())
3940 return false;
3941 for (std::size_t i = 0; i < v.size(); ++i)
3942 if (m_comparator[i] != v[i])
3943 return false;
3944 return true;
3945 }
3946 std::string describe() const override {
3947 return "Equals: " + ::Catch::Detail::stringify(m_comparator);
3948 }
3949 std::vector<T, AllocComp> const& m_comparator;
3950};
3951
3952template <typename T, typename AllocComp, typename AllocMatch>
3953struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3954
3955 ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator(comparator) {}
3956
3957 bool match(std::vector<T, AllocMatch> const& v) const override {
3958 if (m_comparator.size() != v.size())
3959 return false;
3960 for (std::size_t i = 0; i < v.size(); ++i)
3961 if (m_comparator[i] != approx(v[i]))
3962 return false;
3963 return true;
3964 }
3965 std::string describe() const override {
3966 return "is approx: " + ::Catch::Detail::stringify(m_comparator);
3967 }
3968 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3969 ApproxMatcher& epsilon(T const& newEpsilon) {
3970 approx.epsilon(newEpsilon);
3971 return *this;
3972 }
3973 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3974 ApproxMatcher& margin(T const& newMargin) {
3975 approx.margin(newMargin);
3976 return *this;
3977 }
3978 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3979 ApproxMatcher& scale(T const& newScale) {
3980 approx.scale(newScale);
3981 return *this;
3982 }
3983
3984 std::vector<T, AllocComp> const& m_comparator;
3985 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3986};
3987
3988template <typename T, typename AllocComp, typename AllocMatch>
3989struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3990 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
3991 bool match(std::vector<T, AllocMatch> const& vec) const override {
3992 if (m_target.size() != vec.size()) {
3993 return false;
3994 }
3995 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3996 }
3997
3998 std::string describe() const override {
3999 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
4000 }
4001
4002 private:
4003 std::vector<T, AllocComp> const& m_target;
4004};
4005
4006} // namespace Vector
4007
4008// The following functions create the actual matcher objects.
4009// This allows the types to be inferred
4010
4011template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4013Contains(std::vector<T, AllocComp> const& comparator) {
4015}
4016
4017template <typename T, typename Alloc = std::allocator<T>>
4018Vector::ContainsElementMatcher<T, Alloc> VectorContains(T const& comparator) {
4020}
4021
4022template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4023Vector::EqualsMatcher<T, AllocComp, AllocMatch>
4024Equals(std::vector<T, AllocComp> const& comparator) {
4025 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>(comparator);
4026}
4027
4028template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4030Approx(std::vector<T, AllocComp> const& comparator) {
4032}
4033
4034template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4036UnorderedEquals(std::vector<T, AllocComp> const& target) {
4038}
4039
4040} // namespace Matchers
4041} // namespace Catch
4042
4043// end catch_matchers_vector.h
4044namespace Catch {
4045
4046template <typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression {
4047 ArgT const& m_arg;
4048 MatcherT m_matcher;
4049 StringRef m_matcherString;
4050
4051 public:
4052 MatchExpr(ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString)
4053 : ITransientExpression{true, matcher.match(arg)}, m_arg(arg), m_matcher(matcher),
4054 m_matcherString(matcherString) {}
4055
4056 void streamReconstructedExpression(std::ostream& os) const override {
4057 auto matcherAsString = m_matcher.toString();
4058 os << Catch::Detail::stringify(m_arg) << ' ';
4059 if (matcherAsString == Detail::unprintableString)
4060 os << m_matcherString;
4061 else
4062 os << matcherAsString;
4063 }
4064};
4065
4066using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
4067
4068void handleExceptionMatchExpr(AssertionHandler& handler, StringMatcher const& matcher,
4069 StringRef const& matcherString);
4070
4071template <typename ArgT, typename MatcherT>
4072auto makeMatchExpr(ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString)
4074 return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString);
4075}
4076
4077} // namespace Catch
4078
4080#define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \
4081 do { \
4082 Catch::AssertionHandler catchAssertionHandler( \
4083 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
4084 CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
4085 resultDisposition); \
4086 INTERNAL_CATCH_TRY { \
4087 catchAssertionHandler.handleExpr( \
4088 Catch::makeMatchExpr(arg, matcher, #matcher##_catch_sr)); \
4089 } \
4090 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
4091 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4092 } while (false)
4093
4095#define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...) \
4096 do { \
4097 Catch::AssertionHandler catchAssertionHandler( \
4098 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
4099 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY( \
4100 exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
4101 resultDisposition); \
4102 if (catchAssertionHandler.allowThrows()) \
4103 try { \
4104 static_cast<void>(__VA_ARGS__); \
4105 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
4106 } catch (exceptionType const& ex) { \
4107 catchAssertionHandler.handleExpr( \
4108 Catch::makeMatchExpr(ex, matcher, #matcher##_catch_sr)); \
4109 } catch (...) { \
4110 catchAssertionHandler.handleUnexpectedInflightException(); \
4111 } \
4112 else \
4113 catchAssertionHandler.handleThrowingCallSkipped(); \
4114 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4115 } while (false)
4116
4117// end catch_capture_matchers.h
4118#endif
4119// start catch_generators.hpp
4120
4121// start catch_interfaces_generatortracker.h
4122
4123#include <memory>
4124
4125namespace Catch {
4126
4127namespace Generators {
4128class GeneratorUntypedBase {
4129 public:
4130 GeneratorUntypedBase() = default;
4131 virtual ~GeneratorUntypedBase();
4132 // Attempts to move the generator to the next element
4133 //
4134 // Returns true iff the move succeeded (and a valid element
4135 // can be retrieved).
4136 virtual bool next() = 0;
4137};
4138using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
4139
4140} // namespace Generators
4141
4143 virtual ~IGeneratorTracker();
4144 virtual auto hasGenerator() const -> bool = 0;
4145 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
4146 virtual void setGenerator(Generators::GeneratorBasePtr&& generator) = 0;
4147};
4148
4149} // namespace Catch
4150
4151// end catch_interfaces_generatortracker.h
4152// start catch_enforce.h
4153
4154#include <exception>
4155
4156namespace Catch {
4157#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
4158template <typename Ex>
4159[[noreturn]]
4160void throw_exception(Ex const& e) {
4161 throw e;
4162}
4163#else // ^^ Exceptions are enabled // Exceptions are disabled vv
4164[[noreturn]]
4165void throw_exception(std::exception const& e);
4166#endif
4167
4168[[noreturn]]
4169void throw_logic_error(std::string const& msg);
4170[[noreturn]]
4171void throw_domain_error(std::string const& msg);
4172[[noreturn]]
4173void throw_runtime_error(std::string const& msg);
4174
4175} // namespace Catch
4176
4177#define CATCH_MAKE_MSG(...) (Catch::ReusableStringStream() << __VA_ARGS__).str()
4178
4179#define CATCH_INTERNAL_ERROR(...) \
4180 Catch::throw_logic_error( \
4181 CATCH_MAKE_MSG(CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
4182
4183#define CATCH_ERROR(...) Catch::throw_domain_error(CATCH_MAKE_MSG(__VA_ARGS__))
4184
4185#define CATCH_RUNTIME_ERROR(...) Catch::throw_runtime_error(CATCH_MAKE_MSG(__VA_ARGS__))
4186
4187#define CATCH_ENFORCE(condition, ...) \
4188 do { \
4189 if (!(condition)) \
4190 CATCH_ERROR(__VA_ARGS__); \
4191 } while (false)
4192
4193// end catch_enforce.h
4194#include <cassert>
4195#include <memory>
4196#include <vector>
4197
4198#include <exception>
4199#include <utility>
4200
4201namespace Catch {
4202
4203class GeneratorException : public std::exception {
4204 const char* const m_msg = "";
4205
4206 public:
4207 GeneratorException(const char* msg) : m_msg(msg) {}
4208
4209 const char* what() const noexcept override final;
4210};
4211
4212namespace Generators {
4213
4214// !TBD move this into its own location?
4215namespace pf {
4216template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
4217 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
4218}
4219} // namespace pf
4220
4221template <typename T> struct IGenerator : GeneratorUntypedBase {
4222 virtual ~IGenerator() = default;
4223
4224 // Returns the current element of the generator
4225 //
4226 // \Precondition The generator is either freshly constructed,
4227 // or the last call to `next()` returned true
4228 virtual T const& get() const = 0;
4229 using type = T;
4230};
4231
4232template <typename T> class SingleValueGenerator final : public IGenerator<T> {
4233 T m_value;
4234
4235 public:
4236 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
4237
4238 T const& get() const override { return m_value; }
4239 bool next() override { return false; }
4240};
4241
4242template <typename T> class FixedValuesGenerator final : public IGenerator<T> {
4243 static_assert(!std::is_same<T, bool>::value,
4244 "FixedValuesGenerator does not support bools because of std::vector<bool>"
4245 "specialization, use SingleValue Generator instead.");
4246 std::vector<T> m_values;
4247 size_t m_idx = 0;
4248
4249 public:
4250 FixedValuesGenerator(std::initializer_list<T> values) : m_values(values) {}
4251
4252 T const& get() const override { return m_values[m_idx]; }
4253 bool next() override {
4254 ++m_idx;
4255 return m_idx < m_values.size();
4256 }
4257};
4258
4259template <typename T> class GeneratorWrapper final {
4260 std::unique_ptr<IGenerator<T>> m_generator;
4261
4262 public:
4263 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator)
4264 : m_generator(std::move(generator)) {}
4265 T const& get() const { return m_generator->get(); }
4266 bool next() { return m_generator->next(); }
4267};
4268
4269template <typename T> GeneratorWrapper<T> value(T&& value) {
4270 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4271}
4272template <typename T> GeneratorWrapper<T> values(std::initializer_list<T> values) {
4273 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4274}
4275
4276template <typename T> class Generators : public IGenerator<T> {
4277 std::vector<GeneratorWrapper<T>> m_generators;
4278 size_t m_current = 0;
4279
4280 void populate(GeneratorWrapper<T>&& generator) {
4281 m_generators.emplace_back(std::move(generator));
4282 }
4283 void populate(T&& val) { m_generators.emplace_back(value(std::forward<T>(val))); }
4284 template <typename U> void populate(U&& val) { populate(T(std::forward<U>(val))); }
4285 template <typename U, typename... Gs>
4286 void populate(U&& valueOrGenerator, Gs&&... moreGenerators) {
4287 populate(std::forward<U>(valueOrGenerator));
4288 populate(std::forward<Gs>(moreGenerators)...);
4289 }
4290
4291 public:
4292 template <typename... Gs> Generators(Gs&&... moreGenerators) {
4293 m_generators.reserve(sizeof...(Gs));
4294 populate(std::forward<Gs>(moreGenerators)...);
4295 }
4296
4297 T const& get() const override { return m_generators[m_current].get(); }
4298
4299 bool next() override {
4300 if (m_current >= m_generators.size()) {
4301 return false;
4302 }
4303 const bool current_status = m_generators[m_current].next();
4304 if (!current_status) {
4305 ++m_current;
4306 }
4307 return m_current < m_generators.size();
4308 }
4309};
4310
4311template <typename... Ts>
4312GeneratorWrapper<std::tuple<Ts...>>
4313table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples) {
4314 return values<std::tuple<Ts...>>(tuples);
4315}
4316
4317// Tag type to signal that a generator sequence should convert arguments to a
4318// specific type
4319template <typename T> struct as {};
4320
4321template <typename T, typename... Gs>
4322auto makeGenerators(GeneratorWrapper<T>&& generator, Gs&&... moreGenerators) -> Generators<T> {
4323 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4324}
4325template <typename T> auto makeGenerators(GeneratorWrapper<T>&& generator) -> Generators<T> {
4326 return Generators<T>(std::move(generator));
4327}
4328template <typename T, typename... Gs>
4329auto makeGenerators(T&& val, Gs&&... moreGenerators) -> Generators<T> {
4330 return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
4331}
4332template <typename T, typename U, typename... Gs>
4333auto makeGenerators(as<T>, U&& val, Gs&&... moreGenerators) -> Generators<T> {
4334 return makeGenerators(value(T(std::forward<U>(val))), std::forward<Gs>(moreGenerators)...);
4335}
4336
4337auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
4338 -> IGeneratorTracker&;
4339
4340template <typename L>
4341// Note: The type after -> is weird, because VS2015 cannot parse
4342// the expression used in the typedef inside, when it is in
4343// return type. Yeah.
4344auto generate(StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression)
4345 -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4346 using UnderlyingType = typename decltype(generatorExpression())::type;
4347
4348 IGeneratorTracker& tracker = acquireGeneratorTracker(generatorName, lineInfo);
4349 if (!tracker.hasGenerator()) {
4350 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4351 }
4352
4353 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>(*tracker.getGenerator());
4354 return generator.get();
4355}
4356
4357} // namespace Generators
4358} // namespace Catch
4359
4360#define GENERATE(...) \
4361 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4362 CATCH_INTERNAL_LINEINFO, [] { \
4363 using namespace Catch::Generators; \
4364 return makeGenerators(__VA_ARGS__); \
4365 }) // NOLINT(google-build-using-namespace)
4366#define GENERATE_COPY(...) \
4367 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4368 CATCH_INTERNAL_LINEINFO, [=] { \
4369 using namespace Catch::Generators; \
4370 return makeGenerators(__VA_ARGS__); \
4371 }) // NOLINT(google-build-using-namespace)
4372#define GENERATE_REF(...) \
4373 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4374 CATCH_INTERNAL_LINEINFO, [&] { \
4375 using namespace Catch::Generators; \
4376 return makeGenerators(__VA_ARGS__); \
4377 }) // NOLINT(google-build-using-namespace)
4378
4379// end catch_generators.hpp
4380// start catch_generators_generic.hpp
4381
4382namespace Catch {
4383namespace Generators {
4384
4385template <typename T> class TakeGenerator : public IGenerator<T> {
4386 GeneratorWrapper<T> m_generator;
4387 size_t m_returned = 0;
4388 size_t m_target;
4389
4390 public:
4391 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator)
4392 : m_generator(std::move(generator)), m_target(target) {
4393 assert(target != 0 && "Empty generators are not allowed");
4394 }
4395 T const& get() const override { return m_generator.get(); }
4396 bool next() override {
4397 ++m_returned;
4398 if (m_returned >= m_target) {
4399 return false;
4400 }
4401
4402 const auto success = m_generator.next();
4403 // If the underlying generator does not contain enough values
4404 // then we cut short as well
4405 if (!success) {
4406 m_returned = m_target;
4407 }
4408 return success;
4409 }
4410};
4411
4412template <typename T> GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4413 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4414}
4415
4416template <typename T, typename Predicate> class FilterGenerator : public IGenerator<T> {
4417 GeneratorWrapper<T> m_generator;
4418 Predicate m_predicate;
4419
4420 public:
4421 template <typename P = Predicate>
4422 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator)
4423 : m_generator(std::move(generator)), m_predicate(std::forward<P>(pred)) {
4424 if (!m_predicate(m_generator.get())) {
4425 // It might happen that there are no values that pass the
4426 // filter. In that case we throw an exception.
4427 auto has_initial_value = nextImpl();
4428 if (!has_initial_value) {
4429 Catch::throw_exception(
4430 GeneratorException("No valid value found in filtered generator"));
4431 }
4432 }
4433 }
4434
4435 T const& get() const override { return m_generator.get(); }
4436
4437 bool next() override { return nextImpl(); }
4438
4439 private:
4440 bool nextImpl() {
4441 bool success = m_generator.next();
4442 if (!success) {
4443 return false;
4444 }
4445 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true)
4446 ;
4447 return success;
4448 }
4449};
4450
4451template <typename T, typename Predicate>
4452GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4453 return GeneratorWrapper<T>(
4454 std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(
4455 std::forward<Predicate>(pred), std::move(generator))));
4456}
4457
4458template <typename T> class RepeatGenerator : public IGenerator<T> {
4459 static_assert(!std::is_same<T, bool>::value, "RepeatGenerator currently does not support bools"
4460 "because of std::vector<bool> specialization");
4461 GeneratorWrapper<T> m_generator;
4462 mutable std::vector<T> m_returned;
4463 size_t m_target_repeats;
4464 size_t m_current_repeat = 0;
4465 size_t m_repeat_index = 0;
4466
4467 public:
4468 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator)
4469 : m_generator(std::move(generator)), m_target_repeats(repeats) {
4470 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4471 }
4472
4473 T const& get() const override {
4474 if (m_current_repeat == 0) {
4475 m_returned.push_back(m_generator.get());
4476 return m_returned.back();
4477 }
4478 return m_returned[m_repeat_index];
4479 }
4480
4481 bool next() override {
4482 // There are 2 basic cases:
4483 // 1) We are still reading the generator
4484 // 2) We are reading our own cache
4485
4486 // In the first case, we need to poke the underlying generator.
4487 // If it happily moves, we are left in that state, otherwise it is time to
4488 // start reading from our cache
4489 if (m_current_repeat == 0) {
4490 const auto success = m_generator.next();
4491 if (!success) {
4492 ++m_current_repeat;
4493 }
4494 return m_current_repeat < m_target_repeats;
4495 }
4496
4497 // In the second case, we need to move indices forward and check that we
4498 // haven't run up against the end
4499 ++m_repeat_index;
4500 if (m_repeat_index == m_returned.size()) {
4501 m_repeat_index = 0;
4502 ++m_current_repeat;
4503 }
4504 return m_current_repeat < m_target_repeats;
4505 }
4506};
4507
4508template <typename T> GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4509 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4510}
4511
4512template <typename T, typename U, typename Func> class MapGenerator : public IGenerator<T> {
4513 // TBD: provide static assert for mapping function, for friendly error message
4514 GeneratorWrapper<U> m_generator;
4515 Func m_function;
4516 // To avoid returning dangling reference, we have to save the values
4517 T m_cache;
4518
4519 public:
4520 template <typename F2 = Func>
4521 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator)
4522 : m_generator(std::move(generator)), m_function(std::forward<F2>(function)),
4523 m_cache(m_function(m_generator.get())) {}
4524
4525 T const& get() const override { return m_cache; }
4526 bool next() override {
4527 const auto success = m_generator.next();
4528 if (success) {
4529 m_cache = m_function(m_generator.get());
4530 }
4531 return success;
4532 }
4533};
4534
4535template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4536GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4537 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4538 std::forward<Func>(function), std::move(generator)));
4539}
4540
4541template <typename T, typename U, typename Func>
4542GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4543 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4544 std::forward<Func>(function), std::move(generator)));
4545}
4546
4547template <typename T> class ChunkGenerator final : public IGenerator<std::vector<T>> {
4548 std::vector<T> m_chunk;
4549 size_t m_chunk_size;
4550 GeneratorWrapper<T> m_generator;
4551 bool m_used_up = false;
4552
4553 public:
4554 ChunkGenerator(size_t size, GeneratorWrapper<T> generator)
4555 : m_chunk_size(size), m_generator(std::move(generator)) {
4556 m_chunk.reserve(m_chunk_size);
4557 if (m_chunk_size != 0) {
4558 m_chunk.push_back(m_generator.get());
4559 for (size_t i = 1; i < m_chunk_size; ++i) {
4560 if (!m_generator.next()) {
4561 Catch::throw_exception(
4562 GeneratorException("Not enough values to initialize the first chunk"));
4563 }
4564 m_chunk.push_back(m_generator.get());
4565 }
4566 }
4567 }
4568 std::vector<T> const& get() const override { return m_chunk; }
4569 bool next() override {
4570 m_chunk.clear();
4571 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4572 if (!m_generator.next()) {
4573 return false;
4574 }
4575 m_chunk.push_back(m_generator.get());
4576 }
4577 return true;
4578 }
4579};
4580
4581template <typename T>
4582GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4584 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator)));
4585}
4586
4587} // namespace Generators
4588} // namespace Catch
4589
4590// end catch_generators_generic.hpp
4591// start catch_generators_specific.hpp
4592
4593// start catch_context.h
4594
4595#include <memory>
4596
4597namespace Catch {
4598
4599struct IResultCapture;
4600struct IRunner;
4601struct IConfig;
4602struct IMutableContext;
4603
4604using IConfigPtr = std::shared_ptr<IConfig const>;
4605
4606struct IContext {
4607 virtual ~IContext();
4608
4609 virtual IResultCapture* getResultCapture() = 0;
4610 virtual IRunner* getRunner() = 0;
4611 virtual IConfigPtr const& getConfig() const = 0;
4612};
4613
4615 virtual ~IMutableContext();
4616 virtual void setResultCapture(IResultCapture* resultCapture) = 0;
4617 virtual void setRunner(IRunner* runner) = 0;
4618 virtual void setConfig(IConfigPtr const& config) = 0;
4619
4620 private:
4621 static IMutableContext* currentContext;
4622 friend IMutableContext& getCurrentMutableContext();
4623 friend void cleanUpContext();
4624 static void createContext();
4625};
4626
4627inline IMutableContext& getCurrentMutableContext() {
4628 if (!IMutableContext::currentContext)
4629 IMutableContext::createContext();
4630 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4631 return *IMutableContext::currentContext;
4632}
4633
4634inline IContext& getCurrentContext() {
4635 return getCurrentMutableContext();
4636}
4637
4638void cleanUpContext();
4639
4640class SimplePcg32;
4641SimplePcg32& rng();
4642} // namespace Catch
4643
4644// end catch_context.h
4645// start catch_interfaces_config.h
4646
4647// start catch_option.hpp
4648
4649namespace Catch {
4650
4651// An optional type
4652template <typename T> class Option {
4653 public:
4654 Option() : nullableValue(nullptr) {}
4655 Option(T const& _value) : nullableValue(new(storage) T(_value)) {}
4656 Option(Option const& _other) : nullableValue(_other ? new(storage) T(*_other) : nullptr) {}
4657
4658 ~Option() { reset(); }
4659
4660 Option& operator=(Option const& _other) {
4661 if (&_other != this) {
4662 reset();
4663 if (_other)
4664 nullableValue = new (storage) T(*_other);
4665 }
4666 return *this;
4667 }
4668 Option& operator=(T const& _value) {
4669 reset();
4670 nullableValue = new (storage) T(_value);
4671 return *this;
4672 }
4673
4674 void reset() {
4675 if (nullableValue)
4676 nullableValue->~T();
4677 nullableValue = nullptr;
4678 }
4679
4680 T& operator*() { return *nullableValue; }
4681 T const& operator*() const { return *nullableValue; }
4682 T* operator->() { return nullableValue; }
4683 const T* operator->() const { return nullableValue; }
4684
4685 T valueOr(T const& defaultValue) const { return nullableValue ? *nullableValue : defaultValue; }
4686
4687 bool some() const { return nullableValue != nullptr; }
4688 bool none() const { return nullableValue == nullptr; }
4689
4690 bool operator!() const { return nullableValue == nullptr; }
4691 explicit operator bool() const { return some(); }
4692
4693 private:
4694 T* nullableValue;
4695 alignas(alignof(T)) char storage[sizeof(T)];
4696};
4697
4698} // end namespace Catch
4699
4700// end catch_option.hpp
4701#include <chrono>
4702#include <iosfwd>
4703#include <memory>
4704#include <string>
4705#include <vector>
4706
4707namespace Catch {
4708
4709enum class Verbosity { Quiet = 0, Normal, High };
4710
4712 enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 };
4713};
4714
4716 enum OrNot { DefaultForReporter, Always, Never };
4717};
4718struct RunTests {
4719 enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder };
4720};
4722 enum YesOrNo { Auto, Yes, No };
4723};
4725 enum When {
4726 Never,
4727 BeforeStart = 1,
4728 BeforeExit = 2,
4729 BeforeStartAndExit = BeforeStart | BeforeExit
4730 };
4731};
4732
4733class TestSpec;
4734
4735struct IConfig : NonCopyable {
4736
4737 virtual ~IConfig();
4738
4739 virtual bool allowThrows() const = 0;
4740 virtual std::ostream& stream() const = 0;
4741 virtual std::string name() const = 0;
4742 virtual bool includeSuccessfulResults() const = 0;
4743 virtual bool shouldDebugBreak() const = 0;
4744 virtual bool warnAboutMissingAssertions() const = 0;
4745 virtual bool warnAboutNoTests() const = 0;
4746 virtual int abortAfter() const = 0;
4747 virtual bool showInvisibles() const = 0;
4748 virtual ShowDurations::OrNot showDurations() const = 0;
4749 virtual double minDuration() const = 0;
4750 virtual TestSpec const& testSpec() const = 0;
4751 virtual bool hasTestFilters() const = 0;
4752 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4753 virtual RunTests::InWhatOrder runOrder() const = 0;
4754 virtual unsigned int rngSeed() const = 0;
4755 virtual UseColour::YesOrNo useColour() const = 0;
4756 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4757 virtual Verbosity verbosity() const = 0;
4758
4759 virtual bool benchmarkNoAnalysis() const = 0;
4760 virtual int benchmarkSamples() const = 0;
4761 virtual double benchmarkConfidenceInterval() const = 0;
4762 virtual unsigned int benchmarkResamples() const = 0;
4763 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
4764};
4765
4766using IConfigPtr = std::shared_ptr<IConfig const>;
4767} // namespace Catch
4768
4769// end catch_interfaces_config.h
4770// start catch_random_number_generator.h
4771
4772#include <cstdint>
4773
4774namespace Catch {
4775
4776// This is a simple implementation of C++11 Uniform Random Number
4777// Generator. It does not provide all operators, because Catch2
4778// does not use it, but it should behave as expected inside stdlib's
4779// distributions.
4780// The implementation is based on the PCG family (http://pcg-random.org)
4781class SimplePcg32 {
4782 using state_type = std::uint64_t;
4783
4784 public:
4785 using result_type = std::uint32_t;
4786 static constexpr result_type(min)() { return 0; }
4787 static constexpr result_type(max)() { return static_cast<result_type>(-1); }
4788
4789 // Provide some default initial state for the default constructor
4790 SimplePcg32() : SimplePcg32(0xed743cc4U) {}
4791
4792 explicit SimplePcg32(result_type seed_);
4793
4794 void seed(result_type seed_);
4795 void discard(uint64_t skip);
4796
4797 result_type operator()();
4798
4799 private:
4800 friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4801 friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4802
4803 // In theory we also need operator<< and operator>>
4804 // In practice we do not use them, so we will skip them for now
4805
4806 std::uint64_t m_state;
4807 // This part of the state determines which "stream" of the numbers
4808 // is chosen -- we take it as a constant for Catch2, so we only
4809 // need to deal with seeding the main state.
4810 // Picked by reading 8 bytes from `/dev/random` :-)
4811 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4812};
4813
4814} // end namespace Catch
4815
4816// end catch_random_number_generator.h
4817#include <random>
4818
4819namespace Catch {
4820namespace Generators {
4821
4822template <typename Float> class RandomFloatingGenerator final : public IGenerator<Float> {
4823 Catch::SimplePcg32& m_rng;
4824 std::uniform_real_distribution<Float> m_dist;
4825 Float m_current_number;
4826
4827 public:
4828 RandomFloatingGenerator(Float a, Float b) : m_rng(rng()), m_dist(a, b) {
4829 static_cast<void>(next());
4830 }
4831
4832 Float const& get() const override { return m_current_number; }
4833 bool next() override {
4834 m_current_number = m_dist(m_rng);
4835 return true;
4836 }
4837};
4838
4839template <typename Integer> class RandomIntegerGenerator final : public IGenerator<Integer> {
4840 Catch::SimplePcg32& m_rng;
4841 std::uniform_int_distribution<Integer> m_dist;
4842 Integer m_current_number;
4843
4844 public:
4845 RandomIntegerGenerator(Integer a, Integer b) : m_rng(rng()), m_dist(a, b) {
4846 static_cast<void>(next());
4847 }
4848
4849 Integer const& get() const override { return m_current_number; }
4850 bool next() override {
4851 m_current_number = m_dist(m_rng);
4852 return true;
4853 }
4854};
4855
4856// TODO: Ideally this would be also constrained against the various char types,
4857// but I don't expect users to run into that in practice.
4858template <typename T>
4859typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4860 GeneratorWrapper<T>>::type
4861random(T a, T b) {
4862 return GeneratorWrapper<T>(pf::make_unique<RandomIntegerGenerator<T>>(a, b));
4863}
4864
4865template <typename T>
4866typename std::enable_if<std::is_floating_point<T>::value, GeneratorWrapper<T>>::type random(T a,
4867 T b) {
4868 return GeneratorWrapper<T>(pf::make_unique<RandomFloatingGenerator<T>>(a, b));
4869}
4870
4871template <typename T> class RangeGenerator final : public IGenerator<T> {
4872 T m_current;
4873 T m_end;
4874 T m_step;
4875 bool m_positive;
4876
4877 public:
4878 RangeGenerator(T const& start, T const& end, T const& step)
4879 : m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0)) {
4880 assert(m_current != m_end && "Range start and end cannot be equal");
4881 assert(m_step != T(0) && "Step size cannot be zero");
4882 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
4883 "Step moves away from end");
4884 }
4885
4886 RangeGenerator(T const& start, T const& end)
4887 : RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {}
4888
4889 T const& get() const override { return m_current; }
4890
4891 bool next() override {
4892 m_current += m_step;
4893 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4894 }
4895};
4896
4897template <typename T> GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4898 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
4899 "Type must be numeric");
4900 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4901}
4902
4903template <typename T> GeneratorWrapper<T> range(T const& start, T const& end) {
4904 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
4905 "Type must be an integer");
4906 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4907}
4908
4909template <typename T> class IteratorGenerator final : public IGenerator<T> {
4910 static_assert(!std::is_same<T, bool>::value,
4911 "IteratorGenerator currently does not support bools"
4912 "because of std::vector<bool> specialization");
4913
4914 std::vector<T> m_elems;
4915 size_t m_current = 0;
4916
4917 public:
4918 template <typename InputIterator, typename InputSentinel>
4919 IteratorGenerator(InputIterator first, InputSentinel last) : m_elems(first, last) {
4920 if (m_elems.empty()) {
4921 Catch::throw_exception(
4922 GeneratorException("IteratorGenerator received no valid values"));
4923 }
4924 }
4925
4926 T const& get() const override { return m_elems[m_current]; }
4927
4928 bool next() override {
4929 ++m_current;
4930 return m_current != m_elems.size();
4931 }
4932};
4933
4934template <typename InputIterator, typename InputSentinel,
4935 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
4936GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
4937 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
4938}
4939
4940template <typename Container, typename ResultType = typename Container::value_type>
4941GeneratorWrapper<ResultType> from_range(Container const& cnt) {
4942 return GeneratorWrapper<ResultType>(
4943 pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4944}
4945
4946} // namespace Generators
4947} // namespace Catch
4948
4949// end catch_generators_specific.hpp
4950
4951// These files are included here so the single_include script doesn't put them
4952// in the conditionally compiled sections
4953// start catch_test_case_info.h
4954
4955#include <memory>
4956#include <string>
4957#include <vector>
4958
4959#ifdef __clang__
4960#pragma clang diagnostic push
4961#pragma clang diagnostic ignored "-Wpadded"
4962#endif
4963
4964namespace Catch {
4965
4966struct ITestInvoker;
4967
4968struct TestCaseInfo {
4969 enum SpecialProperties {
4970 None = 0,
4971 IsHidden = 1 << 1,
4972 ShouldFail = 1 << 2,
4973 MayFail = 1 << 3,
4974 Throws = 1 << 4,
4975 NonPortable = 1 << 5,
4976 Benchmark = 1 << 6
4977 };
4978
4979 TestCaseInfo(std::string const& _name, std::string const& _className,
4980 std::string const& _description, std::vector<std::string> const& _tags,
4981 SourceLineInfo const& _lineInfo);
4982
4983 friend void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags);
4984
4985 bool isHidden() const;
4986 bool throws() const;
4987 bool okToFail() const;
4988 bool expectedToFail() const;
4989
4990 std::string tagsAsString() const;
4991
4992 std::string name;
4993 std::string className;
4994 std::string description;
4995 std::vector<std::string> tags;
4996 std::vector<std::string> lcaseTags;
4997 SourceLineInfo lineInfo;
4998 SpecialProperties properties;
4999};
5000
5001class TestCase : public TestCaseInfo {
5002 public:
5003 TestCase(ITestInvoker* testCase, TestCaseInfo&& info);
5004
5005 TestCase withName(std::string const& _newName) const;
5006
5007 void invoke() const;
5008
5009 TestCaseInfo const& getTestCaseInfo() const;
5010
5011 bool operator==(TestCase const& other) const;
5012 bool operator<(TestCase const& other) const;
5013
5014 private:
5015 std::shared_ptr<ITestInvoker> test;
5016};
5017
5018TestCase makeTestCase(ITestInvoker* testCase, std::string const& className,
5019 NameAndTags const& nameAndTags, SourceLineInfo const& lineInfo);
5020} // namespace Catch
5021
5022#ifdef __clang__
5023#pragma clang diagnostic pop
5024#endif
5025
5026// end catch_test_case_info.h
5027// start catch_interfaces_runner.h
5028
5029namespace Catch {
5030
5031struct IRunner {
5032 virtual ~IRunner();
5033 virtual bool aborting() const = 0;
5034};
5035} // namespace Catch
5036
5037// end catch_interfaces_runner.h
5038
5039#ifdef __OBJC__
5040// start catch_objc.hpp
5041
5042#import <objc/runtime.h>
5043
5044#include <string>
5045
5046// NB. Any general catch headers included here must be included
5047// in catch.hpp first to make sure they are included by the single
5048// header for non obj-usage
5049
5051// This protocol is really only here for (self) documenting purposes, since
5052// all its methods are optional.
5053@protocol OcFixture
5054
5055@optional
5056
5057- (void)setUp;
5058- (void)tearDown;
5059
5060@end
5061
5062namespace Catch {
5063
5064class OcMethod : public ITestInvoker {
5065
5066 public:
5067 OcMethod(Class cls, SEL sel) : m_cls(cls), m_sel(sel) {}
5068
5069 virtual void invoke() const {
5070 id obj = [[m_cls alloc] init];
5071
5072 performOptionalSelector(obj, @selector(setUp));
5073 performOptionalSelector(obj, m_sel);
5074 performOptionalSelector(obj, @selector(tearDown));
5075
5076 arcSafeRelease(obj);
5077 }
5078
5079 private:
5080 virtual ~OcMethod() {}
5081
5082 Class m_cls;
5083 SEL m_sel;
5084};
5085
5086namespace Detail {
5087
5088inline std::string getAnnotation(Class cls, std::string const& annotationName,
5089 std::string const& testCaseName) {
5090 NSString* selStr = [[NSString alloc]
5091 initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
5092 SEL sel = NSSelectorFromString(selStr);
5093 arcSafeRelease(selStr);
5094 id value = performOptionalSelector(cls, sel);
5095 if (value)
5096 return [(NSString*)value UTF8String];
5097 return "";
5098}
5099} // namespace Detail
5100
5101inline std::size_t registerTestMethods() {
5102 std::size_t noTestMethods = 0;
5103 int noClasses = objc_getClassList(nullptr, 0);
5104
5105 Class* classes = (CATCH_UNSAFE_UNRETAINED Class*)malloc(sizeof(Class) * noClasses);
5106 objc_getClassList(classes, noClasses);
5107
5108 for (int c = 0; c < noClasses; c++) {
5109 Class cls = classes[c];
5110 {
5111 u_int count;
5112 Method* methods = class_copyMethodList(cls, &count);
5113 for (u_int m = 0; m < count; m++) {
5114 SEL selector = method_getName(methods[m]);
5115 std::string methodName = sel_getName(selector);
5116 if (startsWith(methodName, "Catch_TestCase_")) {
5117 std::string testCaseName = methodName.substr(15);
5118 std::string name = Detail::getAnnotation(cls, "Name", testCaseName);
5119 std::string desc = Detail::getAnnotation(cls, "Description", testCaseName);
5120 const char* className = class_getName(cls);
5121
5122 getMutableRegistryHub().registerTest(makeTestCase(
5123 new OcMethod(cls, selector), className,
5124 NameAndTags(name.c_str(), desc.c_str()), SourceLineInfo("", 0)));
5125 noTestMethods++;
5126 }
5127 }
5128 free(methods);
5129 }
5130 }
5131 return noTestMethods;
5132}
5133
5134#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
5135
5136namespace Matchers {
5137namespace Impl {
5138namespace NSStringMatchers {
5139
5140struct StringHolder : MatcherBase<NSString*> {
5141 StringHolder(NSString* substr) : m_substr([substr copy]) {}
5142 StringHolder(StringHolder const& other) : m_substr([other.m_substr copy]) {}
5143 StringHolder() { arcSafeRelease(m_substr); }
5144
5145 bool match(NSString* str) const override { return false; }
5146
5147 NSString* CATCH_ARC_STRONG m_substr;
5148};
5149
5150struct Equals : StringHolder {
5151 Equals(NSString* substr) : StringHolder(substr) {}
5152
5153 bool match(NSString* str) const override {
5154 return (str != nil || m_substr == nil) && [str isEqualToString:m_substr];
5155 }
5156
5157 std::string describe() const override {
5158 return "equals string: " + Catch::Detail::stringify(m_substr);
5159 }
5160};
5161
5162struct Contains : StringHolder {
5163 Contains(NSString* substr) : StringHolder(substr) {}
5164
5165 bool match(NSString* str) const override {
5166 return (str != nil || m_substr == nil) &&
5167 [str rangeOfString:m_substr].location != NSNotFound;
5168 }
5169
5170 std::string describe() const override {
5171 return "contains string: " + Catch::Detail::stringify(m_substr);
5172 }
5173};
5174
5175struct StartsWith : StringHolder {
5176 StartsWith(NSString* substr) : StringHolder(substr) {}
5177
5178 bool match(NSString* str) const override {
5179 return (str != nil || m_substr == nil) && [str rangeOfString:m_substr].location == 0;
5180 }
5181
5182 std::string describe() const override {
5183 return "starts with: " + Catch::Detail::stringify(m_substr);
5184 }
5185};
5186struct EndsWith : StringHolder {
5187 EndsWith(NSString* substr) : StringHolder(substr) {}
5188
5189 bool match(NSString* str) const override {
5190 return (str != nil || m_substr == nil) &&
5191 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5192 }
5193
5194 std::string describe() const override {
5195 return "ends with: " + Catch::Detail::stringify(m_substr);
5196 }
5197};
5198
5199} // namespace NSStringMatchers
5200} // namespace Impl
5201
5202inline Impl::NSStringMatchers::Equals Equals(NSString* substr) {
5203 return Impl::NSStringMatchers::Equals(substr);
5204}
5205
5206inline Impl::NSStringMatchers::Contains Contains(NSString* substr) {
5207 return Impl::NSStringMatchers::Contains(substr);
5208}
5209
5210inline Impl::NSStringMatchers::StartsWith StartsWith(NSString* substr) {
5211 return Impl::NSStringMatchers::StartsWith(substr);
5212}
5213
5214inline Impl::NSStringMatchers::EndsWith EndsWith(NSString* substr) {
5215 return Impl::NSStringMatchers::EndsWith(substr);
5216}
5217
5218} // namespace Matchers
5219
5220using namespace Matchers;
5221
5222#endif // CATCH_CONFIG_DISABLE_MATCHERS
5223
5224} // namespace Catch
5225
5227#define OC_MAKE_UNIQUE_NAME(root, uniqueSuffix) root##uniqueSuffix
5228#define OC_TEST_CASE2(name, desc, uniqueSuffix) \
5229 +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Name_test_, uniqueSuffix) { \
5230 return @name; \
5231 } \
5232 +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Description_test_, uniqueSuffix) { \
5233 return @desc; \
5234 } \
5235 -(void)OC_MAKE_UNIQUE_NAME(Catch_TestCase_test_, uniqueSuffix)
5236
5237#define OC_TEST_CASE(name, desc) OC_TEST_CASE2(name, desc, __LINE__)
5238
5239// end catch_objc.hpp
5240#endif
5241
5242// Benchmarking needs the externally-facing parts of reporters to work
5243#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5244// start catch_external_interfaces.h
5245
5246// start catch_reporter_bases.hpp
5247
5248// start catch_interfaces_reporter.h
5249
5250// start catch_config.hpp
5251
5252// start catch_test_spec_parser.h
5253
5254#ifdef __clang__
5255#pragma clang diagnostic push
5256#pragma clang diagnostic ignored "-Wpadded"
5257#endif
5258
5259// start catch_test_spec.h
5260
5261#ifdef __clang__
5262#pragma clang diagnostic push
5263#pragma clang diagnostic ignored "-Wpadded"
5264#endif
5265
5266// start catch_wildcard_pattern.h
5267
5268namespace Catch {
5269class WildcardPattern {
5270 enum WildcardPosition {
5271 NoWildcard = 0,
5272 WildcardAtStart = 1,
5273 WildcardAtEnd = 2,
5274 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5275 };
5276
5277 public:
5278 WildcardPattern(std::string const& pattern, CaseSensitive::Choice caseSensitivity);
5279 virtual ~WildcardPattern() = default;
5280 virtual bool matches(std::string const& str) const;
5281
5282 private:
5283 std::string normaliseString(std::string const& str) const;
5284 CaseSensitive::Choice m_caseSensitivity;
5285 WildcardPosition m_wildcard = NoWildcard;
5286 std::string m_pattern;
5287};
5288} // namespace Catch
5289
5290// end catch_wildcard_pattern.h
5291#include <memory>
5292#include <string>
5293#include <vector>
5294
5295namespace Catch {
5296
5297struct IConfig;
5298
5299class TestSpec {
5300 class Pattern {
5301 public:
5302 explicit Pattern(std::string const& name);
5303 virtual ~Pattern();
5304 virtual bool matches(TestCaseInfo const& testCase) const = 0;
5305 std::string const& name() const;
5306
5307 private:
5308 std::string const m_name;
5309 };
5310 using PatternPtr = std::shared_ptr<Pattern>;
5311
5312 class NamePattern : public Pattern {
5313 public:
5314 explicit NamePattern(std::string const& name, std::string const& filterString);
5315 bool matches(TestCaseInfo const& testCase) const override;
5316
5317 private:
5318 WildcardPattern m_wildcardPattern;
5319 };
5320
5321 class TagPattern : public Pattern {
5322 public:
5323 explicit TagPattern(std::string const& tag, std::string const& filterString);
5324 bool matches(TestCaseInfo const& testCase) const override;
5325
5326 private:
5327 std::string m_tag;
5328 };
5329
5330 class ExcludedPattern : public Pattern {
5331 public:
5332 explicit ExcludedPattern(PatternPtr const& underlyingPattern);
5333 bool matches(TestCaseInfo const& testCase) const override;
5334
5335 private:
5336 PatternPtr m_underlyingPattern;
5337 };
5338
5339 struct Filter {
5340 std::vector<PatternPtr> m_patterns;
5341
5342 bool matches(TestCaseInfo const& testCase) const;
5343 std::string name() const;
5344 };
5345
5346 public:
5347 struct FilterMatch {
5348 std::string name;
5349 std::vector<TestCase const*> tests;
5350 };
5351 using Matches = std::vector<FilterMatch>;
5352 using vectorStrings = std::vector<std::string>;
5353
5354 bool hasFilters() const;
5355 bool matches(TestCaseInfo const& testCase) const;
5356 Matches matchesByFilter(std::vector<TestCase> const& testCases, IConfig const& config) const;
5357 const vectorStrings& getInvalidArgs() const;
5358
5359 private:
5360 std::vector<Filter> m_filters;
5361 std::vector<std::string> m_invalidArgs;
5362 friend class TestSpecParser;
5363};
5364} // namespace Catch
5365
5366#ifdef __clang__
5367#pragma clang diagnostic pop
5368#endif
5369
5370// end catch_test_spec.h
5371// start catch_interfaces_tag_alias_registry.h
5372
5373#include <string>
5374
5375namespace Catch {
5376
5377struct TagAlias;
5378
5379struct ITagAliasRegistry {
5380 virtual ~ITagAliasRegistry();
5381 // Nullptr if not present
5382 virtual TagAlias const* find(std::string const& alias) const = 0;
5383 virtual std::string expandAliases(std::string const& unexpandedTestSpec) const = 0;
5384
5385 static ITagAliasRegistry const& get();
5386};
5387
5388} // end namespace Catch
5389
5390// end catch_interfaces_tag_alias_registry.h
5391namespace Catch {
5392
5393class TestSpecParser {
5394 enum Mode { None, Name, QuotedName, Tag, EscapedName };
5395 Mode m_mode = None;
5396 Mode lastMode = None;
5397 bool m_exclusion = false;
5398 std::size_t m_pos = 0;
5399 std::size_t m_realPatternPos = 0;
5400 std::string m_arg;
5401 std::string m_substring;
5402 std::string m_patternName;
5403 std::vector<std::size_t> m_escapeChars;
5404 TestSpec::Filter m_currentFilter;
5405 TestSpec m_testSpec;
5406 ITagAliasRegistry const* m_tagAliases = nullptr;
5407
5408 public:
5409 TestSpecParser(ITagAliasRegistry const& tagAliases);
5410
5411 TestSpecParser& parse(std::string const& arg);
5412 TestSpec testSpec();
5413
5414 private:
5415 bool visitChar(char c);
5416 void startNewMode(Mode mode);
5417 bool processNoneChar(char c);
5418 void processNameChar(char c);
5419 bool processOtherChar(char c);
5420 void endMode();
5421 void escape();
5422 bool isControlChar(char c) const;
5423 void saveLastMode();
5424 void revertBackToLastMode();
5425 void addFilter();
5426 bool separate();
5427
5428 // Handles common preprocessing of the pattern for name/tag patterns
5429 std::string preprocessPattern();
5430 // Adds the current pattern as a test name
5431 void addNamePattern();
5432 // Adds the current pattern as a tag
5433 void addTagPattern();
5434
5435 inline void addCharToPattern(char c) {
5436 m_substring += c;
5437 m_patternName += c;
5438 m_realPatternPos++;
5439 }
5440};
5441TestSpec parseTestSpec(std::string const& arg);
5442
5443} // namespace Catch
5444
5445#ifdef __clang__
5446#pragma clang diagnostic pop
5447#endif
5448
5449// end catch_test_spec_parser.h
5450// Libstdc++ doesn't like incomplete classes for unique_ptr
5451
5452#include <memory>
5453#include <string>
5454#include <vector>
5455
5456#ifndef CATCH_CONFIG_CONSOLE_WIDTH
5457#define CATCH_CONFIG_CONSOLE_WIDTH 80
5458#endif
5459
5460namespace Catch {
5461
5462struct IStream;
5463
5464struct ConfigData {
5465 bool listTests = false;
5466 bool listTags = false;
5467 bool listReporters = false;
5468 bool listTestNamesOnly = false;
5469
5470 bool showSuccessfulTests = false;
5471 bool shouldDebugBreak = false;
5472 bool noThrow = false;
5473 bool showHelp = false;
5474 bool showInvisibles = false;
5475 bool filenamesAsTags = false;
5476 bool libIdentify = false;
5477
5478 int abortAfter = -1;
5479 unsigned int rngSeed = 0;
5480
5481 bool benchmarkNoAnalysis = false;
5482 unsigned int benchmarkSamples = 100;
5483 double benchmarkConfidenceInterval = 0.95;
5484 unsigned int benchmarkResamples = 100000;
5485 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5486
5487 Verbosity verbosity = Verbosity::Normal;
5488 WarnAbout::What warnings = WarnAbout::Nothing;
5489 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5490 double minDuration = -1;
5491 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5492 UseColour::YesOrNo useColour = UseColour::Auto;
5493 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5494
5495 std::string outputFilename;
5496 std::string name;
5497 std::string processName;
5498#ifndef CATCH_CONFIG_DEFAULT_REPORTER
5499#define CATCH_CONFIG_DEFAULT_REPORTER "console"
5500#endif
5501 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5502#undef CATCH_CONFIG_DEFAULT_REPORTER
5503
5504 std::vector<std::string> testsOrTags;
5505 std::vector<std::string> sectionsToRun;
5506};
5507
5508class Config : public IConfig {
5509 public:
5510 Config() = default;
5511 Config(ConfigData const& data);
5512 virtual ~Config() = default;
5513
5514 std::string const& getFilename() const;
5515
5516 bool listTests() const;
5517 bool listTestNamesOnly() const;
5518 bool listTags() const;
5519 bool listReporters() const;
5520
5521 std::string getProcessName() const;
5522 std::string const& getReporterName() const;
5523
5524 std::vector<std::string> const& getTestsOrTags() const override;
5525 std::vector<std::string> const& getSectionsToRun() const override;
5526
5527 TestSpec const& testSpec() const override;
5528 bool hasTestFilters() const override;
5529
5530 bool showHelp() const;
5531
5532 // IConfig interface
5533 bool allowThrows() const override;
5534 std::ostream& stream() const override;
5535 std::string name() const override;
5536 bool includeSuccessfulResults() const override;
5537 bool warnAboutMissingAssertions() const override;
5538 bool warnAboutNoTests() const override;
5539 ShowDurations::OrNot showDurations() const override;
5540 double minDuration() const override;
5541 RunTests::InWhatOrder runOrder() const override;
5542 unsigned int rngSeed() const override;
5543 UseColour::YesOrNo useColour() const override;
5544 bool shouldDebugBreak() const override;
5545 int abortAfter() const override;
5546 bool showInvisibles() const override;
5547 Verbosity verbosity() const override;
5548 bool benchmarkNoAnalysis() const override;
5549 int benchmarkSamples() const override;
5550 double benchmarkConfidenceInterval() const override;
5551 unsigned int benchmarkResamples() const override;
5552 std::chrono::milliseconds benchmarkWarmupTime() const override;
5553
5554 private:
5555 IStream const* openStream();
5556 ConfigData m_data;
5557
5558 std::unique_ptr<IStream const> m_stream;
5559 TestSpec m_testSpec;
5560 bool m_hasTestFilters = false;
5561};
5562
5563} // end namespace Catch
5564
5565// end catch_config.hpp
5566// start catch_assertionresult.h
5567
5568#include <string>
5569
5570namespace Catch {
5571
5572struct AssertionResultData {
5573 AssertionResultData() = delete;
5574
5575 AssertionResultData(ResultWas::OfType _resultType, LazyExpression const& _lazyExpression);
5576
5577 std::string message;
5578 mutable std::string reconstructedExpression;
5579 LazyExpression lazyExpression;
5580 ResultWas::OfType resultType;
5581
5582 std::string reconstructExpression() const;
5583};
5584
5585class AssertionResult {
5586 public:
5587 AssertionResult() = delete;
5588 AssertionResult(AssertionInfo const& info, AssertionResultData const& data);
5589
5590 bool isOk() const;
5591 bool succeeded() const;
5592 ResultWas::OfType getResultType() const;
5593 bool hasExpression() const;
5594 bool hasMessage() const;
5595 std::string getExpression() const;
5596 std::string getExpressionInMacro() const;
5597 bool hasExpandedExpression() const;
5598 std::string getExpandedExpression() const;
5599 std::string getMessage() const;
5600 SourceLineInfo getSourceInfo() const;
5601 StringRef getTestMacroName() const;
5602
5603 // protected:
5604 AssertionInfo m_info;
5605 AssertionResultData m_resultData;
5606};
5607
5608} // end namespace Catch
5609
5610// end catch_assertionresult.h
5611#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5612// start catch_estimate.hpp
5613
5614// Statistics estimates
5615
5616namespace Catch {
5617namespace Benchmark {
5618template <typename Duration> struct Estimate {
5619 Duration point;
5620 Duration lower_bound;
5621 Duration upper_bound;
5622 double confidence_interval;
5623
5624 template <typename Duration2> operator Estimate<Duration2>() const {
5625 return {point, lower_bound, upper_bound, confidence_interval};
5626 }
5627};
5628} // namespace Benchmark
5629} // namespace Catch
5630
5631// end catch_estimate.hpp
5632// start catch_outlier_classification.hpp
5633
5634// Outlier information
5635
5636namespace Catch {
5637namespace Benchmark {
5638struct OutlierClassification {
5639 int samples_seen = 0;
5640 int low_severe = 0; // more than 3 times IQR below Q1
5641 int low_mild = 0; // 1.5 to 3 times IQR below Q1
5642 int high_mild = 0; // 1.5 to 3 times IQR above Q3
5643 int high_severe = 0; // more than 3 times IQR above Q3
5644
5645 int total() const { return low_severe + low_mild + high_mild + high_severe; }
5646};
5647} // namespace Benchmark
5648} // namespace Catch
5649
5650// end catch_outlier_classification.hpp
5651
5652#include <iterator>
5653#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5654
5655#include <algorithm>
5656#include <iosfwd>
5657#include <map>
5658#include <memory>
5659#include <set>
5660#include <string>
5661
5662namespace Catch {
5663
5664struct ReporterConfig {
5665 explicit ReporterConfig(IConfigPtr const& _fullConfig);
5666
5667 ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream);
5668
5669 std::ostream& stream() const;
5670 IConfigPtr fullConfig() const;
5671
5672 private:
5673 std::ostream* m_stream;
5674 IConfigPtr m_fullConfig;
5675};
5676
5677struct ReporterPreferences {
5678 bool shouldRedirectStdOut = false;
5679 bool shouldReportAllAssertions = false;
5680};
5681
5682template <typename T> struct LazyStat : Option<T> {
5683 LazyStat& operator=(T const& _value) {
5684 Option<T>::operator=(_value);
5685 used = false;
5686 return *this;
5687 }
5688 void reset() {
5689 Option<T>::reset();
5690 used = false;
5691 }
5692 bool used = false;
5693};
5694
5695struct TestRunInfo {
5696 TestRunInfo(std::string const& _name);
5697 std::string name;
5698};
5699struct GroupInfo {
5700 GroupInfo(std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount);
5701
5702 std::string name;
5703 std::size_t groupIndex;
5704 std::size_t groupsCounts;
5705};
5706
5707struct AssertionStats {
5708 AssertionStats(AssertionResult const& _assertionResult,
5709 std::vector<MessageInfo> const& _infoMessages, Totals const& _totals);
5710
5711 AssertionStats(AssertionStats const&) = default;
5712 AssertionStats(AssertionStats&&) = default;
5713 AssertionStats& operator=(AssertionStats const&) = delete;
5714 AssertionStats& operator=(AssertionStats&&) = delete;
5715 virtual ~AssertionStats();
5716
5717 AssertionResult assertionResult;
5718 std::vector<MessageInfo> infoMessages;
5719 Totals totals;
5720};
5721
5722struct SectionStats {
5723 SectionStats(SectionInfo const& _sectionInfo, Counts const& _assertions,
5724 double _durationInSeconds, bool _missingAssertions);
5725 SectionStats(SectionStats const&) = default;
5726 SectionStats(SectionStats&&) = default;
5727 SectionStats& operator=(SectionStats const&) = default;
5728 SectionStats& operator=(SectionStats&&) = default;
5729 virtual ~SectionStats();
5730
5731 SectionInfo sectionInfo;
5732 Counts assertions;
5733 double durationInSeconds;
5734 bool missingAssertions;
5735};
5736
5737struct TestCaseStats {
5738 TestCaseStats(TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut,
5739 std::string const& _stdErr, bool _aborting);
5740
5741 TestCaseStats(TestCaseStats const&) = default;
5742 TestCaseStats(TestCaseStats&&) = default;
5743 TestCaseStats& operator=(TestCaseStats const&) = default;
5744 TestCaseStats& operator=(TestCaseStats&&) = default;
5745 virtual ~TestCaseStats();
5746
5747 TestCaseInfo testInfo;
5748 Totals totals;
5749 std::string stdOut;
5750 std::string stdErr;
5751 bool aborting;
5752};
5753
5754struct TestGroupStats {
5755 TestGroupStats(GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting);
5756 TestGroupStats(GroupInfo const& _groupInfo);
5757
5758 TestGroupStats(TestGroupStats const&) = default;
5759 TestGroupStats(TestGroupStats&&) = default;
5760 TestGroupStats& operator=(TestGroupStats const&) = default;
5761 TestGroupStats& operator=(TestGroupStats&&) = default;
5762 virtual ~TestGroupStats();
5763
5764 GroupInfo groupInfo;
5765 Totals totals;
5766 bool aborting;
5767};
5768
5769struct TestRunStats {
5770 TestRunStats(TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting);
5771
5772 TestRunStats(TestRunStats const&) = default;
5773 TestRunStats(TestRunStats&&) = default;
5774 TestRunStats& operator=(TestRunStats const&) = default;
5775 TestRunStats& operator=(TestRunStats&&) = default;
5776 virtual ~TestRunStats();
5777
5778 TestRunInfo runInfo;
5779 Totals totals;
5780 bool aborting;
5781};
5782
5783#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5784struct BenchmarkInfo {
5785 std::string name;
5786 double estimatedDuration;
5787 int iterations;
5788 int samples;
5789 unsigned int resamples;
5790 double clockResolution;
5791 double clockCost;
5792};
5793
5794template <class Duration> struct BenchmarkStats {
5795 BenchmarkInfo info;
5796
5797 std::vector<Duration> samples;
5798 Benchmark::Estimate<Duration> mean;
5799 Benchmark::Estimate<Duration> standardDeviation;
5800 Benchmark::OutlierClassification outliers;
5801 double outlierVariance;
5802
5803 template <typename Duration2> operator BenchmarkStats<Duration2>() const {
5804 std::vector<Duration2> samples2;
5805 samples2.reserve(samples.size());
5806 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
5807 [](Duration d) { return Duration2(d); });
5808 return {
5809 info, std::move(samples2), mean, standardDeviation, outliers, outlierVariance,
5810 };
5811 }
5812};
5813#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5814
5815struct IStreamingReporter {
5816 virtual ~IStreamingReporter() = default;
5817
5818 // Implementing class must also provide the following static methods:
5819 // static std::string getDescription();
5820 // static std::set<Verbosity> getSupportedVerbosities()
5821
5822 virtual ReporterPreferences getPreferences() const = 0;
5823
5824 virtual void noMatchingTestCases(std::string const& spec) = 0;
5825
5826 virtual void reportInvalidArguments(std::string const&) {}
5827
5828 virtual void testRunStarting(TestRunInfo const& testRunInfo) = 0;
5829 virtual void testGroupStarting(GroupInfo const& groupInfo) = 0;
5830
5831 virtual void testCaseStarting(TestCaseInfo const& testInfo) = 0;
5832 virtual void sectionStarting(SectionInfo const& sectionInfo) = 0;
5833
5834#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5835 virtual void benchmarkPreparing(std::string const&) {}
5836 virtual void benchmarkStarting(BenchmarkInfo const&) {}
5837 virtual void benchmarkEnded(BenchmarkStats<> const&) {}
5838 virtual void benchmarkFailed(std::string const&) {}
5839#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5840
5841 virtual void assertionStarting(AssertionInfo const& assertionInfo) = 0;
5842
5843 // The return value indicates if the messages buffer should be cleared:
5844 virtual bool assertionEnded(AssertionStats const& assertionStats) = 0;
5845
5846 virtual void sectionEnded(SectionStats const& sectionStats) = 0;
5847 virtual void testCaseEnded(TestCaseStats const& testCaseStats) = 0;
5848 virtual void testGroupEnded(TestGroupStats const& testGroupStats) = 0;
5849 virtual void testRunEnded(TestRunStats const& testRunStats) = 0;
5850
5851 virtual void skipTest(TestCaseInfo const& testInfo) = 0;
5852
5853 // Default empty implementation provided
5854 virtual void fatalErrorEncountered(StringRef name);
5855
5856 virtual bool isMulti() const;
5857};
5858using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5859
5860struct IReporterFactory {
5861 virtual ~IReporterFactory();
5862 virtual IStreamingReporterPtr create(ReporterConfig const& config) const = 0;
5863 virtual std::string getDescription() const = 0;
5864};
5865using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5866
5867struct IReporterRegistry {
5868 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5869 using Listeners = std::vector<IReporterFactoryPtr>;
5870
5871 virtual ~IReporterRegistry();
5872 virtual IStreamingReporterPtr create(std::string const& name,
5873 IConfigPtr const& config) const = 0;
5874 virtual FactoryMap const& getFactories() const = 0;
5875 virtual Listeners const& getListeners() const = 0;
5876};
5877
5878} // end namespace Catch
5879
5880// end catch_interfaces_reporter.h
5881#include <algorithm>
5882#include <cassert>
5883#include <cfloat>
5884#include <cstdio>
5885#include <cstring>
5886#include <memory>
5887#include <ostream>
5888
5889namespace Catch {
5890void prepareExpandedExpression(AssertionResult& result);
5891
5892// Returns double formatted as %.3f (format expected on output)
5893std::string getFormattedDuration(double duration);
5894
5896bool shouldShowDuration(IConfig const& config, double duration);
5897
5898std::string serializeFilters(std::vector<std::string> const& container);
5899
5900template <typename DerivedT> struct StreamingReporterBase : IStreamingReporter {
5901
5902 StreamingReporterBase(ReporterConfig const& _config)
5903 : m_config(_config.fullConfig()), stream(_config.stream()) {
5904 m_reporterPrefs.shouldRedirectStdOut = false;
5905 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
5906 CATCH_ERROR("Verbosity level not supported by this reporter");
5907 }
5908
5909 ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
5910
5911 static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
5912
5913 ~StreamingReporterBase() override = default;
5914
5915 void noMatchingTestCases(std::string const&) override {}
5916
5917 void reportInvalidArguments(std::string const&) override {}
5918
5919 void testRunStarting(TestRunInfo const& _testRunInfo) override {
5920 currentTestRunInfo = _testRunInfo;
5921 }
5922
5923 void testGroupStarting(GroupInfo const& _groupInfo) override { currentGroupInfo = _groupInfo; }
5924
5925 void testCaseStarting(TestCaseInfo const& _testInfo) override {
5926 currentTestCaseInfo = _testInfo;
5927 }
5928 void sectionStarting(SectionInfo const& _sectionInfo) override {
5929 m_sectionStack.push_back(_sectionInfo);
5930 }
5931
5932 void sectionEnded(SectionStats const& /* _sectionStats */) override {
5933 m_sectionStack.pop_back();
5934 }
5935 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5936 currentTestCaseInfo.reset();
5937 }
5938 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5939 currentGroupInfo.reset();
5940 }
5941 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5942 currentTestCaseInfo.reset();
5943 currentGroupInfo.reset();
5944 currentTestRunInfo.reset();
5945 }
5946
5947 void skipTest(TestCaseInfo const&) override {
5948 // Don't do anything with this by default.
5949 // It can optionally be overridden in the derived class.
5950 }
5951
5952 IConfigPtr m_config;
5953 std::ostream& stream;
5954
5955 LazyStat<TestRunInfo> currentTestRunInfo;
5956 LazyStat<GroupInfo> currentGroupInfo;
5957 LazyStat<TestCaseInfo> currentTestCaseInfo;
5958
5959 std::vector<SectionInfo> m_sectionStack;
5960 ReporterPreferences m_reporterPrefs;
5961};
5962
5963template <typename DerivedT> struct CumulativeReporterBase : IStreamingReporter {
5964 template <typename T, typename ChildNodeT> struct Node {
5965 explicit Node(T const& _value) : value(_value) {}
5966 virtual ~Node() {}
5967
5968 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5969 T value;
5970 ChildNodes children;
5971 };
5972 struct SectionNode {
5973 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5974 virtual ~SectionNode() = default;
5975
5976 bool operator==(SectionNode const& other) const {
5977 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5978 }
5979 bool operator==(std::shared_ptr<SectionNode> const& other) const {
5980 return operator==(*other);
5981 }
5982
5983 SectionStats stats;
5984 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5985 using Assertions = std::vector<AssertionStats>;
5986 ChildSections childSections;
5987 Assertions assertions;
5988 std::string stdOut;
5989 std::string stdErr;
5990 };
5991
5992 struct BySectionInfo {
5993 BySectionInfo(SectionInfo const& other) : m_other(other) {}
5994 BySectionInfo(BySectionInfo const& other) : m_other(other.m_other) {}
5995 bool operator()(std::shared_ptr<SectionNode> const& node) const {
5996 return ((node->stats.sectionInfo.name == m_other.name) &&
5997 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5998 }
5999 void operator=(BySectionInfo const&) = delete;
6000
6001 private:
6002 SectionInfo const& m_other;
6003 };
6004
6005 using TestCaseNode = Node<TestCaseStats, SectionNode>;
6006 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
6007 using TestRunNode = Node<TestRunStats, TestGroupNode>;
6008
6009 CumulativeReporterBase(ReporterConfig const& _config)
6010 : m_config(_config.fullConfig()), stream(_config.stream()) {
6011 m_reporterPrefs.shouldRedirectStdOut = false;
6012 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6013 CATCH_ERROR("Verbosity level not supported by this reporter");
6014 }
6015 ~CumulativeReporterBase() override = default;
6016
6017 ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6018
6019 static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6020
6021 void testRunStarting(TestRunInfo const&) override {}
6022 void testGroupStarting(GroupInfo const&) override {}
6023
6024 void testCaseStarting(TestCaseInfo const&) override {}
6025
6026 void sectionStarting(SectionInfo const& sectionInfo) override {
6027 SectionStats incompleteStats(sectionInfo, Counts(), 0, false);
6028 std::shared_ptr<SectionNode> node;
6029 if (m_sectionStack.empty()) {
6030 if (!m_rootSection)
6031 m_rootSection = std::make_shared<SectionNode>(incompleteStats);
6032 node = m_rootSection;
6033 } else {
6034 SectionNode& parentNode = *m_sectionStack.back();
6035 auto it = std::find_if(parentNode.childSections.begin(), parentNode.childSections.end(),
6036 BySectionInfo(sectionInfo));
6037 if (it == parentNode.childSections.end()) {
6038 node = std::make_shared<SectionNode>(incompleteStats);
6039 parentNode.childSections.push_back(node);
6040 } else
6041 node = *it;
6042 }
6043 m_sectionStack.push_back(node);
6044 m_deepestSection = std::move(node);
6045 }
6046
6047 void assertionStarting(AssertionInfo const&) override {}
6048
6049 bool assertionEnded(AssertionStats const& assertionStats) override {
6050 assert(!m_sectionStack.empty());
6051 // AssertionResult holds a pointer to a temporary DecomposedExpression,
6052 // which getExpandedExpression() calls to build the expression string.
6053 // Our section stack copy of the assertionResult will likely outlive the
6054 // temporary, so it must be expanded or discarded now to avoid calling
6055 // a destroyed object later.
6056 prepareExpandedExpression(const_cast<AssertionResult&>(assertionStats.assertionResult));
6057 SectionNode& sectionNode = *m_sectionStack.back();
6058 sectionNode.assertions.push_back(assertionStats);
6059 return true;
6060 }
6061 void sectionEnded(SectionStats const& sectionStats) override {
6062 assert(!m_sectionStack.empty());
6063 SectionNode& node = *m_sectionStack.back();
6064 node.stats = sectionStats;
6065 m_sectionStack.pop_back();
6066 }
6067 void testCaseEnded(TestCaseStats const& testCaseStats) override {
6068 auto node = std::make_shared<TestCaseNode>(testCaseStats);
6069 assert(m_sectionStack.size() == 0);
6070 node->children.push_back(m_rootSection);
6071 m_testCases.push_back(node);
6072 m_rootSection.reset();
6073
6074 assert(m_deepestSection);
6075 m_deepestSection->stdOut = testCaseStats.stdOut;
6076 m_deepestSection->stdErr = testCaseStats.stdErr;
6077 }
6078 void testGroupEnded(TestGroupStats const& testGroupStats) override {
6079 auto node = std::make_shared<TestGroupNode>(testGroupStats);
6080 node->children.swap(m_testCases);
6081 m_testGroups.push_back(node);
6082 }
6083 void testRunEnded(TestRunStats const& testRunStats) override {
6084 auto node = std::make_shared<TestRunNode>(testRunStats);
6085 node->children.swap(m_testGroups);
6086 m_testRuns.push_back(node);
6087 testRunEndedCumulative();
6088 }
6089 virtual void testRunEndedCumulative() = 0;
6090
6091 void skipTest(TestCaseInfo const&) override {}
6092
6093 IConfigPtr m_config;
6094 std::ostream& stream;
6095 std::vector<AssertionStats> m_assertions;
6096 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
6097 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
6098 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
6099
6100 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
6101
6102 std::shared_ptr<SectionNode> m_rootSection;
6103 std::shared_ptr<SectionNode> m_deepestSection;
6104 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
6105 ReporterPreferences m_reporterPrefs;
6106};
6107
6108template <char C> char const* getLineOfChars() {
6109 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
6110 if (!*line) {
6111 std::memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1);
6112 line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0;
6113 }
6114 return line;
6115}
6116
6117struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
6118 TestEventListenerBase(ReporterConfig const& _config);
6119
6120 static std::set<Verbosity> getSupportedVerbosities();
6121
6122 void assertionStarting(AssertionInfo const&) override;
6123 bool assertionEnded(AssertionStats const&) override;
6124};
6125
6126} // end namespace Catch
6127
6128// end catch_reporter_bases.hpp
6129// start catch_console_colour.h
6130
6131namespace Catch {
6132
6133struct Colour {
6134 enum Code {
6135 None = 0,
6136
6137 White,
6138 Red,
6139 Green,
6140 Blue,
6141 Cyan,
6142 Yellow,
6143 Grey,
6144
6145 Bright = 0x10,
6146
6147 BrightRed = Bright | Red,
6148 BrightGreen = Bright | Green,
6149 LightGrey = Bright | Grey,
6150 BrightWhite = Bright | White,
6151 BrightYellow = Bright | Yellow,
6152
6153 // By intention
6154 FileName = LightGrey,
6155 Warning = BrightYellow,
6156 ResultError = BrightRed,
6157 ResultSuccess = BrightGreen,
6158 ResultExpectedFailure = Warning,
6159
6160 Error = BrightRed,
6161 Success = Green,
6162
6163 OriginalExpression = Cyan,
6164 ReconstructedExpression = BrightYellow,
6165
6166 SecondaryText = LightGrey,
6167 Headers = White
6168 };
6169
6170 // Use constructed object for RAII guard
6171 Colour(Code _colourCode);
6172 Colour(Colour&& other) noexcept;
6173 Colour& operator=(Colour&& other) noexcept;
6174 ~Colour();
6175
6176 // Use static method for one-shot changes
6177 static void use(Code _colourCode);
6178
6179 private:
6180 bool m_moved = false;
6181};
6182
6183std::ostream& operator<<(std::ostream& os, Colour const&);
6184
6185} // end namespace Catch
6186
6187// end catch_console_colour.h
6188// start catch_reporter_registrars.hpp
6189
6190namespace Catch {
6191
6192template <typename T> class ReporterRegistrar {
6193
6194 class ReporterFactory : public IReporterFactory {
6195
6196 IStreamingReporterPtr create(ReporterConfig const& config) const override {
6197 return std::unique_ptr<T>(new T(config));
6198 }
6199
6200 std::string getDescription() const override { return T::getDescription(); }
6201 };
6202
6203 public:
6204 explicit ReporterRegistrar(std::string const& name) {
6205 getMutableRegistryHub().registerReporter(name, std::make_shared<ReporterFactory>());
6206 }
6207};
6208
6209template <typename T> class ListenerRegistrar {
6210
6211 class ListenerFactory : public IReporterFactory {
6212
6213 IStreamingReporterPtr create(ReporterConfig const& config) const override {
6214 return std::unique_ptr<T>(new T(config));
6215 }
6216 std::string getDescription() const override { return std::string(); }
6217 };
6218
6219 public:
6220 ListenerRegistrar() {
6221 getMutableRegistryHub().registerListener(std::make_shared<ListenerFactory>());
6222 }
6223};
6224} // namespace Catch
6225
6226#if !defined(CATCH_CONFIG_DISABLE)
6227
6228#define CATCH_REGISTER_REPORTER(name, reporterType) \
6229 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6230 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6231 namespace { \
6232 Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType(name); \
6233 } \
6234 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6235
6236#define CATCH_REGISTER_LISTENER(listenerType) \
6237 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6238 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6239 namespace { \
6240 Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; \
6241 } \
6242 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6243#else // CATCH_CONFIG_DISABLE
6244
6245#define CATCH_REGISTER_REPORTER(name, reporterType)
6246#define CATCH_REGISTER_LISTENER(listenerType)
6247
6248#endif // CATCH_CONFIG_DISABLE
6249
6250// end catch_reporter_registrars.hpp
6251// Allow users to base their work off existing reporters
6252// start catch_reporter_compact.h
6253
6254namespace Catch {
6255
6256struct CompactReporter : StreamingReporterBase<CompactReporter> {
6257
6258 using StreamingReporterBase::StreamingReporterBase;
6259
6260 ~CompactReporter() override;
6261
6262 static std::string getDescription();
6263
6264 void noMatchingTestCases(std::string const& spec) override;
6265
6266 void assertionStarting(AssertionInfo const&) override;
6267
6268 bool assertionEnded(AssertionStats const& _assertionStats) override;
6269
6270 void sectionEnded(SectionStats const& _sectionStats) override;
6271
6272 void testRunEnded(TestRunStats const& _testRunStats) override;
6273};
6274
6275} // end namespace Catch
6276
6277// end catch_reporter_compact.h
6278// start catch_reporter_console.h
6279
6280#if defined(_MSC_VER)
6281#pragma warning(push)
6282#pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in
6283 // switch Note that 4062 (not all labels are
6284 // handled and default is missing) is enabled
6285#endif
6286
6287namespace Catch {
6288// Fwd decls
6289struct SummaryColumn;
6290class TablePrinter;
6291
6292struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6293 std::unique_ptr<TablePrinter> m_tablePrinter;
6294
6295 ConsoleReporter(ReporterConfig const& config);
6296 ~ConsoleReporter() override;
6297 static std::string getDescription();
6298
6299 void noMatchingTestCases(std::string const& spec) override;
6300
6301 void reportInvalidArguments(std::string const& arg) override;
6302
6303 void assertionStarting(AssertionInfo const&) override;
6304
6305 bool assertionEnded(AssertionStats const& _assertionStats) override;
6306
6307 void sectionStarting(SectionInfo const& _sectionInfo) override;
6308 void sectionEnded(SectionStats const& _sectionStats) override;
6309
6310#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6311 void benchmarkPreparing(std::string const& name) override;
6312 void benchmarkStarting(BenchmarkInfo const& info) override;
6313 void benchmarkEnded(BenchmarkStats<> const& stats) override;
6314 void benchmarkFailed(std::string const& error) override;
6315#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6316
6317 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6318 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6319 void testRunEnded(TestRunStats const& _testRunStats) override;
6320 void testRunStarting(TestRunInfo const& _testRunInfo) override;
6321
6322 private:
6323 void lazyPrint();
6324
6325 void lazyPrintWithoutClosingBenchmarkTable();
6326 void lazyPrintRunInfo();
6327 void lazyPrintGroupInfo();
6328 void printTestCaseAndSectionHeader();
6329
6330 void printClosedHeader(std::string const& _name);
6331 void printOpenHeader(std::string const& _name);
6332
6333 // if string has a : in first line will set indent to follow it on
6334 // subsequent lines
6335 void printHeaderString(std::string const& _string, std::size_t indent = 0);
6336
6337 void printTotals(Totals const& totals);
6338 void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols,
6339 std::size_t row);
6340
6341 void printTotalsDivider(Totals const& totals);
6342 void printSummaryDivider();
6343 void printTestFilters();
6344
6345 private:
6346 bool m_headerPrinted = false;
6347};
6348
6349} // end namespace Catch
6350
6351#if defined(_MSC_VER)
6352#pragma warning(pop)
6353#endif
6354
6355// end catch_reporter_console.h
6356// start catch_reporter_junit.h
6357
6358// start catch_xmlwriter.h
6359
6360#include <vector>
6361
6362namespace Catch {
6363enum class XmlFormatting {
6364 None = 0x00,
6365 Indent = 0x01,
6366 Newline = 0x02,
6367};
6368
6369XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs);
6370XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs);
6371
6372class XmlEncode {
6373 public:
6374 enum ForWhat { ForTextNodes, ForAttributes };
6375
6376 XmlEncode(std::string const& str, ForWhat forWhat = ForTextNodes);
6377
6378 void encodeTo(std::ostream& os) const;
6379
6380 friend std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode);
6381
6382 private:
6383 std::string m_str;
6384 ForWhat m_forWhat;
6385};
6386
6387class XmlWriter {
6388 public:
6389 class ScopedElement {
6390 public:
6391 ScopedElement(XmlWriter* writer, XmlFormatting fmt);
6392
6393 ScopedElement(ScopedElement&& other) noexcept;
6394 ScopedElement& operator=(ScopedElement&& other) noexcept;
6395
6396 ~ScopedElement();
6397
6398 ScopedElement& writeText(std::string const& text,
6399 XmlFormatting fmt = XmlFormatting::Newline |
6400 XmlFormatting::Indent);
6401
6402 template <typename T>
6403 ScopedElement& writeAttribute(std::string const& name, T const& attribute) {
6404 m_writer->writeAttribute(name, attribute);
6405 return *this;
6406 }
6407
6408 private:
6409 mutable XmlWriter* m_writer = nullptr;
6410 XmlFormatting m_fmt;
6411 };
6412
6413 XmlWriter(std::ostream& os = Catch::cout());
6414 ~XmlWriter();
6415
6416 XmlWriter(XmlWriter const&) = delete;
6417 XmlWriter& operator=(XmlWriter const&) = delete;
6418
6419 XmlWriter& startElement(std::string const& name,
6420 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6421
6422 ScopedElement scopedElement(std::string const& name,
6423 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6424
6425 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6426
6427 XmlWriter& writeAttribute(std::string const& name, std::string const& attribute);
6428
6429 XmlWriter& writeAttribute(std::string const& name, bool attribute);
6430
6431 template <typename T> XmlWriter& writeAttribute(std::string const& name, T const& attribute) {
6432 ReusableStringStream rss;
6433 rss << attribute;
6434 return writeAttribute(name, rss.str());
6435 }
6436
6437 XmlWriter& writeText(std::string const& text,
6438 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6439
6440 XmlWriter& writeComment(std::string const& text,
6441 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6442
6443 void writeStylesheetRef(std::string const& url);
6444
6445 XmlWriter& writeBlankLine();
6446
6447 void ensureTagClosed();
6448
6449 private:
6450 void applyFormatting(XmlFormatting fmt);
6451
6452 void writeDeclaration();
6453
6454 void newlineIfNecessary();
6455
6456 bool m_tagIsOpen = false;
6457 bool m_needsNewline = false;
6458 std::vector<std::string> m_tags;
6459 std::string m_indent;
6460 std::ostream& m_os;
6461};
6462
6463} // namespace Catch
6464
6465// end catch_xmlwriter.h
6466namespace Catch {
6467
6468class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6469 public:
6470 JunitReporter(ReporterConfig const& _config);
6471
6472 ~JunitReporter() override;
6473
6474 static std::string getDescription();
6475
6476 void noMatchingTestCases(std::string const& /*spec*/) override;
6477
6478 void testRunStarting(TestRunInfo const& runInfo) override;
6479
6480 void testGroupStarting(GroupInfo const& groupInfo) override;
6481
6482 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6483 bool assertionEnded(AssertionStats const& assertionStats) override;
6484
6485 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6486
6487 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6488
6489 void testRunEndedCumulative() override;
6490
6491 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6492
6493 void writeTestCase(TestCaseNode const& testCaseNode);
6494
6495 void writeSection(std::string const& className, std::string const& rootName,
6496 SectionNode const& sectionNode, bool testOkToFail);
6497
6498 void writeAssertions(SectionNode const& sectionNode);
6499 void writeAssertion(AssertionStats const& stats);
6500
6501 XmlWriter xml;
6502 Timer suiteTimer;
6503 std::string stdOutForSuite;
6504 std::string stdErrForSuite;
6505 unsigned int unexpectedExceptions = 0;
6506 bool m_okToFail = false;
6507};
6508
6509} // end namespace Catch
6510
6511// end catch_reporter_junit.h
6512// start catch_reporter_xml.h
6513
6514namespace Catch {
6515class XmlReporter : public StreamingReporterBase<XmlReporter> {
6516 public:
6517 XmlReporter(ReporterConfig const& _config);
6518
6519 ~XmlReporter() override;
6520
6521 static std::string getDescription();
6522
6523 virtual std::string getStylesheetRef() const;
6524
6525 void writeSourceInfo(SourceLineInfo const& sourceInfo);
6526
6527 public: // StreamingReporterBase
6528 void noMatchingTestCases(std::string const& s) override;
6529
6530 void testRunStarting(TestRunInfo const& testInfo) override;
6531
6532 void testGroupStarting(GroupInfo const& groupInfo) override;
6533
6534 void testCaseStarting(TestCaseInfo const& testInfo) override;
6535
6536 void sectionStarting(SectionInfo const& sectionInfo) override;
6537
6538 void assertionStarting(AssertionInfo const&) override;
6539
6540 bool assertionEnded(AssertionStats const& assertionStats) override;
6541
6542 void sectionEnded(SectionStats const& sectionStats) override;
6543
6544 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6545
6546 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6547
6548 void testRunEnded(TestRunStats const& testRunStats) override;
6549
6550#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6551 void benchmarkPreparing(std::string const& name) override;
6552 void benchmarkStarting(BenchmarkInfo const&) override;
6553 void benchmarkEnded(BenchmarkStats<> const&) override;
6554 void benchmarkFailed(std::string const&) override;
6555#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6556
6557 private:
6558 Timer m_testCaseTimer;
6559 XmlWriter m_xml;
6560 int m_sectionDepth = 0;
6561};
6562
6563} // end namespace Catch
6564
6565// end catch_reporter_xml.h
6566
6567// end catch_external_interfaces.h
6568#endif
6569
6570#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6571// start catch_benchmarking_all.hpp
6572
6573// A proxy header that includes all of the benchmarking headers to allow
6574// concise include of the benchmarking features. You should prefer the
6575// individual includes in standard use.
6576
6577// start catch_benchmark.hpp
6578
6579// Benchmark
6580
6581// start catch_chronometer.hpp
6582
6583// User-facing chronometer
6584
6585// start catch_clock.hpp
6586
6587// Clocks
6588
6589#include <chrono>
6590#include <ratio>
6591
6592namespace Catch {
6593namespace Benchmark {
6594template <typename Clock> using ClockDuration = typename Clock::duration;
6595template <typename Clock>
6596using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6597
6598template <typename Clock> using TimePoint = typename Clock::time_point;
6599
6600using default_clock = std::chrono::steady_clock;
6601
6602template <typename Clock> struct now {
6603 TimePoint<Clock> operator()() const { return Clock::now(); }
6604};
6605
6606using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6607} // namespace Benchmark
6608} // namespace Catch
6609
6610// end catch_clock.hpp
6611// start catch_optimizer.hpp
6612
6613// Hinting the optimizer
6614
6615#if defined(_MSC_VER)
6616#include <atomic> // atomic_thread_fence
6617#endif
6618
6619namespace Catch {
6620namespace Benchmark {
6621#if defined(__GNUC__) || defined(__clang__)
6622template <typename T> inline void keep_memory(T* p) {
6623 asm volatile("" : : "g"(p) : "memory");
6624}
6625inline void keep_memory() {
6626 asm volatile("" : : : "memory");
6627}
6628
6629namespace Detail {
6630inline void optimizer_barrier() {
6631 keep_memory();
6632}
6633} // namespace Detail
6634#elif defined(_MSC_VER)
6635
6636#pragma optimize("", off)
6637template <typename T> inline void keep_memory(T* p) {
6638 // thanks @milleniumbug
6639 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6640}
6641// TODO equivalent keep_memory()
6642#pragma optimize("", on)
6643
6644namespace Detail {
6645inline void optimizer_barrier() {
6646 std::atomic_thread_fence(std::memory_order_seq_cst);
6647}
6648} // namespace Detail
6649
6650#endif
6651
6652template <typename T> inline void deoptimize_value(T&& x) {
6653 keep_memory(&x);
6654}
6655
6656template <typename Fn, typename... Args>
6657inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6658 typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6659 deoptimize_value(std::forward<Fn>(fn)(std::forward<Args...>(args...)));
6660}
6661
6662template <typename Fn, typename... Args>
6663inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6664 typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6665 std::forward<Fn>(fn)(std::forward<Args...>(args...));
6666}
6667} // namespace Benchmark
6668} // namespace Catch
6669
6670// end catch_optimizer.hpp
6671// start catch_complete_invoke.hpp
6672
6673// Invoke with a special case for void
6674
6675#include <type_traits>
6676#include <utility>
6677
6678namespace Catch {
6679namespace Benchmark {
6680namespace Detail {
6681template <typename T> struct CompleteType {
6682 using type = T;
6683};
6684template <> struct CompleteType<void> {
6685 struct type {};
6686};
6687
6688template <typename T> using CompleteType_t = typename CompleteType<T>::type;
6689
6690template <typename Result> struct CompleteInvoker {
6691 template <typename Fun, typename... Args> static Result invoke(Fun&& fun, Args&&... args) {
6692 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6693 }
6694};
6695template <> struct CompleteInvoker<void> {
6696 template <typename Fun, typename... Args>
6697 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6698 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6699 return {};
6700 }
6701};
6702
6703// invoke and not return void :(
6704template <typename Fun, typename... Args>
6705CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6706 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun),
6707 std::forward<Args>(args)...);
6708}
6709
6710const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6711} // namespace Detail
6712
6713template <typename Fun> Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6714 CATCH_TRY {
6715 return Detail::complete_invoke(std::forward<Fun>(fun));
6716 }
6717 CATCH_CATCH_ALL {
6718 getResultCapture().benchmarkFailed(translateActiveException());
6719 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6720 }
6721}
6722} // namespace Benchmark
6723} // namespace Catch
6724
6725// end catch_complete_invoke.hpp
6726namespace Catch {
6727namespace Benchmark {
6728namespace Detail {
6729struct ChronometerConcept {
6730 virtual void start() = 0;
6731 virtual void finish() = 0;
6732 virtual ~ChronometerConcept() = default;
6733};
6734template <typename Clock> struct ChronometerModel final : public ChronometerConcept {
6735 void start() override { started = Clock::now(); }
6736 void finish() override { finished = Clock::now(); }
6737
6738 ClockDuration<Clock> elapsed() const { return finished - started; }
6739
6740 TimePoint<Clock> started;
6741 TimePoint<Clock> finished;
6742};
6743} // namespace Detail
6744
6745struct Chronometer {
6746 public:
6747 template <typename Fun> void measure(Fun&& fun) {
6748 measure(std::forward<Fun>(fun), is_callable<Fun(int)>());
6749 }
6750
6751 int runs() const { return k; }
6752
6753 Chronometer(Detail::ChronometerConcept& meter, int k) : impl(&meter), k(k) {}
6754
6755 private:
6756 template <typename Fun> void measure(Fun&& fun, std::false_type) {
6757 measure([&fun](int) { return fun(); }, std::true_type());
6758 }
6759
6760 template <typename Fun> void measure(Fun&& fun, std::true_type) {
6761 Detail::optimizer_barrier();
6762 impl->start();
6763 for (int i = 0; i < k; ++i)
6764 invoke_deoptimized(fun, i);
6765 impl->finish();
6766 Detail::optimizer_barrier();
6767 }
6768
6769 Detail::ChronometerConcept* impl;
6770 int k;
6771};
6772} // namespace Benchmark
6773} // namespace Catch
6774
6775// end catch_chronometer.hpp
6776// start catch_environment.hpp
6777
6778// Environment information
6779
6780namespace Catch {
6781namespace Benchmark {
6782template <typename Duration> struct EnvironmentEstimate {
6783 Duration mean;
6784 OutlierClassification outliers;
6785
6786 template <typename Duration2> operator EnvironmentEstimate<Duration2>() const {
6787 return {mean, outliers};
6788 }
6789};
6790template <typename Clock> struct Environment {
6791 using clock_type = Clock;
6792 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6793 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6794};
6795} // namespace Benchmark
6796} // namespace Catch
6797
6798// end catch_environment.hpp
6799// start catch_execution_plan.hpp
6800
6801// Execution plan
6802
6803// start catch_benchmark_function.hpp
6804
6805// Dumb std::function implementation for consistent call overhead
6806
6807#include <cassert>
6808#include <memory>
6809#include <type_traits>
6810#include <utility>
6811
6812namespace Catch {
6813namespace Benchmark {
6814namespace Detail {
6815template <typename T> using Decay = typename std::decay<T>::type;
6816template <typename T, typename U> struct is_related : std::is_same<Decay<T>, Decay<U>> {};
6817
6825struct BenchmarkFunction {
6826 private:
6827 struct callable {
6828 virtual void call(Chronometer meter) const = 0;
6829 virtual callable* clone() const = 0;
6830 virtual ~callable() = default;
6831 };
6832 template <typename Fun> struct model : public callable {
6833 model(Fun&& fun) : fun(std::move(fun)) {}
6834 model(Fun const& fun) : fun(fun) {}
6835
6836 model<Fun>* clone() const override { return new model<Fun>(*this); }
6837
6838 void call(Chronometer meter) const override {
6839 call(meter, is_callable<Fun(Chronometer)>());
6840 }
6841 void call(Chronometer meter, std::true_type) const { fun(meter); }
6842 void call(Chronometer meter, std::false_type) const { meter.measure(fun); }
6843
6844 Fun fun;
6845 };
6846
6847 struct do_nothing {
6848 void operator()() const {}
6849 };
6850
6851 template <typename T> BenchmarkFunction(model<T>* c) : f(c) {}
6852
6853 public:
6854 BenchmarkFunction() : f(new model<do_nothing>{{}}) {}
6855
6856 template <typename Fun,
6857 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
6858 BenchmarkFunction(Fun&& fun)
6859 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6860
6861 BenchmarkFunction(BenchmarkFunction&& that) : f(std::move(that.f)) {}
6862
6863 BenchmarkFunction(BenchmarkFunction const& that) : f(that.f->clone()) {}
6864
6865 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6866 f = std::move(that.f);
6867 return *this;
6868 }
6869
6870 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6871 f.reset(that.f->clone());
6872 return *this;
6873 }
6874
6875 void operator()(Chronometer meter) const { f->call(meter); }
6876
6877 private:
6878 std::unique_ptr<callable> f;
6879};
6880} // namespace Detail
6881} // namespace Benchmark
6882} // namespace Catch
6883
6884// end catch_benchmark_function.hpp
6885// start catch_repeat.hpp
6886
6887// repeat algorithm
6888
6889#include <type_traits>
6890#include <utility>
6891
6892namespace Catch {
6893namespace Benchmark {
6894namespace Detail {
6895template <typename Fun> struct repeater {
6896 void operator()(int k) const {
6897 for (int i = 0; i < k; ++i) {
6898 fun();
6899 }
6900 }
6901 Fun fun;
6902};
6903template <typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6904 return {std::forward<Fun>(fun)};
6905}
6906} // namespace Detail
6907} // namespace Benchmark
6908} // namespace Catch
6909
6910// end catch_repeat.hpp
6911// start catch_run_for_at_least.hpp
6912
6913// Run a function for a minimum amount of time
6914
6915// start catch_measure.hpp
6916
6917// Measure
6918
6919// start catch_timing.hpp
6920
6921// Timing
6922
6923#include <tuple>
6924#include <type_traits>
6925
6926namespace Catch {
6927namespace Benchmark {
6928template <typename Duration, typename Result> struct Timing {
6929 Duration elapsed;
6930 Result result;
6931 int iterations;
6932};
6933template <typename Clock, typename Func, typename... Args>
6934using TimingOf =
6935 Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6936} // namespace Benchmark
6937} // namespace Catch
6938
6939// end catch_timing.hpp
6940#include <utility>
6941
6942namespace Catch {
6943namespace Benchmark {
6944namespace Detail {
6945template <typename Clock, typename Fun, typename... Args>
6946TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6947 auto start = Clock::now();
6948 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6949 auto end = Clock::now();
6950 auto delta = end - start;
6951 return {delta, std::forward<decltype(r)>(r), 1};
6952}
6953} // namespace Detail
6954} // namespace Benchmark
6955} // namespace Catch
6956
6957// end catch_measure.hpp
6958#include <type_traits>
6959#include <utility>
6960
6961namespace Catch {
6962namespace Benchmark {
6963namespace Detail {
6964template <typename Clock, typename Fun>
6965TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
6966 return Detail::measure<Clock>(fun, iters);
6967}
6968template <typename Clock, typename Fun>
6969TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
6970 Detail::ChronometerModel<Clock> meter;
6971 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6972
6973 return {meter.elapsed(), std::move(result), iters};
6974}
6975
6976template <typename Clock, typename Fun>
6977using run_for_at_least_argument_t =
6978 typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6979
6980struct optimized_away_error : std::exception {
6981 const char* what() const noexcept override {
6982 return "could not measure benchmark, maybe it was optimized away";
6983 }
6984};
6985
6986template <typename Clock, typename Fun>
6987TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>>
6988run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6989 auto iters = seed;
6990 while (iters < (1 << 30)) {
6991 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6992
6993 if (Timing.elapsed >= how_long) {
6994 return {Timing.elapsed, std::move(Timing.result), iters};
6995 }
6996 iters *= 2;
6997 }
6998 Catch::throw_exception(optimized_away_error{});
6999}
7000} // namespace Detail
7001} // namespace Benchmark
7002} // namespace Catch
7003
7004// end catch_run_for_at_least.hpp
7005#include <algorithm>
7006#include <iterator>
7007
7008namespace Catch {
7009namespace Benchmark {
7010template <typename Duration> struct ExecutionPlan {
7011 int iterations_per_sample;
7012 Duration estimated_duration;
7013 Detail::BenchmarkFunction benchmark;
7014 Duration warmup_time;
7015 int warmup_iterations;
7016
7017 template <typename Duration2> operator ExecutionPlan<Duration2>() const {
7018 return {iterations_per_sample, estimated_duration, benchmark, warmup_time,
7019 warmup_iterations};
7020 }
7021
7022 template <typename Clock>
7023 std::vector<FloatDuration<Clock>> run(const IConfig& cfg,
7024 Environment<FloatDuration<Clock>> env) const {
7025 // warmup a bit
7026 Detail::run_for_at_least<Clock>(
7027 std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
7028 Detail::repeat(now<Clock>{}));
7029
7030 std::vector<FloatDuration<Clock>> times;
7031 times.reserve(cfg.benchmarkSamples());
7032 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
7033 Detail::ChronometerModel<Clock> model;
7034 this->benchmark(Chronometer(model, iterations_per_sample));
7035 auto sample_time = model.elapsed() - env.clock_cost.mean;
7036 if (sample_time < FloatDuration<Clock>::zero())
7037 sample_time = FloatDuration<Clock>::zero();
7038 return sample_time / iterations_per_sample;
7039 });
7040 return times;
7041 }
7042};
7043} // namespace Benchmark
7044} // namespace Catch
7045
7046// end catch_execution_plan.hpp
7047// start catch_estimate_clock.hpp
7048
7049// Environment measurement
7050
7051// start catch_stats.hpp
7052
7053// Statistical analysis tools
7054
7055#include <algorithm>
7056#include <cmath>
7057#include <cstddef>
7058#include <functional>
7059#include <iterator>
7060#include <numeric>
7061#include <random>
7062#include <tuple>
7063#include <utility>
7064#include <vector>
7065
7066namespace Catch {
7067namespace Benchmark {
7068namespace Detail {
7069using sample = std::vector<double>;
7070
7071double weighted_average_quantile(int k, int q, std::vector<double>::iterator first,
7072 std::vector<double>::iterator last);
7073
7074template <typename Iterator>
7075OutlierClassification classify_outliers(Iterator first, Iterator last) {
7076 std::vector<double> copy(first, last);
7077
7078 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
7079 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
7080 auto iqr = q3 - q1;
7081 auto los = q1 - (iqr * 3.);
7082 auto lom = q1 - (iqr * 1.5);
7083 auto him = q3 + (iqr * 1.5);
7084 auto his = q3 + (iqr * 3.);
7085
7086 OutlierClassification o;
7087 for (; first != last; ++first) {
7088 auto&& t = *first;
7089 if (t < los)
7090 ++o.low_severe;
7091 else if (t < lom)
7092 ++o.low_mild;
7093 else if (t > his)
7094 ++o.high_severe;
7095 else if (t > him)
7096 ++o.high_mild;
7097 ++o.samples_seen;
7098 }
7099 return o;
7100}
7101
7102template <typename Iterator> double mean(Iterator first, Iterator last) {
7103 auto count = last - first;
7104 double sum = std::accumulate(first, last, 0.);
7105 return sum / count;
7106}
7107
7108template <typename URng, typename Iterator, typename Estimator>
7109sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
7110 auto n = last - first;
7111 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7112
7113 sample out;
7114 out.reserve(resamples);
7115 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7116 std::vector<double> resampled;
7117 resampled.reserve(n);
7118 std::generate_n(std::back_inserter(resampled), n,
7119 [first, &dist, &rng] { return first[dist(rng)]; });
7120 return estimator(resampled.begin(), resampled.end());
7121 });
7122 std::sort(out.begin(), out.end());
7123 return out;
7124}
7125
7126template <typename Estimator, typename Iterator>
7127sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7128 auto n = last - first;
7129 auto second = std::next(first);
7130 sample results;
7131 results.reserve(n);
7132
7133 for (auto it = first; it != last; ++it) {
7134 std::iter_swap(it, first);
7135 results.push_back(estimator(second, last));
7136 }
7137
7138 return results;
7139}
7140
7141inline double normal_cdf(double x) {
7142 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7143}
7144
7145double erfc_inv(double x);
7146
7147double normal_quantile(double p);
7148
7149template <typename Iterator, typename Estimator>
7150Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last,
7151 sample const& resample, Estimator&& estimator) {
7152 auto n_samples = last - first;
7153
7154 double point = estimator(first, last);
7155 // Degenerate case with a single sample
7156 if (n_samples == 1)
7157 return {point, point, point, confidence_level};
7158
7159 sample jack = jackknife(estimator, first, last);
7160 double jack_mean = mean(jack.begin(), jack.end());
7161 double sum_squares, sum_cubes;
7162 std::tie(sum_squares, sum_cubes) = std::accumulate(
7163 jack.begin(), jack.end(), std::make_pair(0., 0.),
7164 [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
7165 auto d = jack_mean - x;
7166 auto d2 = d * d;
7167 auto d3 = d2 * d;
7168 return {sqcb.first + d2, sqcb.second + d3};
7169 });
7170
7171 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7172 int n = static_cast<int>(resample.size());
7173 double prob_n =
7174 std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) /
7175 (double)n;
7176 // degenerate case with uniform samples
7177 if (prob_n == 0)
7178 return {point, point, point, confidence_level};
7179
7180 double bias = normal_quantile(prob_n);
7181 double z1 = normal_quantile((1. - confidence_level) / 2.);
7182
7183 auto cumn = [n](double x) -> int { return std::lround(normal_cdf(x) * n); };
7184 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7185 double b1 = bias + z1;
7186 double b2 = bias - z1;
7187 double a1 = a(b1);
7188 double a2 = a(b2);
7189 auto lo = (std::max)(cumn(a1), 0);
7190 auto hi = (std::min)(cumn(a2), n - 1);
7191
7192 return {point, resample[lo], resample[hi], confidence_level};
7193}
7194
7195double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7196
7197struct bootstrap_analysis {
7198 Estimate<double> mean;
7199 Estimate<double> standard_deviation;
7200 double outlier_variance;
7201};
7202
7203bootstrap_analysis analyse_samples(double confidence_level, int n_resamples,
7204 std::vector<double>::iterator first,
7205 std::vector<double>::iterator last);
7206} // namespace Detail
7207} // namespace Benchmark
7208} // namespace Catch
7209
7210// end catch_stats.hpp
7211#include <algorithm>
7212#include <cmath>
7213#include <iterator>
7214#include <tuple>
7215#include <vector>
7216
7217namespace Catch {
7218namespace Benchmark {
7219namespace Detail {
7220template <typename Clock> std::vector<double> resolution(int k) {
7221 std::vector<TimePoint<Clock>> times;
7222 times.reserve(k + 1);
7223 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7224
7225 std::vector<double> deltas;
7226 deltas.reserve(k);
7227 std::transform(std::next(times.begin()), times.end(), times.begin(), std::back_inserter(deltas),
7228 [](TimePoint<Clock> a, TimePoint<Clock> b) {
7229 return static_cast<double>((a - b).count());
7230 });
7231
7232 return deltas;
7233}
7234
7235const auto warmup_iterations = 10000;
7236const auto warmup_time = std::chrono::milliseconds(100);
7237const auto minimum_ticks = 1000;
7238const auto warmup_seed = 10000;
7239const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7240const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7241const auto clock_cost_estimation_tick_limit = 100000;
7242const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7243const auto clock_cost_estimation_iterations = 10000;
7244
7245template <typename Clock> int warmup() {
7246 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time),
7247 warmup_seed, &resolution<Clock>)
7248 .iterations;
7249}
7250template <typename Clock>
7251EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7252 auto r = run_for_at_least<Clock>(
7253 std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time),
7254 iterations, &resolution<Clock>)
7255 .result;
7256 return {
7257 FloatDuration<Clock>(mean(r.begin(), r.end())),
7258 classify_outliers(r.begin(), r.end()),
7259 };
7260}
7261template <typename Clock>
7262EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7263 auto time_limit = (std::min)(resolution * clock_cost_estimation_tick_limit,
7264 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7265 auto time_clock = [](int k) {
7266 return Detail::measure<Clock>([k] {
7267 for (int i = 0; i < k; ++i) {
7268 volatile auto ignored = Clock::now();
7269 (void)ignored;
7270 }
7271 })
7272 .elapsed;
7273 };
7274 time_clock(1);
7275 int iters = clock_cost_estimation_iterations;
7276 auto&& r = run_for_at_least<Clock>(
7277 std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters,
7278 time_clock);
7279 std::vector<double> times;
7280 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7281 times.reserve(nsamples);
7282 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7283 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7284 });
7285 return {
7286 FloatDuration<Clock>(mean(times.begin(), times.end())),
7287 classify_outliers(times.begin(), times.end()),
7288 };
7289}
7290
7291template <typename Clock> Environment<FloatDuration<Clock>> measure_environment() {
7292 static Environment<FloatDuration<Clock>>* env = nullptr;
7293 if (env) {
7294 return *env;
7295 }
7296
7297 auto iters = Detail::warmup<Clock>();
7298 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7299 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7300
7301 env = new Environment<FloatDuration<Clock>>{resolution, cost};
7302 return *env;
7303}
7304} // namespace Detail
7305} // namespace Benchmark
7306} // namespace Catch
7307
7308// end catch_estimate_clock.hpp
7309// start catch_analyse.hpp
7310
7311// Run and analyse one benchmark
7312
7313// start catch_sample_analysis.hpp
7314
7315// Benchmark results
7316
7317#include <algorithm>
7318#include <iterator>
7319#include <string>
7320#include <vector>
7321
7322namespace Catch {
7323namespace Benchmark {
7324template <typename Duration> struct SampleAnalysis {
7325 std::vector<Duration> samples;
7326 Estimate<Duration> mean;
7327 Estimate<Duration> standard_deviation;
7328 OutlierClassification outliers;
7329 double outlier_variance;
7330
7331 template <typename Duration2> operator SampleAnalysis<Duration2>() const {
7332 std::vector<Duration2> samples2;
7333 samples2.reserve(samples.size());
7334 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
7335 [](Duration d) { return Duration2(d); });
7336 return {
7337 std::move(samples2), mean, standard_deviation, outliers, outlier_variance,
7338 };
7339 }
7340};
7341} // namespace Benchmark
7342} // namespace Catch
7343
7344// end catch_sample_analysis.hpp
7345#include <algorithm>
7346#include <iterator>
7347#include <vector>
7348
7349namespace Catch {
7350namespace Benchmark {
7351namespace Detail {
7352template <typename Duration, typename Iterator>
7353SampleAnalysis<Duration> analyse(const IConfig& cfg, Environment<Duration>, Iterator first,
7354 Iterator last) {
7355 if (!cfg.benchmarkNoAnalysis()) {
7356 std::vector<double> samples;
7357 samples.reserve(last - first);
7358 std::transform(first, last, std::back_inserter(samples),
7359 [](Duration d) { return d.count(); });
7360
7361 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(),
7362 cfg.benchmarkResamples(),
7363 samples.begin(), samples.end());
7364 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7365
7366 auto wrap_estimate = [](Estimate<double> e) {
7367 return Estimate<Duration>{
7368 Duration(e.point),
7369 Duration(e.lower_bound),
7370 Duration(e.upper_bound),
7371 e.confidence_interval,
7372 };
7373 };
7374 std::vector<Duration> samples2;
7375 samples2.reserve(samples.size());
7376 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
7377 [](double d) { return Duration(d); });
7378 return {
7379 std::move(samples2),
7380 wrap_estimate(analysis.mean),
7381 wrap_estimate(analysis.standard_deviation),
7382 outliers,
7383 analysis.outlier_variance,
7384 };
7385 } else {
7386 std::vector<Duration> samples;
7387 samples.reserve(last - first);
7388
7389 Duration mean = Duration(0);
7390 int i = 0;
7391 for (auto it = first; it < last; ++it, ++i) {
7392 samples.push_back(Duration(*it));
7393 mean += Duration(*it);
7394 }
7395 mean /= i;
7396
7397 return {std::move(samples), Estimate<Duration>{mean, mean, mean, 0.0},
7398 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7399 OutlierClassification{}, 0.0};
7400 }
7401}
7402} // namespace Detail
7403} // namespace Benchmark
7404} // namespace Catch
7405
7406// end catch_analyse.hpp
7407#include <algorithm>
7408#include <cmath>
7409#include <functional>
7410#include <string>
7411#include <vector>
7412
7413namespace Catch {
7414namespace Benchmark {
7415struct Benchmark {
7416 Benchmark(std::string&& name) : name(std::move(name)) {}
7417
7418 template <class FUN>
7419 Benchmark(std::string&& name, FUN&& func) : fun(std::move(func)), name(std::move(name)) {}
7420
7421 template <typename Clock>
7422 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig& cfg,
7423 Environment<FloatDuration<Clock>> env) const {
7424 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7425 auto run_time = std::max(
7426 min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7427 auto&& test = Detail::run_for_at_least<Clock>(
7428 std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7429 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7430 return {new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun,
7431 std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()),
7432 Detail::warmup_iterations};
7433 }
7434
7435 template <typename Clock = default_clock> void run() {
7436 IConfigPtr cfg = getCurrentContext().getConfig();
7437
7438 auto env = Detail::measure_environment<Clock>();
7439
7440 getResultCapture().benchmarkPreparing(name);
7441 CATCH_TRY {
7442 auto plan = user_code([&] { return prepare<Clock>(*cfg, env); });
7443
7444 BenchmarkInfo info{name,
7445 plan.estimated_duration.count(),
7446 plan.iterations_per_sample,
7447 cfg->benchmarkSamples(),
7448 cfg->benchmarkResamples(),
7449 env.clock_resolution.mean.count(),
7450 env.clock_cost.mean.count()};
7451
7452 getResultCapture().benchmarkStarting(info);
7453
7454 auto samples = user_code([&] { return plan.template run<Clock>(*cfg, env); });
7455
7456 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7457 BenchmarkStats<FloatDuration<Clock>> stats{info,
7458 analysis.samples,
7459 analysis.mean,
7460 analysis.standard_deviation,
7461 analysis.outliers,
7462 analysis.outlier_variance};
7463 getResultCapture().benchmarkEnded(stats);
7464 }
7465 CATCH_CATCH_ALL {
7466 if (translateActiveException() !=
7467 Detail::benchmarkErrorMsg) // benchmark errors have been reported,
7468 // otherwise rethrow.
7469 std::rethrow_exception(std::current_exception());
7470 }
7471 }
7472
7473 // sets lambda to be used in fun *and* executes benchmark!
7474 template <typename Fun,
7475 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
7476 Benchmark& operator=(Fun func) {
7477 fun = Detail::BenchmarkFunction(func);
7478 run();
7479 return *this;
7480 }
7481
7482 explicit operator bool() { return true; }
7483
7484 private:
7485 Detail::BenchmarkFunction fun;
7486 std::string name;
7487};
7488} // namespace Benchmark
7489} // namespace Catch
7490
7491#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7492#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7493
7494#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex) \
7495 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
7496 BenchmarkName = [&](int benchmarkIndex)
7497
7498#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name) \
7499 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
7500 BenchmarkName = [&]
7501
7502// end catch_benchmark.hpp
7503// start catch_constructor.hpp
7504
7505// Constructor and destructor helpers
7506
7507#include <type_traits>
7508
7509namespace Catch {
7510namespace Benchmark {
7511namespace Detail {
7512template <typename T, bool Destruct> struct ObjectStorage {
7513 using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7514
7515 ObjectStorage() : data() {}
7516
7517 ObjectStorage(const ObjectStorage& other) { new (&data) T(other.stored_object()); }
7518
7519 ObjectStorage(ObjectStorage&& other) { new (&data) T(std::move(other.stored_object())); }
7520
7521 ~ObjectStorage() { destruct_on_exit<T>(); }
7522
7523 template <typename... Args> void construct(Args&&... args) {
7524 new (&data) T(std::forward<Args>(args)...);
7525 }
7526
7527 template <bool AllowManualDestruction = !Destruct>
7528 typename std::enable_if<AllowManualDestruction>::type destruct() {
7529 stored_object().~T();
7530 }
7531
7532 private:
7533 // If this is a constructor benchmark, destruct the underlying object
7534 template <typename U> void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) {
7535 destruct<true>();
7536 }
7537 // Otherwise, don't
7538 template <typename U> void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) {}
7539
7540 T& stored_object() { return *static_cast<T*>(static_cast<void*>(&data)); }
7541
7542 T const& stored_object() const { return *static_cast<T*>(static_cast<void*>(&data)); }
7543
7544 TStorage data;
7545};
7546} // namespace Detail
7547
7548template <typename T> using storage_for = Detail::ObjectStorage<T, true>;
7549
7550template <typename T> using destructable_object = Detail::ObjectStorage<T, false>;
7551} // namespace Benchmark
7552} // namespace Catch
7553
7554// end catch_constructor.hpp
7555// end catch_benchmarking_all.hpp
7556#endif
7557
7558#endif // ! CATCH_CONFIG_IMPL_ONLY
7559
7560#ifdef CATCH_IMPL
7561// start catch_impl.hpp
7562
7563#ifdef __clang__
7564#pragma clang diagnostic push
7565#pragma clang diagnostic ignored "-Wweak-vtables"
7566#endif
7567
7568// Keep these here for external reporters
7569// start catch_test_case_tracker.h
7570
7571#include <memory>
7572#include <string>
7573#include <vector>
7574
7575namespace Catch {
7576namespace TestCaseTracking {
7577
7578struct NameAndLocation {
7579 std::string name;
7580 SourceLineInfo location;
7581
7582 NameAndLocation(std::string const& _name, SourceLineInfo const& _location);
7583 friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7584 return lhs.name == rhs.name && lhs.location == rhs.location;
7585 }
7586};
7587
7588class ITracker;
7589
7590using ITrackerPtr = std::shared_ptr<ITracker>;
7591
7592class ITracker {
7593 NameAndLocation m_nameAndLocation;
7594
7595 public:
7596 ITracker(NameAndLocation const& nameAndLoc) : m_nameAndLocation(nameAndLoc) {}
7597
7598 // static queries
7599 NameAndLocation const& nameAndLocation() const { return m_nameAndLocation; }
7600
7601 virtual ~ITracker();
7602
7603 // dynamic queries
7604 virtual bool isComplete() const = 0; // Successfully completed or failed
7605 virtual bool isSuccessfullyCompleted() const = 0;
7606 virtual bool isOpen() const = 0; // Started but not complete
7607 virtual bool hasChildren() const = 0;
7608 virtual bool hasStarted() const = 0;
7609
7610 virtual ITracker& parent() = 0;
7611
7612 // actions
7613 virtual void close() = 0; // Successfully complete
7614 virtual void fail() = 0;
7615 virtual void markAsNeedingAnotherRun() = 0;
7616
7617 virtual void addChild(ITrackerPtr const& child) = 0;
7618 virtual ITrackerPtr findChild(NameAndLocation const& nameAndLocation) = 0;
7619 virtual void openChild() = 0;
7620
7621 // Debug/ checking
7622 virtual bool isSectionTracker() const = 0;
7623 virtual bool isGeneratorTracker() const = 0;
7624};
7625
7626class TrackerContext {
7627
7628 enum RunState { NotStarted, Executing, CompletedCycle };
7629
7630 ITrackerPtr m_rootTracker;
7631 ITracker* m_currentTracker = nullptr;
7632 RunState m_runState = NotStarted;
7633
7634 public:
7635 ITracker& startRun();
7636 void endRun();
7637
7638 void startCycle();
7639 void completeCycle();
7640
7641 bool completedCycle() const;
7642 ITracker& currentTracker();
7643 void setCurrentTracker(ITracker* tracker);
7644};
7645
7646class TrackerBase : public ITracker {
7647 protected:
7648 enum CycleState {
7649 NotStarted,
7650 Executing,
7651 ExecutingChildren,
7652 NeedsAnotherRun,
7653 CompletedSuccessfully,
7654 Failed
7655 };
7656
7657 using Children = std::vector<ITrackerPtr>;
7658 TrackerContext& m_ctx;
7659 ITracker* m_parent;
7660 Children m_children;
7661 CycleState m_runState = NotStarted;
7662
7663 public:
7664 TrackerBase(NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent);
7665
7666 bool isComplete() const override;
7667 bool isSuccessfullyCompleted() const override;
7668 bool isOpen() const override;
7669 bool hasChildren() const override;
7670 bool hasStarted() const override { return m_runState != NotStarted; }
7671
7672 void addChild(ITrackerPtr const& child) override;
7673
7674 ITrackerPtr findChild(NameAndLocation const& nameAndLocation) override;
7675 ITracker& parent() override;
7676
7677 void openChild() override;
7678
7679 bool isSectionTracker() const override;
7680 bool isGeneratorTracker() const override;
7681
7682 void open();
7683
7684 void close() override;
7685 void fail() override;
7686 void markAsNeedingAnotherRun() override;
7687
7688 private:
7689 void moveToParent();
7690 void moveToThis();
7691};
7692
7693class SectionTracker : public TrackerBase {
7694 std::vector<std::string> m_filters;
7695 std::string m_trimmed_name;
7696
7697 public:
7698 SectionTracker(NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent);
7699
7700 bool isSectionTracker() const override;
7701
7702 bool isComplete() const override;
7703
7704 static SectionTracker& acquire(TrackerContext& ctx, NameAndLocation const& nameAndLocation);
7705
7706 void tryOpen();
7707
7708 void addInitialFilters(std::vector<std::string> const& filters);
7709 void addNextFilters(std::vector<std::string> const& filters);
7711 std::vector<std::string> const& getFilters() const;
7713 std::string const& trimmedName() const;
7714};
7715
7716} // namespace TestCaseTracking
7717
7718using TestCaseTracking::ITracker;
7719using TestCaseTracking::SectionTracker;
7720using TestCaseTracking::TrackerContext;
7721
7722} // namespace Catch
7723
7724// end catch_test_case_tracker.h
7725
7726// start catch_leak_detector.h
7727
7728namespace Catch {
7729
7730struct LeakDetector {
7731 LeakDetector();
7732 ~LeakDetector();
7733};
7734
7735} // namespace Catch
7736// end catch_leak_detector.h
7737// Cpp files will be included in the single-header file here
7738// start catch_stats.cpp
7739
7740// Statistical analysis tools
7741
7742#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7743
7744#include <cassert>
7745#include <random>
7746
7747#if defined(CATCH_CONFIG_USE_ASYNC)
7748#include <future>
7749#endif
7750
7751namespace {
7752double erf_inv(double x) {
7753 // Code accompanying the article "Approximating the erfinv function" in GPU
7754 // Computing Gems, Volume 2
7755 double w, p;
7756
7757 w = -log((1.0 - x) * (1.0 + x));
7758
7759 if (w < 6.250000) {
7760 w = w - 3.125000;
7761 p = -3.6444120640178196996e-21;
7762 p = -1.685059138182016589e-19 + p * w;
7763 p = 1.2858480715256400167e-18 + p * w;
7764 p = 1.115787767802518096e-17 + p * w;
7765 p = -1.333171662854620906e-16 + p * w;
7766 p = 2.0972767875968561637e-17 + p * w;
7767 p = 6.6376381343583238325e-15 + p * w;
7768 p = -4.0545662729752068639e-14 + p * w;
7769 p = -8.1519341976054721522e-14 + p * w;
7770 p = 2.6335093153082322977e-12 + p * w;
7771 p = -1.2975133253453532498e-11 + p * w;
7772 p = -5.4154120542946279317e-11 + p * w;
7773 p = 1.051212273321532285e-09 + p * w;
7774 p = -4.1126339803469836976e-09 + p * w;
7775 p = -2.9070369957882005086e-08 + p * w;
7776 p = 4.2347877827932403518e-07 + p * w;
7777 p = -1.3654692000834678645e-06 + p * w;
7778 p = -1.3882523362786468719e-05 + p * w;
7779 p = 0.0001867342080340571352 + p * w;
7780 p = -0.00074070253416626697512 + p * w;
7781 p = -0.0060336708714301490533 + p * w;
7782 p = 0.24015818242558961693 + p * w;
7783 p = 1.6536545626831027356 + p * w;
7784 } else if (w < 16.000000) {
7785 w = sqrt(w) - 3.250000;
7786 p = 2.2137376921775787049e-09;
7787 p = 9.0756561938885390979e-08 + p * w;
7788 p = -2.7517406297064545428e-07 + p * w;
7789 p = 1.8239629214389227755e-08 + p * w;
7790 p = 1.5027403968909827627e-06 + p * w;
7791 p = -4.013867526981545969e-06 + p * w;
7792 p = 2.9234449089955446044e-06 + p * w;
7793 p = 1.2475304481671778723e-05 + p * w;
7794 p = -4.7318229009055733981e-05 + p * w;
7795 p = 6.8284851459573175448e-05 + p * w;
7796 p = 2.4031110387097893999e-05 + p * w;
7797 p = -0.0003550375203628474796 + p * w;
7798 p = 0.00095328937973738049703 + p * w;
7799 p = -0.0016882755560235047313 + p * w;
7800 p = 0.0024914420961078508066 + p * w;
7801 p = -0.0037512085075692412107 + p * w;
7802 p = 0.005370914553590063617 + p * w;
7803 p = 1.0052589676941592334 + p * w;
7804 p = 3.0838856104922207635 + p * w;
7805 } else {
7806 w = sqrt(w) - 5.000000;
7807 p = -2.7109920616438573243e-11;
7808 p = -2.5556418169965252055e-10 + p * w;
7809 p = 1.5076572693500548083e-09 + p * w;
7810 p = -3.7894654401267369937e-09 + p * w;
7811 p = 7.6157012080783393804e-09 + p * w;
7812 p = -1.4960026627149240478e-08 + p * w;
7813 p = 2.9147953450901080826e-08 + p * w;
7814 p = -6.7711997758452339498e-08 + p * w;
7815 p = 2.2900482228026654717e-07 + p * w;
7816 p = -9.9298272942317002539e-07 + p * w;
7817 p = 4.5260625972231537039e-06 + p * w;
7818 p = -1.9681778105531670567e-05 + p * w;
7819 p = 7.5995277030017761139e-05 + p * w;
7820 p = -0.00021503011930044477347 + p * w;
7821 p = -0.00013871931833623122026 + p * w;
7822 p = 1.0103004648645343977 + p * w;
7823 p = 4.8499064014085844221 + p * w;
7824 }
7825 return p * x;
7826}
7827
7828double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7829 auto m = Catch::Benchmark::Detail::mean(first, last);
7830 double variance = std::accumulate(first, last, 0.,
7831 [m](double a, double b) {
7832 double diff = b - m;
7833 return a + diff * diff;
7834 }) /
7835 (last - first);
7836 return std::sqrt(variance);
7837}
7838
7839} // namespace
7840
7841namespace Catch {
7842namespace Benchmark {
7843namespace Detail {
7844
7845double weighted_average_quantile(int k, int q, std::vector<double>::iterator first,
7846 std::vector<double>::iterator last) {
7847 auto count = last - first;
7848 double idx = (count - 1) * k / static_cast<double>(q);
7849 int j = static_cast<int>(idx);
7850 double g = idx - j;
7851 std::nth_element(first, first + j, last);
7852 auto xj = first[j];
7853 if (g == 0)
7854 return xj;
7855
7856 auto xj1 = *std::min_element(first + (j + 1), last);
7857 return xj + g * (xj1 - xj);
7858}
7859
7860double erfc_inv(double x) {
7861 return erf_inv(1.0 - x);
7862}
7863
7864double normal_quantile(double p) {
7865 static const double ROOT_TWO = std::sqrt(2.0);
7866
7867 double result = 0.0;
7868 assert(p >= 0 && p <= 1);
7869 if (p < 0 || p > 1) {
7870 return result;
7871 }
7872
7873 result = -erfc_inv(2.0 * p);
7874 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7875 result *= /*sd * */ ROOT_TWO;
7876 // result += normal disttribution mean (0)
7877 return result;
7878}
7879
7880double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7881 double sb = stddev.point;
7882 double mn = mean.point / n;
7883 double mg_min = mn / 2.;
7884 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7885 double sg2 = sg * sg;
7886 double sb2 = sb * sb;
7887
7888 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7889 double k = mn - x;
7890 double d = k * k;
7891 double nd = n * d;
7892 double k0 = -n * nd;
7893 double k1 = sb2 - n * sg2 + nd;
7894 double det = k1 * k1 - 4 * sg2 * k0;
7895 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7896 };
7897
7898 auto var_out = [n, sb2, sg2](double c) {
7899 double nc = n - c;
7900 return (nc / n) * (sb2 - nc * sg2);
7901 };
7902
7903 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7904}
7905
7906bootstrap_analysis analyse_samples(double confidence_level, int n_resamples,
7907 std::vector<double>::iterator first,
7908 std::vector<double>::iterator last) {
7909 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7910 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7911 static std::random_device entropy;
7912 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7913
7914 auto n = static_cast<int>(last -
7915 first); // seriously, one can't use integral types without hell in C++
7916
7917 auto mean = &Detail::mean<std::vector<double>::iterator>;
7918 auto stddev = &standard_deviation;
7919
7920#if defined(CATCH_CONFIG_USE_ASYNC)
7921 auto Estimate = [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7922 auto seed = entropy();
7923 return std::async(std::launch::async, [=] {
7924 std::mt19937 rng(seed);
7925 auto resampled = resample(rng, n_resamples, first, last, f);
7926 return bootstrap(confidence_level, first, last, resampled, f);
7927 });
7928 };
7929
7930 auto mean_future = Estimate(mean);
7931 auto stddev_future = Estimate(stddev);
7932
7933 auto mean_estimate = mean_future.get();
7934 auto stddev_estimate = stddev_future.get();
7935#else
7936 auto Estimate = [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7937 auto seed = entropy();
7938 std::mt19937 rng(seed);
7939 auto resampled = resample(rng, n_resamples, first, last, f);
7940 return bootstrap(confidence_level, first, last, resampled, f);
7941 };
7942
7943 auto mean_estimate = Estimate(mean);
7944 auto stddev_estimate = Estimate(stddev);
7945#endif // CATCH_USE_ASYNC
7946
7947 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7948
7949 return {mean_estimate, stddev_estimate, outlier_variance};
7950}
7951} // namespace Detail
7952} // namespace Benchmark
7953} // namespace Catch
7954
7955#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7956// end catch_stats.cpp
7957// start catch_approx.cpp
7958
7959#include <cmath>
7960#include <limits>
7961
7962namespace {
7963
7964// Performs equivalent check of std::fabs(lhs - rhs) <= margin
7965// But without the subtraction to allow for INFINITY in comparison
7966bool marginComparison(double lhs, double rhs, double margin) {
7967 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7968}
7969
7970} // namespace
7971
7972namespace Catch {
7973namespace Detail {
7974
7975Approx::Approx(double value)
7976 : m_epsilon(std::numeric_limits<float>::epsilon() * 100), m_margin(0.0), m_scale(0.0),
7977 m_value(value) {}
7978
7979Approx Approx::custom() {
7980 return Approx(0);
7981}
7982
7983Approx Approx::operator-() const {
7984 auto temp(*this);
7985 temp.m_value = -temp.m_value;
7986 return temp;
7987}
7988
7989std::string Approx::toString() const {
7991 rss << "Approx( " << ::Catch::Detail::stringify(m_value) << " )";
7992 return rss.str();
7993}
7994
7995bool Approx::equalityComparisonImpl(const double other) const {
7996 // First try with fixed margin, then compute margin based on epsilon, scale
7997 // and Approx's value Thanks to Richard Harris for his help refining the
7998 // scaled margin value
7999 return marginComparison(m_value, other, m_margin) ||
8000 marginComparison(m_value, other,
8001 m_epsilon * (m_scale + std::fabs(std::isinf(m_value) ? 0 : m_value)));
8002}
8003
8004void Approx::setMargin(double newMargin) {
8005 CATCH_ENFORCE(newMargin >= 0,
8006 "Invalid Approx::margin: " << newMargin << '.'
8007 << " Approx::Margin has to be non-negative.");
8008 m_margin = newMargin;
8009}
8010
8011void Approx::setEpsilon(double newEpsilon) {
8012 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
8013 "Invalid Approx::epsilon: " << newEpsilon << '.'
8014 << " Approx::epsilon has to be in [0, 1]");
8015 m_epsilon = newEpsilon;
8016}
8017
8018} // end namespace Detail
8019
8020namespace literals {
8021Detail::Approx operator"" _a(long double val) {
8022 return Detail::Approx(val);
8023}
8024Detail::Approx operator"" _a(unsigned long long val) {
8025 return Detail::Approx(val);
8026}
8027} // end namespace literals
8028
8029std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
8030 return value.toString();
8031}
8032
8033} // end namespace Catch
8034// end catch_approx.cpp
8035// start catch_assertionhandler.cpp
8036
8037// start catch_debugger.h
8038
8039namespace Catch {
8040bool isDebuggerActive();
8041}
8042
8043#ifdef CATCH_PLATFORM_MAC
8044
8045#if defined(__i386__) || defined(__x86_64__)
8046#define CATCH_TRAP() __asm__("int $3\n" : :) /* NOLINT */
8047#elif defined(__aarch64__)
8048#define CATCH_TRAP() __asm__(".inst 0xd4200000")
8049#endif
8050
8051#elif defined(CATCH_PLATFORM_IPHONE)
8052
8053// use inline assembler
8054#if defined(__i386__) || defined(__x86_64__)
8055#define CATCH_TRAP() __asm__("int $3")
8056#elif defined(__aarch64__)
8057#define CATCH_TRAP() __asm__(".inst 0xd4200000")
8058#elif defined(__arm__) && !defined(__thumb__)
8059#define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
8060#elif defined(__arm__) && defined(__thumb__)
8061#define CATCH_TRAP() __asm__(".inst 0xde01")
8062#endif
8063
8064#elif defined(CATCH_PLATFORM_LINUX)
8065// If we can use inline assembler, do it because this allows us to break
8066// directly at the location of the failing check instead of breaking inside
8067// raise() called from it, i.e. one stack frame below.
8068#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
8069#define CATCH_TRAP() asm volatile("int $3") /* NOLINT */
8070#else // Fall back to the generic way.
8071#include <signal.h>
8072
8073#define CATCH_TRAP() raise(SIGTRAP)
8074#endif
8075#elif defined(_MSC_VER)
8076#define CATCH_TRAP() __debugbreak()
8077#elif defined(__MINGW32__)
8078extern "C" __declspec(dllimport) void __stdcall DebugBreak();
8079#define CATCH_TRAP() DebugBreak()
8080#endif
8081
8082#ifndef CATCH_BREAK_INTO_DEBUGGER
8083#ifdef CATCH_TRAP
8084#define CATCH_BREAK_INTO_DEBUGGER() \
8085 [] { \
8086 if (Catch::isDebuggerActive()) { \
8087 CATCH_TRAP(); \
8088 } \
8089 }()
8090#else
8091#define CATCH_BREAK_INTO_DEBUGGER() [] {}()
8092#endif
8093#endif
8094
8095// end catch_debugger.h
8096// start catch_run_context.h
8097
8098// start catch_fatal_condition.h
8099
8100#include <cassert>
8101
8102namespace Catch {
8103
8104// Wrapper for platform-specific fatal error (signals/SEH) handlers
8105//
8106// Tries to be cooperative with other handlers, and not step over
8107// other handlers. This means that unknown structured exceptions
8108// are passed on, previous signal handlers are called, and so on.
8109//
8110// Can only be instantiated once, and assumes that once a signal
8111// is caught, the binary will end up terminating. Thus, there
8112class FatalConditionHandler {
8113 bool m_started = false;
8114
8115 // Install/disengage implementation for specific platform.
8116 // Should be if-defed to work on current platform, can assume
8117 // engage-disengage 1:1 pairing.
8118 void engage_platform();
8119 void disengage_platform();
8120
8121 public:
8122 // Should also have platform-specific implementations as needed
8123 FatalConditionHandler();
8124 ~FatalConditionHandler();
8125
8126 void engage() {
8127 assert(!m_started && "Handler cannot be installed twice.");
8128 m_started = true;
8129 engage_platform();
8130 }
8131
8132 void disengage() {
8133 assert(m_started && "Handler cannot be uninstalled without being installed first");
8134 m_started = false;
8135 disengage_platform();
8136 }
8137};
8138
8140class FatalConditionHandlerGuard {
8141 FatalConditionHandler* m_handler;
8142
8143 public:
8144 FatalConditionHandlerGuard(FatalConditionHandler* handler) : m_handler(handler) {
8145 m_handler->engage();
8146 }
8147 ~FatalConditionHandlerGuard() { m_handler->disengage(); }
8148};
8149
8150} // end namespace Catch
8151
8152// end catch_fatal_condition.h
8153#include <string>
8154
8155namespace Catch {
8156
8157struct IMutableContext;
8158
8160
8161class RunContext : public IResultCapture, public IRunner {
8162
8163 public:
8164 RunContext(RunContext const&) = delete;
8165 RunContext& operator=(RunContext const&) = delete;
8166
8167 explicit RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter);
8168
8169 ~RunContext() override;
8170
8171 void testGroupStarting(std::string const& testSpec, std::size_t groupIndex,
8172 std::size_t groupsCount);
8173 void testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex,
8174 std::size_t groupsCount);
8175
8176 Totals runTest(TestCase const& testCase);
8177
8178 IConfigPtr config() const;
8179 IStreamingReporter& reporter() const;
8180
8181 public: // IResultCapture
8182 // Assertion handlers
8183 void handleExpr(AssertionInfo const& info, ITransientExpression const& expr,
8184 AssertionReaction& reaction) override;
8185 void handleMessage(AssertionInfo const& info, ResultWas::OfType resultType,
8186 StringRef const& message, AssertionReaction& reaction) override;
8187 void handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
8188 AssertionReaction& reaction) override;
8189 void handleUnexpectedInflightException(AssertionInfo const& info, std::string const& message,
8190 AssertionReaction& reaction) override;
8191 void handleIncomplete(AssertionInfo const& info) override;
8192 void handleNonExpr(AssertionInfo const& info, ResultWas::OfType resultType,
8193 AssertionReaction& reaction) override;
8194
8195 bool sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) override;
8196
8197 void sectionEnded(SectionEndInfo const& endInfo) override;
8198 void sectionEndedEarly(SectionEndInfo const& endInfo) override;
8199
8200 auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
8201 -> IGeneratorTracker& override;
8202
8203#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8204 void benchmarkPreparing(std::string const& name) override;
8205 void benchmarkStarting(BenchmarkInfo const& info) override;
8206 void benchmarkEnded(BenchmarkStats<> const& stats) override;
8207 void benchmarkFailed(std::string const& error) override;
8208#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8209
8210 void pushScopedMessage(MessageInfo const& message) override;
8211 void popScopedMessage(MessageInfo const& message) override;
8212
8213 void emplaceUnscopedMessage(MessageBuilder const& builder) override;
8214
8215 std::string getCurrentTestName() const override;
8216
8217 const AssertionResult* getLastResult() const override;
8218
8219 void exceptionEarlyReported() override;
8220
8221 void handleFatalErrorCondition(StringRef message) override;
8222
8223 bool lastAssertionPassed() override;
8224
8225 void assertionPassed() override;
8226
8227 public:
8228 // !TBD We need to do this another way!
8229 bool aborting() const final;
8230
8231 private:
8232 void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr);
8233 void invokeActiveTestCase();
8234
8235 void resetAssertionInfo();
8236 bool testForMissingAssertions(Counts& assertions);
8237
8238 void assertionEnded(AssertionResult const& result);
8239 void reportExpr(AssertionInfo const& info, ResultWas::OfType resultType,
8240 ITransientExpression const* expr, bool negated);
8241
8242 void populateReaction(AssertionReaction& reaction);
8243
8244 private:
8245 void handleUnfinishedSections();
8246
8247 TestRunInfo m_runInfo;
8248 IMutableContext& m_context;
8249 TestCase const* m_activeTestCase = nullptr;
8250 ITracker* m_testCaseTracker = nullptr;
8251 Option<AssertionResult> m_lastResult;
8252
8253 IConfigPtr m_config;
8254 Totals m_totals;
8255 IStreamingReporterPtr m_reporter;
8256 std::vector<MessageInfo> m_messages;
8257 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8258 AssertionInfo m_lastAssertionInfo;
8259 std::vector<SectionEndInfo> m_unfinishedSections;
8260 std::vector<ITracker*> m_activeSections;
8261 TrackerContext m_trackerContext;
8262 FatalConditionHandler m_fatalConditionhandler;
8263 bool m_lastAssertionPassed = false;
8264 bool m_shouldReportUnexpected = true;
8265 bool m_includeSuccessfulResults;
8266};
8267
8268void seedRng(IConfig const& config);
8269unsigned int rngSeed();
8270} // end namespace Catch
8271
8272// end catch_run_context.h
8273namespace Catch {
8274
8275namespace {
8276auto operator<<(std::ostream& os, ITransientExpression const& expr) -> std::ostream& {
8277 expr.streamReconstructedExpression(os);
8278 return os;
8279}
8280} // namespace
8281
8282LazyExpression::LazyExpression(bool isNegated) : m_isNegated(isNegated) {}
8283
8284LazyExpression::LazyExpression(LazyExpression const& other) : m_isNegated(other.m_isNegated) {}
8285
8286LazyExpression::operator bool() const {
8287 return m_transientExpression != nullptr;
8288}
8289
8290auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& {
8291 if (lazyExpr.m_isNegated)
8292 os << "!";
8293
8294 if (lazyExpr) {
8295 if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
8296 os << "(" << *lazyExpr.m_transientExpression << ")";
8297 else
8298 os << *lazyExpr.m_transientExpression;
8299 } else {
8300 os << "{** error - unchecked empty expression requested **}";
8301 }
8302 return os;
8303}
8304
8305AssertionHandler::AssertionHandler(StringRef const& macroName, SourceLineInfo const& lineInfo,
8306 StringRef capturedExpression,
8307 ResultDisposition::Flags resultDisposition)
8308 : m_assertionInfo{macroName, lineInfo, capturedExpression, resultDisposition},
8309 m_resultCapture(getResultCapture()) {}
8310
8311void AssertionHandler::handleExpr(ITransientExpression const& expr) {
8312 m_resultCapture.handleExpr(m_assertionInfo, expr, m_reaction);
8313}
8314void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8315 m_resultCapture.handleMessage(m_assertionInfo, resultType, message, m_reaction);
8316}
8317
8318auto AssertionHandler::allowThrows() const -> bool {
8319 return getCurrentContext().getConfig()->allowThrows();
8320}
8321
8322void AssertionHandler::complete() {
8323 setCompleted();
8324 if (m_reaction.shouldDebugBreak) {
8325
8326 // If you find your debugger stopping you here then go one level up on the
8327 // call-stack for the code that caused it (typically a failed assertion)
8328
8329 // (To go back to the test and change execution, jump over the throw, next)
8330 CATCH_BREAK_INTO_DEBUGGER();
8331 }
8332 if (m_reaction.shouldThrow) {
8333#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8334 throw Catch::TestFailureException();
8335#else
8336 CATCH_ERROR("Test failure requires aborting test!");
8337#endif
8338 }
8339}
8340void AssertionHandler::setCompleted() {
8341 m_completed = true;
8342}
8343
8344void AssertionHandler::handleUnexpectedInflightException() {
8345 m_resultCapture.handleUnexpectedInflightException(
8346 m_assertionInfo, Catch::translateActiveException(), m_reaction);
8347}
8348
8349void AssertionHandler::handleExceptionThrownAsExpected() {
8350 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8351}
8352void AssertionHandler::handleExceptionNotThrownAsExpected() {
8353 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8354}
8355
8356void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8357 m_resultCapture.handleUnexpectedExceptionNotThrown(m_assertionInfo, m_reaction);
8358}
8359
8360void AssertionHandler::handleThrowingCallSkipped() {
8361 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8362}
8363
8364// This is the overload that takes a string and infers the Equals matcher from
8365// it The more general overload, that takes any string matcher, is in
8366// catch_capture_matchers.cpp
8367void handleExceptionMatchExpr(AssertionHandler& handler, std::string const& str,
8368 StringRef const& matcherString) {
8369 handleExceptionMatchExpr(handler, Matchers::Equals(str), matcherString);
8370}
8371
8372} // namespace Catch
8373// end catch_assertionhandler.cpp
8374// start catch_assertionresult.cpp
8375
8376namespace Catch {
8377AssertionResultData::AssertionResultData(ResultWas::OfType _resultType,
8378 LazyExpression const& _lazyExpression)
8379 : lazyExpression(_lazyExpression), resultType(_resultType) {}
8380
8381std::string AssertionResultData::reconstructExpression() const {
8382
8383 if (reconstructedExpression.empty()) {
8384 if (lazyExpression) {
8386 rss << lazyExpression;
8387 reconstructedExpression = rss.str();
8388 }
8389 }
8390 return reconstructedExpression;
8391}
8392
8393AssertionResult::AssertionResult(AssertionInfo const& info, AssertionResultData const& data)
8394 : m_info(info), m_resultData(data) {}
8395
8396// Result was a success
8397bool AssertionResult::succeeded() const {
8398 return Catch::isOk(m_resultData.resultType);
8399}
8400
8401// Result was a success, or failure is suppressed
8402bool AssertionResult::isOk() const {
8403 return Catch::isOk(m_resultData.resultType) || shouldSuppressFailure(m_info.resultDisposition);
8404}
8405
8406ResultWas::OfType AssertionResult::getResultType() const {
8407 return m_resultData.resultType;
8408}
8409
8410bool AssertionResult::hasExpression() const {
8411 return !m_info.capturedExpression.empty();
8412}
8413
8414bool AssertionResult::hasMessage() const {
8415 return !m_resultData.message.empty();
8416}
8417
8418std::string AssertionResult::getExpression() const {
8419 // Possibly overallocating by 3 characters should be basically free
8420 std::string expr;
8421 expr.reserve(m_info.capturedExpression.size() + 3);
8422 if (isFalseTest(m_info.resultDisposition)) {
8423 expr += "!(";
8424 }
8425 expr += m_info.capturedExpression;
8426 if (isFalseTest(m_info.resultDisposition)) {
8427 expr += ')';
8428 }
8429 return expr;
8430}
8431
8432std::string AssertionResult::getExpressionInMacro() const {
8433 std::string expr;
8434 if (m_info.macroName.empty())
8435 expr = static_cast<std::string>(m_info.capturedExpression);
8436 else {
8437 expr.reserve(m_info.macroName.size() + m_info.capturedExpression.size() + 4);
8438 expr += m_info.macroName;
8439 expr += "( ";
8440 expr += m_info.capturedExpression;
8441 expr += " )";
8442 }
8443 return expr;
8444}
8445
8446bool AssertionResult::hasExpandedExpression() const {
8447 return hasExpression() && getExpandedExpression() != getExpression();
8448}
8449
8450std::string AssertionResult::getExpandedExpression() const {
8451 std::string expr = m_resultData.reconstructExpression();
8452 return expr.empty() ? getExpression() : expr;
8453}
8454
8455std::string AssertionResult::getMessage() const {
8456 return m_resultData.message;
8457}
8458SourceLineInfo AssertionResult::getSourceInfo() const {
8459 return m_info.lineInfo;
8460}
8461
8462StringRef AssertionResult::getTestMacroName() const {
8463 return m_info.macroName;
8464}
8465
8466} // end namespace Catch
8467// end catch_assertionresult.cpp
8468// start catch_capture_matchers.cpp
8469
8470namespace Catch {
8471
8472using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8473
8474// This is the general overload that takes a any string matcher
8475// There is another overload, in catch_assertionhandler.h/.cpp, that only takes
8476// a string and infers the Equals matcher (so the header does not mention
8477// matchers)
8478void handleExceptionMatchExpr(AssertionHandler& handler, StringMatcher const& matcher,
8479 StringRef const& matcherString) {
8480 std::string exceptionMessage = Catch::translateActiveException();
8481 MatchExpr<std::string, StringMatcher const&> expr(exceptionMessage, matcher, matcherString);
8482 handler.handleExpr(expr);
8483}
8484
8485} // namespace Catch
8486// end catch_capture_matchers.cpp
8487// start catch_commandline.cpp
8488
8489// start catch_commandline.h
8490
8491// start catch_clara.h
8492
8493// Use Catch's value for console width (store Clara's off to the side, if
8494// present)
8495#ifdef CLARA_CONFIG_CONSOLE_WIDTH
8496#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8497#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8498#endif
8499#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1
8500
8501#ifdef __clang__
8502#pragma clang diagnostic push
8503#pragma clang diagnostic ignored "-Wweak-vtables"
8504#pragma clang diagnostic ignored "-Wexit-time-destructors"
8505#pragma clang diagnostic ignored "-Wshadow"
8506#endif
8507
8508// start clara.hpp
8509// Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8510//
8511// Distributed under the Boost Software License, Version 1.0. (See accompanying
8512// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8513//
8514// See https://github.com/philsquared/Clara for more details
8515
8516// Clara v1.1.5
8517
8518#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8519#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8520#endif
8521
8522#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8523#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8524#endif
8525
8526#ifndef CLARA_CONFIG_OPTIONAL_TYPE
8527#ifdef __has_include
8528#if __has_include(<optional>) && __cplusplus >= 201703L
8529#include <optional>
8530#define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8531#endif
8532#endif
8533#endif
8534
8535// ----------- #included from clara_textflow.hpp -----------
8536
8537// TextFlowCpp
8538//
8539// A single-header library for wrapping and laying out basic text, by Phil Nash
8540//
8541// Distributed under the Boost Software License, Version 1.0. (See accompanying
8542// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8543//
8544// This project is hosted at https://github.com/philsquared/textflowcpp
8545
8546#include <cassert>
8547#include <ostream>
8548#include <sstream>
8549#include <vector>
8550
8551#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8552#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8553#endif
8554
8555namespace Catch {
8556namespace clara {
8557namespace TextFlow {
8558
8559inline auto isWhitespace(char c) -> bool {
8560 static std::string chars = " \t\n\r";
8561 return chars.find(c) != std::string::npos;
8562}
8563inline auto isBreakableBefore(char c) -> bool {
8564 static std::string chars = "[({<|";
8565 return chars.find(c) != std::string::npos;
8566}
8567inline auto isBreakableAfter(char c) -> bool {
8568 static std::string chars = "])}>.,:;*+-=&/\\";
8569 return chars.find(c) != std::string::npos;
8570}
8571
8572class Columns;
8573
8574class Column {
8575 std::vector<std::string> m_strings;
8576 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8577 size_t m_indent = 0;
8578 size_t m_initialIndent = std::string::npos;
8579
8580 public:
8581 class iterator {
8582 friend Column;
8583
8584 Column const& m_column;
8585 size_t m_stringIndex = 0;
8586 size_t m_pos = 0;
8587
8588 size_t m_len = 0;
8589 size_t m_end = 0;
8590 bool m_suffix = false;
8591
8592 iterator(Column const& column, size_t stringIndex)
8593 : m_column(column), m_stringIndex(stringIndex) {}
8594
8595 auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8596
8597 auto isBoundary(size_t at) const -> bool {
8598 assert(at > 0);
8599 assert(at <= line().size());
8600
8601 return at == line().size() ||
8602 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8603 isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]);
8604 }
8605
8606 void calcLength() {
8607 assert(m_stringIndex < m_column.m_strings.size());
8608
8609 m_suffix = false;
8610 auto width = m_column.m_width - indent();
8611 m_end = m_pos;
8612 if (line()[m_pos] == '\n') {
8613 ++m_end;
8614 }
8615 while (m_end < line().size() && line()[m_end] != '\n')
8616 ++m_end;
8617
8618 if (m_end < m_pos + width) {
8619 m_len = m_end - m_pos;
8620 } else {
8621 size_t len = width;
8622 while (len > 0 && !isBoundary(m_pos + len))
8623 --len;
8624 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8625 --len;
8626
8627 if (len > 0) {
8628 m_len = len;
8629 } else {
8630 m_suffix = true;
8631 m_len = width - 1;
8632 }
8633 }
8634 }
8635
8636 auto indent() const -> size_t {
8637 auto initial =
8638 m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8639 return initial == std::string::npos ? m_column.m_indent : initial;
8640 }
8641
8642 auto addIndentAndSuffix(std::string const& plain) const -> std::string {
8643 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8644 }
8645
8646 public:
8647 using difference_type = std::ptrdiff_t;
8648 using value_type = std::string;
8649 using pointer = value_type*;
8650 using reference = value_type&;
8651 using iterator_category = std::forward_iterator_tag;
8652
8653 explicit iterator(Column const& column) : m_column(column) {
8654 assert(m_column.m_width > m_column.m_indent);
8655 assert(m_column.m_initialIndent == std::string::npos ||
8656 m_column.m_width > m_column.m_initialIndent);
8657 calcLength();
8658 if (m_len == 0)
8659 m_stringIndex++; // Empty string
8660 }
8661
8662 auto operator*() const -> std::string {
8663 assert(m_stringIndex < m_column.m_strings.size());
8664 assert(m_pos <= m_end);
8665 return addIndentAndSuffix(line().substr(m_pos, m_len));
8666 }
8667
8668 auto operator++() -> iterator& {
8669 m_pos += m_len;
8670 if (m_pos < line().size() && line()[m_pos] == '\n')
8671 m_pos += 1;
8672 else
8673 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8674 ++m_pos;
8675
8676 if (m_pos == line().size()) {
8677 m_pos = 0;
8678 ++m_stringIndex;
8679 }
8680 if (m_stringIndex < m_column.m_strings.size())
8681 calcLength();
8682 return *this;
8683 }
8684 auto operator++(int) -> iterator {
8685 iterator prev(*this);
8686 operator++();
8687 return prev;
8688 }
8689
8690 auto operator==(iterator const& other) const -> bool {
8691 return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex &&
8692 &m_column == &other.m_column;
8693 }
8694 auto operator!=(iterator const& other) const -> bool { return !operator==(other); }
8695 };
8696 using const_iterator = iterator;
8697
8698 explicit Column(std::string const& text) { m_strings.push_back(text); }
8699
8700 auto width(size_t newWidth) -> Column& {
8701 assert(newWidth > 0);
8702 m_width = newWidth;
8703 return *this;
8704 }
8705 auto indent(size_t newIndent) -> Column& {
8706 m_indent = newIndent;
8707 return *this;
8708 }
8709 auto initialIndent(size_t newIndent) -> Column& {
8710 m_initialIndent = newIndent;
8711 return *this;
8712 }
8713
8714 auto width() const -> size_t { return m_width; }
8715 auto begin() const -> iterator { return iterator(*this); }
8716 auto end() const -> iterator { return {*this, m_strings.size()}; }
8717
8718 inline friend std::ostream& operator<<(std::ostream& os, Column const& col) {
8719 bool first = true;
8720 for (auto line : col) {
8721 if (first)
8722 first = false;
8723 else
8724 os << "\n";
8725 os << line;
8726 }
8727 return os;
8728 }
8729
8730 auto operator+(Column const& other) -> Columns;
8731
8732 auto toString() const -> std::string {
8733 std::ostringstream oss;
8734 oss << *this;
8735 return oss.str();
8736 }
8737};
8738
8739class Spacer : public Column {
8740
8741 public:
8742 explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); }
8743};
8744
8745class Columns {
8746 std::vector<Column> m_columns;
8747
8748 public:
8749 class iterator {
8750 friend Columns;
8751 struct EndTag {};
8752
8753 std::vector<Column> const& m_columns;
8754 std::vector<Column::iterator> m_iterators;
8755 size_t m_activeIterators;
8756
8757 iterator(Columns const& columns, EndTag)
8758 : m_columns(columns.m_columns), m_activeIterators(0) {
8759 m_iterators.reserve(m_columns.size());
8760
8761 for (auto const& col : m_columns)
8762 m_iterators.push_back(col.end());
8763 }
8764
8765 public:
8766 using difference_type = std::ptrdiff_t;
8767 using value_type = std::string;
8768 using pointer = value_type*;
8769 using reference = value_type&;
8770 using iterator_category = std::forward_iterator_tag;
8771
8772 explicit iterator(Columns const& columns)
8773 : m_columns(columns.m_columns), m_activeIterators(m_columns.size()) {
8774 m_iterators.reserve(m_columns.size());
8775
8776 for (auto const& col : m_columns)
8777 m_iterators.push_back(col.begin());
8778 }
8779
8780 auto operator==(iterator const& other) const -> bool {
8781 return m_iterators == other.m_iterators;
8782 }
8783 auto operator!=(iterator const& other) const -> bool {
8784 return m_iterators != other.m_iterators;
8785 }
8786 auto operator*() const -> std::string {
8787 std::string row, padding;
8788
8789 for (size_t i = 0; i < m_columns.size(); ++i) {
8790 auto width = m_columns[i].width();
8791 if (m_iterators[i] != m_columns[i].end()) {
8792 std::string col = *m_iterators[i];
8793 row += padding + col;
8794 if (col.size() < width)
8795 padding = std::string(width - col.size(), ' ');
8796 else
8797 padding = "";
8798 } else {
8799 padding += std::string(width, ' ');
8800 }
8801 }
8802 return row;
8803 }
8804 auto operator++() -> iterator& {
8805 for (size_t i = 0; i < m_columns.size(); ++i) {
8806 if (m_iterators[i] != m_columns[i].end())
8807 ++m_iterators[i];
8808 }
8809 return *this;
8810 }
8811 auto operator++(int) -> iterator {
8812 iterator prev(*this);
8813 operator++();
8814 return prev;
8815 }
8816 };
8817 using const_iterator = iterator;
8818
8819 auto begin() const -> iterator { return iterator(*this); }
8820 auto end() const -> iterator { return {*this, iterator::EndTag()}; }
8821
8822 auto operator+=(Column const& col) -> Columns& {
8823 m_columns.push_back(col);
8824 return *this;
8825 }
8826 auto operator+(Column const& col) -> Columns {
8827 Columns combined = *this;
8828 combined += col;
8829 return combined;
8830 }
8831
8832 inline friend std::ostream& operator<<(std::ostream& os, Columns const& cols) {
8833
8834 bool first = true;
8835 for (auto line : cols) {
8836 if (first)
8837 first = false;
8838 else
8839 os << "\n";
8840 os << line;
8841 }
8842 return os;
8843 }
8844
8845 auto toString() const -> std::string {
8846 std::ostringstream oss;
8847 oss << *this;
8848 return oss.str();
8849 }
8850};
8851
8852inline auto Column::operator+(Column const& other) -> Columns {
8853 Columns cols;
8854 cols += *this;
8855 cols += other;
8856 return cols;
8857}
8858} // namespace TextFlow
8859
8860} // namespace clara
8861} // namespace Catch
8862
8863// ----------- end of #include from clara_textflow.hpp -----------
8864// ........... back in clara.hpp
8865
8866#include <algorithm>
8867#include <cctype>
8868#include <memory>
8869#include <set>
8870#include <string>
8871
8872#if !defined(CATCH_PLATFORM_WINDOWS) && \
8873 (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER))
8874#define CATCH_PLATFORM_WINDOWS
8875#endif
8876
8877namespace Catch {
8878namespace clara {
8879namespace detail {
8880
8881// Traits for extracting arg and return type of lambdas (for single argument
8882// lambdas)
8883template <typename L> struct UnaryLambdaTraits : UnaryLambdaTraits<decltype(&L::operator())> {};
8884
8885template <typename ClassT, typename ReturnT, typename... Args>
8886struct UnaryLambdaTraits<ReturnT (ClassT::*)(Args...) const> {
8887 static const bool isValid = false;
8888};
8889
8890template <typename ClassT, typename ReturnT, typename ArgT>
8891struct UnaryLambdaTraits<ReturnT (ClassT::*)(ArgT) const> {
8892 static const bool isValid = true;
8893 using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8894 using ReturnType = ReturnT;
8895};
8896
8897class TokenStream;
8898
8899// Transport for raw args (copied from main args, or supplied via init list for
8900// testing)
8901class Args {
8902 friend TokenStream;
8903 std::string m_exeName;
8904 std::vector<std::string> m_args;
8905
8906 public:
8907 Args(int argc, char const* const* argv) : m_exeName(argv[0]), m_args(argv + 1, argv + argc) {}
8908
8909 Args(std::initializer_list<std::string> args)
8910 : m_exeName(*args.begin()), m_args(args.begin() + 1, args.end()) {}
8911
8912 auto exeName() const -> std::string { return m_exeName; }
8913};
8914
8915// Wraps a token coming from a token stream. These may not directly correspond
8916// to strings as a single string may encode an option + its argument if the : or
8917// = form is used
8918enum class TokenType { Option, Argument };
8919struct Token {
8920 TokenType type;
8921 std::string token;
8922};
8923
8924inline auto isOptPrefix(char c) -> bool {
8925 return c == '-'
8926#ifdef CATCH_PLATFORM_WINDOWS
8927 || c == '/'
8928#endif
8929 ;
8930}
8931
8932// Abstracts iterators into args as a stream of tokens, with option arguments
8933// uniformly handled
8934class TokenStream {
8935 using Iterator = std::vector<std::string>::const_iterator;
8936 Iterator it;
8937 Iterator itEnd;
8938 std::vector<Token> m_tokenBuffer;
8939
8940 void loadBuffer() {
8941 m_tokenBuffer.resize(0);
8942
8943 // Skip any empty strings
8944 while (it != itEnd && it->empty())
8945 ++it;
8946
8947 if (it != itEnd) {
8948 auto const& next = *it;
8949 if (isOptPrefix(next[0])) {
8950 auto delimiterPos = next.find_first_of(" :=");
8951 if (delimiterPos != std::string::npos) {
8952 m_tokenBuffer.push_back({TokenType::Option, next.substr(0, delimiterPos)});
8953 m_tokenBuffer.push_back({TokenType::Argument, next.substr(delimiterPos + 1)});
8954 } else {
8955 if (next[1] != '-' && next.size() > 2) {
8956 std::string opt = "- ";
8957 for (size_t i = 1; i < next.size(); ++i) {
8958 opt[1] = next[i];
8959 m_tokenBuffer.push_back({TokenType::Option, opt});
8960 }
8961 } else {
8962 m_tokenBuffer.push_back({TokenType::Option, next});
8963 }
8964 }
8965 } else {
8966 m_tokenBuffer.push_back({TokenType::Argument, next});
8967 }
8968 }
8969 }
8970
8971 public:
8972 explicit TokenStream(Args const& args) : TokenStream(args.m_args.begin(), args.m_args.end()) {}
8973
8974 TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); }
8975
8976 explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; }
8977
8978 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8979
8980 auto operator*() const -> Token {
8981 assert(!m_tokenBuffer.empty());
8982 return m_tokenBuffer.front();
8983 }
8984
8985 auto operator->() const -> Token const* {
8986 assert(!m_tokenBuffer.empty());
8987 return &m_tokenBuffer.front();
8988 }
8989
8990 auto operator++() -> TokenStream& {
8991 if (m_tokenBuffer.size() >= 2) {
8992 m_tokenBuffer.erase(m_tokenBuffer.begin());
8993 } else {
8994 if (it != itEnd)
8995 ++it;
8996 loadBuffer();
8997 }
8998 return *this;
8999 }
9000};
9001
9002class ResultBase {
9003 public:
9004 enum Type { Ok, LogicError, RuntimeError };
9005
9006 protected:
9007 ResultBase(Type type) : m_type(type) {}
9008 virtual ~ResultBase() = default;
9009
9010 virtual void enforceOk() const = 0;
9011
9012 Type m_type;
9013};
9014
9015template <typename T> class ResultValueBase : public ResultBase {
9016 public:
9017 auto value() const -> T const& {
9018 enforceOk();
9019 return m_value;
9020 }
9021
9022 protected:
9023 ResultValueBase(Type type) : ResultBase(type) {}
9024
9025 ResultValueBase(ResultValueBase const& other) : ResultBase(other) {
9026 if (m_type == ResultBase::Ok)
9027 new (&m_value) T(other.m_value);
9028 }
9029
9030 ResultValueBase(Type, T const& value) : ResultBase(Ok) { new (&m_value) T(value); }
9031
9032 auto operator=(ResultValueBase const& other) -> ResultValueBase& {
9033 if (m_type == ResultBase::Ok)
9034 m_value.~T();
9035 ResultBase::operator=(other);
9036 if (m_type == ResultBase::Ok)
9037 new (&m_value) T(other.m_value);
9038 return *this;
9039 }
9040
9041 ~ResultValueBase() override {
9042 if (m_type == Ok)
9043 m_value.~T();
9044 }
9045
9046 union {
9047 T m_value;
9048 };
9049};
9050
9051template <> class ResultValueBase<void> : public ResultBase {
9052 protected:
9053 using ResultBase::ResultBase;
9054};
9055
9056template <typename T = void> class BasicResult : public ResultValueBase<T> {
9057 public:
9058 template <typename U>
9059 explicit BasicResult(BasicResult<U> const& other)
9060 : ResultValueBase<T>(other.type()), m_errorMessage(other.errorMessage()) {
9061 assert(type() != ResultBase::Ok);
9062 }
9063
9064 template <typename U> static auto ok(U const& value) -> BasicResult {
9065 return {ResultBase::Ok, value};
9066 }
9067 static auto ok() -> BasicResult { return {ResultBase::Ok}; }
9068 static auto logicError(std::string const& message) -> BasicResult {
9069 return {ResultBase::LogicError, message};
9070 }
9071 static auto runtimeError(std::string const& message) -> BasicResult {
9072 return {ResultBase::RuntimeError, message};
9073 }
9074
9075 explicit operator bool() const { return m_type == ResultBase::Ok; }
9076 auto type() const -> ResultBase::Type { return m_type; }
9077 auto errorMessage() const -> std::string { return m_errorMessage; }
9078
9079 protected:
9080 void enforceOk() const override {
9081
9082 // Errors shouldn't reach this point, but if they do
9083 // the actual error message will be in m_errorMessage
9084 assert(m_type != ResultBase::LogicError);
9085 assert(m_type != ResultBase::RuntimeError);
9086 if (m_type != ResultBase::Ok)
9087 std::abort();
9088 }
9089
9090 std::string m_errorMessage; // Only populated if resultType is an error
9091
9092 BasicResult(ResultBase::Type type, std::string const& message)
9093 : ResultValueBase<T>(type), m_errorMessage(message) {
9094 assert(m_type != ResultBase::Ok);
9095 }
9096
9097 using ResultValueBase<T>::ResultValueBase;
9098 using ResultBase::m_type;
9099};
9100
9101enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame };
9102
9103class ParseState {
9104 public:
9105 ParseState(ParseResultType type, TokenStream const& remainingTokens)
9106 : m_type(type), m_remainingTokens(remainingTokens) {}
9107
9108 auto type() const -> ParseResultType { return m_type; }
9109 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9110
9111 private:
9112 ParseResultType m_type;
9113 TokenStream m_remainingTokens;
9114};
9115
9116using Result = BasicResult<void>;
9117using ParserResult = BasicResult<ParseResultType>;
9118using InternalParseResult = BasicResult<ParseState>;
9119
9120struct HelpColumns {
9121 std::string left;
9122 std::string right;
9123};
9124
9125template <typename T>
9126inline auto convertInto(std::string const& source, T& target) -> ParserResult {
9127 std::stringstream ss;
9128 ss << source;
9129 ss >> target;
9130 if (ss.fail())
9131 return ParserResult::runtimeError("Unable to convert '" + source + "' to destination type");
9132 else
9133 return ParserResult::ok(ParseResultType::Matched);
9134}
9135inline auto convertInto(std::string const& source, std::string& target) -> ParserResult {
9136 target = source;
9137 return ParserResult::ok(ParseResultType::Matched);
9138}
9139inline auto convertInto(std::string const& source, bool& target) -> ParserResult {
9140 std::string srcLC = source;
9141 std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(),
9142 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
9143 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9144 target = true;
9145 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
9146 target = false;
9147 else
9148 return ParserResult::runtimeError("Expected a boolean value but did not recognise: '" +
9149 source + "'");
9150 return ParserResult::ok(ParseResultType::Matched);
9151}
9152#ifdef CLARA_CONFIG_OPTIONAL_TYPE
9153template <typename T>
9154inline auto convertInto(std::string const& source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target)
9155 -> ParserResult {
9156 T temp;
9157 auto result = convertInto(source, temp);
9158 if (result)
9159 target = std::move(temp);
9160 return result;
9161}
9162#endif // CLARA_CONFIG_OPTIONAL_TYPE
9163
9164struct NonCopyable {
9165 NonCopyable() = default;
9166 NonCopyable(NonCopyable const&) = delete;
9167 NonCopyable(NonCopyable&&) = delete;
9168 NonCopyable& operator=(NonCopyable const&) = delete;
9169 NonCopyable& operator=(NonCopyable&&) = delete;
9170};
9171
9172struct BoundRef : NonCopyable {
9173 virtual ~BoundRef() = default;
9174 virtual auto isContainer() const -> bool { return false; }
9175 virtual auto isFlag() const -> bool { return false; }
9176};
9177struct BoundValueRefBase : BoundRef {
9178 virtual auto setValue(std::string const& arg) -> ParserResult = 0;
9179};
9180struct BoundFlagRefBase : BoundRef {
9181 virtual auto setFlag(bool flag) -> ParserResult = 0;
9182 virtual auto isFlag() const -> bool { return true; }
9183};
9184
9185template <typename T> struct BoundValueRef : BoundValueRefBase {
9186 T& m_ref;
9187
9188 explicit BoundValueRef(T& ref) : m_ref(ref) {}
9189
9190 auto setValue(std::string const& arg) -> ParserResult override {
9191 return convertInto(arg, m_ref);
9192 }
9193};
9194
9195template <typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9196 std::vector<T>& m_ref;
9197
9198 explicit BoundValueRef(std::vector<T>& ref) : m_ref(ref) {}
9199
9200 auto isContainer() const -> bool override { return true; }
9201
9202 auto setValue(std::string const& arg) -> ParserResult override {
9203 T temp;
9204 auto result = convertInto(arg, temp);
9205 if (result)
9206 m_ref.push_back(temp);
9207 return result;
9208 }
9209};
9210
9211struct BoundFlagRef : BoundFlagRefBase {
9212 bool& m_ref;
9213
9214 explicit BoundFlagRef(bool& ref) : m_ref(ref) {}
9215
9216 auto setFlag(bool flag) -> ParserResult override {
9217 m_ref = flag;
9218 return ParserResult::ok(ParseResultType::Matched);
9219 }
9220};
9221
9222template <typename ReturnType> struct LambdaInvoker {
9223 static_assert(std::is_same<ReturnType, ParserResult>::value,
9224 "Lambda must return void or clara::ParserResult");
9225
9226 template <typename L, typename ArgType>
9227 static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult {
9228 return lambda(arg);
9229 }
9230};
9231
9232template <> struct LambdaInvoker<void> {
9233 template <typename L, typename ArgType>
9234 static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult {
9235 lambda(arg);
9236 return ParserResult::ok(ParseResultType::Matched);
9237 }
9238};
9239
9240template <typename ArgType, typename L>
9241inline auto invokeLambda(L const& lambda, std::string const& arg) -> ParserResult {
9242 ArgType temp{};
9243 auto result = convertInto(arg, temp);
9244 return !result ? result
9245 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(lambda, temp);
9246}
9247
9248template <typename L> struct BoundLambda : BoundValueRefBase {
9249 L m_lambda;
9250
9251 static_assert(UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument");
9252 explicit BoundLambda(L const& lambda) : m_lambda(lambda) {}
9253
9254 auto setValue(std::string const& arg) -> ParserResult override {
9255 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(m_lambda, arg);
9256 }
9257};
9258
9259template <typename L> struct BoundFlagLambda : BoundFlagRefBase {
9260 L m_lambda;
9261
9262 static_assert(UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument");
9263 static_assert(std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value,
9264 "flags must be boolean");
9265
9266 explicit BoundFlagLambda(L const& lambda) : m_lambda(lambda) {}
9267
9268 auto setFlag(bool flag) -> ParserResult override {
9269 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(m_lambda, flag);
9270 }
9271};
9272
9273enum class Optionality { Optional, Required };
9274
9275struct Parser;
9276
9277class ParserBase {
9278 public:
9279 virtual ~ParserBase() = default;
9280 virtual auto validate() const -> Result { return Result::ok(); }
9281 virtual auto parse(std::string const& exeName, TokenStream const& tokens) const
9282 -> InternalParseResult = 0;
9283 virtual auto cardinality() const -> size_t { return 1; }
9284
9285 auto parse(Args const& args) const -> InternalParseResult {
9286 return parse(args.exeName(), TokenStream(args));
9287 }
9288};
9289
9290template <typename DerivedT> class ComposableParserImpl : public ParserBase {
9291 public:
9292 template <typename T> auto operator|(T const& other) const -> Parser;
9293
9294 template <typename T> auto operator+(T const& other) const -> Parser;
9295};
9296
9297// Common code and state for Args and Opts
9298template <typename DerivedT> class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9299 protected:
9300 Optionality m_optionality = Optionality::Optional;
9301 std::shared_ptr<BoundRef> m_ref;
9302 std::string m_hint;
9303 std::string m_description;
9304
9305 explicit ParserRefImpl(std::shared_ptr<BoundRef> const& ref) : m_ref(ref) {}
9306
9307 public:
9308 template <typename T>
9309 ParserRefImpl(T& ref, std::string const& hint)
9310 : m_ref(std::make_shared<BoundValueRef<T>>(ref)), m_hint(hint) {}
9311
9312 template <typename LambdaT>
9313 ParserRefImpl(LambdaT const& ref, std::string const& hint)
9314 : m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)), m_hint(hint) {}
9315
9316 auto operator()(std::string const& description) -> DerivedT& {
9317 m_description = description;
9318 return static_cast<DerivedT&>(*this);
9319 }
9320
9321 auto optional() -> DerivedT& {
9322 m_optionality = Optionality::Optional;
9323 return static_cast<DerivedT&>(*this);
9324 };
9325
9326 auto required() -> DerivedT& {
9327 m_optionality = Optionality::Required;
9328 return static_cast<DerivedT&>(*this);
9329 };
9330
9331 auto isOptional() const -> bool { return m_optionality == Optionality::Optional; }
9332
9333 auto cardinality() const -> size_t override {
9334 if (m_ref->isContainer())
9335 return 0;
9336 else
9337 return 1;
9338 }
9339
9340 auto hint() const -> std::string { return m_hint; }
9341};
9342
9343class ExeName : public ComposableParserImpl<ExeName> {
9344 std::shared_ptr<std::string> m_name;
9345 std::shared_ptr<BoundValueRefBase> m_ref;
9346
9347 template <typename LambdaT>
9348 static auto makeRef(LambdaT const& lambda) -> std::shared_ptr<BoundValueRefBase> {
9349 return std::make_shared<BoundLambda<LambdaT>>(lambda);
9350 }
9351
9352 public:
9353 ExeName() : m_name(std::make_shared<std::string>("<executable>")) {}
9354
9355 explicit ExeName(std::string& ref) : ExeName() {
9356 m_ref = std::make_shared<BoundValueRef<std::string>>(ref);
9357 }
9358
9359 template <typename LambdaT> explicit ExeName(LambdaT const& lambda) : ExeName() {
9360 m_ref = std::make_shared<BoundLambda<LambdaT>>(lambda);
9361 }
9362
9363 // The exe name is not parsed out of the normal tokens, but is handled
9364 // specially
9365 auto parse(std::string const&, TokenStream const& tokens) const
9366 -> InternalParseResult override {
9367 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
9368 }
9369
9370 auto name() const -> std::string { return *m_name; }
9371 auto set(std::string const& newName) -> ParserResult {
9372
9373 auto lastSlash = newName.find_last_of("\\/");
9374 auto filename = (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1);
9375
9376 *m_name = filename;
9377 if (m_ref)
9378 return m_ref->setValue(filename);
9379 else
9380 return ParserResult::ok(ParseResultType::Matched);
9381 }
9382};
9383
9384class Arg : public ParserRefImpl<Arg> {
9385 public:
9386 using ParserRefImpl::ParserRefImpl;
9387
9388 auto parse(std::string const&, TokenStream const& tokens) const
9389 -> InternalParseResult override {
9390 auto validationResult = validate();
9391 if (!validationResult)
9392 return InternalParseResult(validationResult);
9393
9394 auto remainingTokens = tokens;
9395 auto const& token = *remainingTokens;
9396 if (token.type != TokenType::Argument)
9397 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
9398
9399 assert(!m_ref->isFlag());
9400 auto valueRef = static_cast<detail::BoundValueRefBase*>(m_ref.get());
9401
9402 auto result = valueRef->setValue(remainingTokens->token);
9403 if (!result)
9404 return InternalParseResult(result);
9405 else
9406 return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens));
9407 }
9408};
9409
9410inline auto normaliseOpt(std::string const& optName) -> std::string {
9411#ifdef CATCH_PLATFORM_WINDOWS
9412 if (optName[0] == '/')
9413 return "-" + optName.substr(1);
9414 else
9415#endif
9416 return optName;
9417}
9418
9419class Opt : public ParserRefImpl<Opt> {
9420 protected:
9421 std::vector<std::string> m_optNames;
9422
9423 public:
9424 template <typename LambdaT>
9425 explicit Opt(LambdaT const& ref)
9426 : ParserRefImpl(std::make_shared<BoundFlagLambda<LambdaT>>(ref)) {}
9427
9428 explicit Opt(bool& ref) : ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {}
9429
9430 template <typename LambdaT>
9431 Opt(LambdaT const& ref, std::string const& hint) : ParserRefImpl(ref, hint) {}
9432
9433 template <typename T> Opt(T& ref, std::string const& hint) : ParserRefImpl(ref, hint) {}
9434
9435 auto operator[](std::string const& optName) -> Opt& {
9436 m_optNames.push_back(optName);
9437 return *this;
9438 }
9439
9440 auto getHelpColumns() const -> std::vector<HelpColumns> {
9441 std::ostringstream oss;
9442 bool first = true;
9443 for (auto const& opt : m_optNames) {
9444 if (first)
9445 first = false;
9446 else
9447 oss << ", ";
9448 oss << opt;
9449 }
9450 if (!m_hint.empty())
9451 oss << " <" << m_hint << ">";
9452 return {{oss.str(), m_description}};
9453 }
9454
9455 auto isMatch(std::string const& optToken) const -> bool {
9456 auto normalisedToken = normaliseOpt(optToken);
9457 for (auto const& name : m_optNames) {
9458 if (normaliseOpt(name) == normalisedToken)
9459 return true;
9460 }
9461 return false;
9462 }
9463
9464 using ParserBase::parse;
9465
9466 auto parse(std::string const&, TokenStream const& tokens) const
9467 -> InternalParseResult override {
9468 auto validationResult = validate();
9469 if (!validationResult)
9470 return InternalParseResult(validationResult);
9471
9472 auto remainingTokens = tokens;
9473 if (remainingTokens && remainingTokens->type == TokenType::Option) {
9474 auto const& token = *remainingTokens;
9475 if (isMatch(token.token)) {
9476 if (m_ref->isFlag()) {
9477 auto flagRef = static_cast<detail::BoundFlagRefBase*>(m_ref.get());
9478 auto result = flagRef->setFlag(true);
9479 if (!result)
9480 return InternalParseResult(result);
9481 if (result.value() == ParseResultType::ShortCircuitAll)
9482 return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
9483 } else {
9484 auto valueRef = static_cast<detail::BoundValueRefBase*>(m_ref.get());
9485 ++remainingTokens;
9486 if (!remainingTokens)
9487 return InternalParseResult::runtimeError("Expected argument following " +
9488 token.token);
9489 auto const& argToken = *remainingTokens;
9490 if (argToken.type != TokenType::Argument)
9491 return InternalParseResult::runtimeError("Expected argument following " +
9492 token.token);
9493 auto result = valueRef->setValue(argToken.token);
9494 if (!result)
9495 return InternalParseResult(result);
9496 if (result.value() == ParseResultType::ShortCircuitAll)
9497 return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
9498 }
9499 return InternalParseResult::ok(
9500 ParseState(ParseResultType::Matched, ++remainingTokens));
9501 }
9502 }
9503 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
9504 }
9505
9506 auto validate() const -> Result override {
9507 if (m_optNames.empty())
9508 return Result::logicError("No options supplied to Opt");
9509 for (auto const& name : m_optNames) {
9510 if (name.empty())
9511 return Result::logicError("Option name cannot be empty");
9512#ifdef CATCH_PLATFORM_WINDOWS
9513 if (name[0] != '-' && name[0] != '/')
9514 return Result::logicError("Option name must begin with '-' or '/'");
9515#else
9516 if (name[0] != '-')
9517 return Result::logicError("Option name must begin with '-'");
9518#endif
9519 }
9520 return ParserRefImpl::validate();
9521 }
9522};
9523
9524struct Help : Opt {
9525 Help(bool& showHelpFlag)
9526 : Opt([&](bool flag) {
9527 showHelpFlag = flag;
9528 return ParserResult::ok(ParseResultType::ShortCircuitAll);
9529 }) {
9530 static_cast<Opt&>(*this)("display usage information")["-?"]["-h"]["--help"].optional();
9531 }
9532};
9533
9534struct Parser : ParserBase {
9535
9536 mutable ExeName m_exeName;
9537 std::vector<Opt> m_options;
9538 std::vector<Arg> m_args;
9539
9540 auto operator|=(ExeName const& exeName) -> Parser& {
9541 m_exeName = exeName;
9542 return *this;
9543 }
9544
9545 auto operator|=(Arg const& arg) -> Parser& {
9546 m_args.push_back(arg);
9547 return *this;
9548 }
9549
9550 auto operator|=(Opt const& opt) -> Parser& {
9551 m_options.push_back(opt);
9552 return *this;
9553 }
9554
9555 auto operator|=(Parser const& other) -> Parser& {
9556 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9557 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9558 return *this;
9559 }
9560
9561 template <typename T> auto operator|(T const& other) const -> Parser {
9562 return Parser(*this) |= other;
9563 }
9564
9565 // Forward deprecated interface with '+' instead of '|'
9566 template <typename T> auto operator+=(T const& other) -> Parser& { return operator|=(other); }
9567 template <typename T> auto operator+(T const& other) const -> Parser {
9568 return operator|(other);
9569 }
9570
9571 auto getHelpColumns() const -> std::vector<HelpColumns> {
9572 std::vector<HelpColumns> cols;
9573 for (auto const& o : m_options) {
9574 auto childCols = o.getHelpColumns();
9575 cols.insert(cols.end(), childCols.begin(), childCols.end());
9576 }
9577 return cols;
9578 }
9579
9580 void writeToStream(std::ostream& os) const {
9581 if (!m_exeName.name().empty()) {
9582 os << "usage:\n" << " " << m_exeName.name() << " ";
9583 bool required = true, first = true;
9584 for (auto const& arg : m_args) {
9585 if (first)
9586 first = false;
9587 else
9588 os << " ";
9589 if (arg.isOptional() && required) {
9590 os << "[";
9591 required = false;
9592 }
9593 os << "<" << arg.hint() << ">";
9594 if (arg.cardinality() == 0)
9595 os << " ... ";
9596 }
9597 if (!required)
9598 os << "]";
9599 if (!m_options.empty())
9600 os << " options";
9601 os << "\n\nwhere options are:" << std::endl;
9602 }
9603
9604 auto rows = getHelpColumns();
9605 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9606 size_t optWidth = 0;
9607 for (auto const& cols : rows)
9608 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9609
9610 optWidth = (std::min)(optWidth, consoleWidth / 2);
9611
9612 for (auto const& cols : rows) {
9613 auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) + TextFlow::Spacer(4) +
9614 TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth);
9615 os << row << std::endl;
9616 }
9617 }
9618
9619 friend auto operator<<(std::ostream& os, Parser const& parser) -> std::ostream& {
9620 parser.writeToStream(os);
9621 return os;
9622 }
9623
9624 auto validate() const -> Result override {
9625 for (auto const& opt : m_options) {
9626 auto result = opt.validate();
9627 if (!result)
9628 return result;
9629 }
9630 for (auto const& arg : m_args) {
9631 auto result = arg.validate();
9632 if (!result)
9633 return result;
9634 }
9635 return Result::ok();
9636 }
9637
9638 using ParserBase::parse;
9639
9640 auto parse(std::string const& exeName, TokenStream const& tokens) const
9641 -> InternalParseResult override {
9642
9643 struct ParserInfo {
9644 ParserBase const* parser = nullptr;
9645 size_t count = 0;
9646 };
9647 const size_t totalParsers = m_options.size() + m_args.size();
9648 assert(totalParsers < 512);
9649 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want
9650 // to do
9651 ParserInfo parseInfos[512];
9652
9653 {
9654 size_t i = 0;
9655 for (auto const& opt : m_options)
9656 parseInfos[i++].parser = &opt;
9657 for (auto const& arg : m_args)
9658 parseInfos[i++].parser = &arg;
9659 }
9660
9661 m_exeName.set(exeName);
9662
9663 auto result = InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
9664 while (result.value().remainingTokens()) {
9665 bool tokenParsed = false;
9666
9667 for (size_t i = 0; i < totalParsers; ++i) {
9668 auto& parseInfo = parseInfos[i];
9669 if (parseInfo.parser->cardinality() == 0 ||
9670 parseInfo.count < parseInfo.parser->cardinality()) {
9671 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9672 if (!result)
9673 return result;
9674 if (result.value().type() != ParseResultType::NoMatch) {
9675 tokenParsed = true;
9676 ++parseInfo.count;
9677 break;
9678 }
9679 }
9680 }
9681
9682 if (result.value().type() == ParseResultType::ShortCircuitAll)
9683 return result;
9684 if (!tokenParsed)
9685 return InternalParseResult::runtimeError("Unrecognised token: " +
9686 result.value().remainingTokens()->token);
9687 }
9688 // !TBD Check missing required options
9689 return result;
9690 }
9691};
9692
9693template <typename DerivedT>
9694template <typename T>
9695auto ComposableParserImpl<DerivedT>::operator|(T const& other) const -> Parser {
9696 return Parser() | static_cast<DerivedT const&>(*this) | other;
9697}
9698} // namespace detail
9699
9700// A Combined parser
9701using detail::Parser;
9702
9703// A parser for options
9704using detail::Opt;
9705
9706// A parser for arguments
9707using detail::Arg;
9708
9709// Wrapper for argc, argv from main()
9710using detail::Args;
9711
9712// Specifies the name of the executable
9713using detail::ExeName;
9714
9715// Convenience wrapper for option parser that specifies the help option
9716using detail::Help;
9717
9718// enum of result types from a parse
9719using detail::ParseResultType;
9720
9721// Result type for parser operation
9722using detail::ParserResult;
9723
9724} // namespace clara
9725} // namespace Catch
9726
9727// end clara.hpp
9728#ifdef __clang__
9729#pragma clang diagnostic pop
9730#endif
9731
9732// Restore Clara's value for console width, if present
9733#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9734#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9735#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9736#endif
9737
9738// end catch_clara.h
9739namespace Catch {
9740
9741clara::Parser makeCommandLineParser(ConfigData& config);
9742
9743} // end namespace Catch
9744
9745// end catch_commandline.h
9746#include <ctime>
9747#include <fstream>
9748
9749namespace Catch {
9750
9751clara::Parser makeCommandLineParser(ConfigData& config) {
9752
9753 using namespace clara;
9754
9755 auto const setWarning = [&](std::string const& warning) {
9756 auto warningSet = [&]() {
9757 if (warning == "NoAssertions")
9758 return WarnAbout::NoAssertions;
9759
9760 if (warning == "NoTests")
9761 return WarnAbout::NoTests;
9762
9763 return WarnAbout::Nothing;
9764 }();
9765
9766 if (warningSet == WarnAbout::Nothing)
9767 return ParserResult::runtimeError("Unrecognised warning: '" + warning + "'");
9768 config.warnings = static_cast<WarnAbout::What>(config.warnings | warningSet);
9769 return ParserResult::ok(ParseResultType::Matched);
9770 };
9771 auto const loadTestNamesFromFile = [&](std::string const& filename) {
9772 std::ifstream f(filename.c_str());
9773 if (!f.is_open())
9774 return ParserResult::runtimeError("Unable to load input file: '" + filename + "'");
9775
9776 std::string line;
9777 while (std::getline(f, line)) {
9778 line = trim(line);
9779 if (!line.empty() && !startsWith(line, '#')) {
9780 if (!startsWith(line, '"'))
9781 line = '"' + line + '"';
9782 config.testsOrTags.push_back(line);
9783 config.testsOrTags.emplace_back(",");
9784 }
9785 }
9786 // Remove comma in the end
9787 if (!config.testsOrTags.empty())
9788 config.testsOrTags.erase(config.testsOrTags.end() - 1);
9789
9790 return ParserResult::ok(ParseResultType::Matched);
9791 };
9792 auto const setTestOrder = [&](std::string const& order) {
9793 if (startsWith("declared", order))
9794 config.runOrder = RunTests::InDeclarationOrder;
9795 else if (startsWith("lexical", order))
9796 config.runOrder = RunTests::InLexicographicalOrder;
9797 else if (startsWith("random", order))
9798 config.runOrder = RunTests::InRandomOrder;
9799 else
9800 return clara::ParserResult::runtimeError("Unrecognised ordering: '" + order + "'");
9801 return ParserResult::ok(ParseResultType::Matched);
9802 };
9803 auto const setRngSeed = [&](std::string const& seed) {
9804 if (seed != "time")
9805 return clara::detail::convertInto(seed, config.rngSeed);
9806 config.rngSeed = static_cast<unsigned int>(std::time(nullptr));
9807 return ParserResult::ok(ParseResultType::Matched);
9808 };
9809 auto const setColourUsage = [&](std::string const& useColour) {
9810 auto mode = toLower(useColour);
9811
9812 if (mode == "yes")
9813 config.useColour = UseColour::Yes;
9814 else if (mode == "no")
9815 config.useColour = UseColour::No;
9816 else if (mode == "auto")
9817 config.useColour = UseColour::Auto;
9818 else
9819 return ParserResult::runtimeError("colour mode must be one of: auto, yes or no. '" +
9820 useColour + "' not recognised");
9821 return ParserResult::ok(ParseResultType::Matched);
9822 };
9823 auto const setWaitForKeypress = [&](std::string const& keypress) {
9824 auto keypressLc = toLower(keypress);
9825 if (keypressLc == "never")
9826 config.waitForKeypress = WaitForKeypress::Never;
9827 else if (keypressLc == "start")
9828 config.waitForKeypress = WaitForKeypress::BeforeStart;
9829 else if (keypressLc == "exit")
9830 config.waitForKeypress = WaitForKeypress::BeforeExit;
9831 else if (keypressLc == "both")
9832 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9833 else
9834 return ParserResult::runtimeError(
9835 "keypress argument must be one of: never, start, exit or both. '" + keypress +
9836 "' not recognised");
9837 return ParserResult::ok(ParseResultType::Matched);
9838 };
9839 auto const setVerbosity = [&](std::string const& verbosity) {
9840 auto lcVerbosity = toLower(verbosity);
9841 if (lcVerbosity == "quiet")
9842 config.verbosity = Verbosity::Quiet;
9843 else if (lcVerbosity == "normal")
9844 config.verbosity = Verbosity::Normal;
9845 else if (lcVerbosity == "high")
9846 config.verbosity = Verbosity::High;
9847 else
9848 return ParserResult::runtimeError("Unrecognised verbosity, '" + verbosity + "'");
9849 return ParserResult::ok(ParseResultType::Matched);
9850 };
9851 auto const setReporter = [&](std::string const& reporter) {
9852 IReporterRegistry::FactoryMap const& factories =
9853 getRegistryHub().getReporterRegistry().getFactories();
9854
9855 auto lcReporter = toLower(reporter);
9856 auto result = factories.find(lcReporter);
9857
9858 if (factories.end() != result)
9859 config.reporterName = lcReporter;
9860 else
9861 return ParserResult::runtimeError("Unrecognized reporter, '" + reporter +
9862 "'. Check available with --list-reporters");
9863 return ParserResult::ok(ParseResultType::Matched);
9864 };
9865
9866 auto cli =
9867 ExeName(config.processName) | Help(config.showHelp) |
9868 Opt(config.listTests)["-l"]["--list-tests"]("list all/matching test cases") |
9869 Opt(config.listTags)["-t"]["--list-tags"]("list all/matching tags") |
9870 Opt(config.showSuccessfulTests)["-s"]["--success"]("include successful tests in output") |
9871 Opt(config.shouldDebugBreak)["-b"]["--break"]("break into debugger on failure") |
9872 Opt(config.noThrow)["-e"]["--nothrow"]("skip exception tests") |
9873 Opt(config.showInvisibles)["-i"]["--invisibles"]("show invisibles (tabs, newlines)") |
9874 Opt(config.outputFilename, "filename")["-o"]["--out"]("output filename") |
9875 Opt(setReporter, "name")["-r"]["--reporter"]("reporter to use (defaults to console)") |
9876 Opt(config.name, "name")["-n"]["--name"]("suite name") |
9877 Opt([&](bool) { config.abortAfter = 1; })["-a"]["--abort"]("abort at first failure") |
9878 Opt([&](int x) { config.abortAfter = x; },
9879 "no. failures")["-x"]["--abortx"]("abort after x failures") |
9880 Opt(setWarning, "warning name")["-w"]["--warn"]("enable warnings") |
9881 Opt(
9882 [&](bool flag) {
9883 config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never;
9884 },
9885 "yes|no")["-d"]["--durations"]("show test durations") |
9886 Opt(config.minDuration, "seconds")["-D"]["--min-duration"](
9887 "show test durations for tests taking at least the given number of "
9888 "seconds") |
9889 Opt(loadTestNamesFromFile,
9890 "filename")["-f"]["--input-file"]("load test names to run from a file") |
9891 Opt(config.filenamesAsTags)["-#"]["--filenames-as-tags"]("adds a tag for the filename") |
9892 Opt(config.sectionsToRun, "section name")["-c"]["--section"]("specify section to run") |
9893 Opt(setVerbosity, "quiet|normal|high")["-v"]["--verbosity"]("set output verbosity") |
9894 Opt(config.listTestNamesOnly)["--list-test-names-only"](
9895 "list all/matching test cases names only") |
9896 Opt(config.listReporters)["--list-reporters"]("list all reporters") |
9897 Opt(setTestOrder, "decl|lex|rand")["--order"]("test case order (defaults to decl)") |
9898 Opt(setRngSeed, "'time'|number")["--rng-seed"]("set a specific seed for random numbers") |
9899 Opt(setColourUsage, "yes|no")["--use-colour"]("should output be colourised") |
9900 Opt(config.libIdentify)["--libidentify"](
9901 "report name and version according to libidentify standard") |
9902 Opt(setWaitForKeypress,
9903 "never|start|exit|both")["--wait-for-keypress"]("waits for a keypress before exiting") |
9904 Opt(config.benchmarkSamples,
9905 "samples")["--benchmark-samples"]("number of samples to collect (default: 100)") |
9906 Opt(config.benchmarkResamples, "resamples")["--benchmark-resamples"](
9907 "number of resamples for the bootstrap (default: 100000)") |
9908 Opt(config.benchmarkConfidenceInterval,
9909 "confidence interval")["--benchmark-confidence-interval"](
9910 "confidence interval for the bootstrap (between 0 and 1, default: "
9911 "0.95)") |
9912 Opt(config.benchmarkNoAnalysis)["--benchmark-no-analysis"](
9913 "perform only measurements; do not perform any analysis") |
9914 Opt(config.benchmarkWarmupTime, "benchmarkWarmupTime")["--benchmark-warmup-time"](
9915 "amount of time in milliseconds spent on warming up each test "
9916 "(default: 100)") |
9917 Arg(config.testsOrTags, "test name|pattern|tags")("which test or tests to use");
9918
9919 return cli;
9920}
9921
9922} // end namespace Catch
9923// end catch_commandline.cpp
9924// start catch_common.cpp
9925
9926#include <cstring>
9927#include <ostream>
9928
9929namespace Catch {
9930
9931bool SourceLineInfo::operator==(SourceLineInfo const& other) const noexcept {
9932 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9933}
9934bool SourceLineInfo::operator<(SourceLineInfo const& other) const noexcept {
9935 // We can assume that the same file will usually have the same pointer.
9936 // Thus, if the pointers are the same, there is no point in calling the strcmp
9937 return line < other.line ||
9938 (line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9939}
9940
9941std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info) {
9942#ifndef __GNUG__
9943 os << info.file << '(' << info.line << ')';
9944#else
9945 os << info.file << ':' << info.line;
9946#endif
9947 return os;
9948}
9949
9950std::string StreamEndStop::operator+() const {
9951 return std::string();
9952}
9953
9954NonCopyable::NonCopyable() = default;
9955NonCopyable::~NonCopyable() = default;
9956
9957} // namespace Catch
9958// end catch_common.cpp
9959// start catch_config.cpp
9960
9961namespace Catch {
9962
9963Config::Config(ConfigData const& data) : m_data(data), m_stream(openStream()) {
9964 // We need to trim filter specs to avoid trouble with superfluous
9965 // whitespace (esp. important for bdd macros, as those are manually
9966 // aligned with whitespace).
9967
9968 for (auto& elem : m_data.testsOrTags) {
9969 elem = trim(elem);
9970 }
9971 for (auto& elem : m_data.sectionsToRun) {
9972 elem = trim(elem);
9973 }
9974
9975 TestSpecParser parser(ITagAliasRegistry::get());
9976 if (!m_data.testsOrTags.empty()) {
9977 m_hasTestFilters = true;
9978 for (auto const& testOrTags : m_data.testsOrTags) {
9979 parser.parse(testOrTags);
9980 }
9981 }
9982 m_testSpec = parser.testSpec();
9983}
9984
9985std::string const& Config::getFilename() const {
9986 return m_data.outputFilename;
9987}
9988
9989bool Config::listTests() const {
9990 return m_data.listTests;
9991}
9992bool Config::listTestNamesOnly() const {
9993 return m_data.listTestNamesOnly;
9994}
9995bool Config::listTags() const {
9996 return m_data.listTags;
9997}
9998bool Config::listReporters() const {
9999 return m_data.listReporters;
10000}
10001
10002std::string Config::getProcessName() const {
10003 return m_data.processName;
10004}
10005std::string const& Config::getReporterName() const {
10006 return m_data.reporterName;
10007}
10008
10009std::vector<std::string> const& Config::getTestsOrTags() const {
10010 return m_data.testsOrTags;
10011}
10012std::vector<std::string> const& Config::getSectionsToRun() const {
10013 return m_data.sectionsToRun;
10014}
10015
10016TestSpec const& Config::testSpec() const {
10017 return m_testSpec;
10018}
10019bool Config::hasTestFilters() const {
10020 return m_hasTestFilters;
10021}
10022
10023bool Config::showHelp() const {
10024 return m_data.showHelp;
10025}
10026
10027// IConfig interface
10028bool Config::allowThrows() const {
10029 return !m_data.noThrow;
10030}
10031std::ostream& Config::stream() const {
10032 return m_stream->stream();
10033}
10034std::string Config::name() const {
10035 return m_data.name.empty() ? m_data.processName : m_data.name;
10036}
10037bool Config::includeSuccessfulResults() const {
10038 return m_data.showSuccessfulTests;
10039}
10040bool Config::warnAboutMissingAssertions() const {
10041 return !!(m_data.warnings & WarnAbout::NoAssertions);
10042}
10043bool Config::warnAboutNoTests() const {
10044 return !!(m_data.warnings & WarnAbout::NoTests);
10045}
10046ShowDurations::OrNot Config::showDurations() const {
10047 return m_data.showDurations;
10048}
10049double Config::minDuration() const {
10050 return m_data.minDuration;
10051}
10052RunTests::InWhatOrder Config::runOrder() const {
10053 return m_data.runOrder;
10054}
10055unsigned int Config::rngSeed() const {
10056 return m_data.rngSeed;
10057}
10058UseColour::YesOrNo Config::useColour() const {
10059 return m_data.useColour;
10060}
10061bool Config::shouldDebugBreak() const {
10062 return m_data.shouldDebugBreak;
10063}
10064int Config::abortAfter() const {
10065 return m_data.abortAfter;
10066}
10067bool Config::showInvisibles() const {
10068 return m_data.showInvisibles;
10069}
10070Verbosity Config::verbosity() const {
10071 return m_data.verbosity;
10072}
10073
10074bool Config::benchmarkNoAnalysis() const {
10075 return m_data.benchmarkNoAnalysis;
10076}
10077int Config::benchmarkSamples() const {
10078 return m_data.benchmarkSamples;
10079}
10080double Config::benchmarkConfidenceInterval() const {
10081 return m_data.benchmarkConfidenceInterval;
10082}
10083unsigned int Config::benchmarkResamples() const {
10084 return m_data.benchmarkResamples;
10085}
10086std::chrono::milliseconds Config::benchmarkWarmupTime() const {
10087 return std::chrono::milliseconds(m_data.benchmarkWarmupTime);
10088}
10089
10090IStream const* Config::openStream() {
10091 return Catch::makeStream(m_data.outputFilename);
10092}
10093
10094} // end namespace Catch
10095// end catch_config.cpp
10096// start catch_console_colour.cpp
10097
10098#if defined(__clang__)
10099#pragma clang diagnostic push
10100#pragma clang diagnostic ignored "-Wexit-time-destructors"
10101#endif
10102
10103// start catch_errno_guard.h
10104
10105namespace Catch {
10106
10107class ErrnoGuard {
10108 public:
10109 ErrnoGuard();
10110 ~ErrnoGuard();
10111
10112 private:
10113 int m_oldErrno;
10114};
10115
10116} // namespace Catch
10117
10118// end catch_errno_guard.h
10119// start catch_windows_h_proxy.h
10120
10121#if defined(CATCH_PLATFORM_WINDOWS)
10122
10123#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10124#define CATCH_DEFINED_NOMINMAX
10125#define NOMINMAX
10126#endif
10127#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10128#define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10129#define WIN32_LEAN_AND_MEAN
10130#endif
10131
10132#ifdef __AFXDLL
10133#include <AfxWin.h>
10134#else
10135#include <windows.h>
10136#endif
10137
10138#ifdef CATCH_DEFINED_NOMINMAX
10139#undef NOMINMAX
10140#endif
10141#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10142#undef WIN32_LEAN_AND_MEAN
10143#endif
10144
10145#endif // defined(CATCH_PLATFORM_WINDOWS)
10146
10147// end catch_windows_h_proxy.h
10148#include <sstream>
10149
10150namespace Catch {
10151namespace {
10152
10153struct IColourImpl {
10154 virtual ~IColourImpl() = default;
10155 virtual void use(Colour::Code _colourCode) = 0;
10156};
10157
10158struct NoColourImpl : IColourImpl {
10159 void use(Colour::Code) override {}
10160
10161 static IColourImpl* instance() {
10162 static NoColourImpl s_instance;
10163 return &s_instance;
10164 }
10165};
10166
10167} // namespace
10168} // namespace Catch
10169
10170#if !defined(CATCH_CONFIG_COLOUR_NONE) && !defined(CATCH_CONFIG_COLOUR_WINDOWS) && \
10171 !defined(CATCH_CONFIG_COLOUR_ANSI)
10172#ifdef CATCH_PLATFORM_WINDOWS
10173#define CATCH_CONFIG_COLOUR_WINDOWS
10174#else
10175#define CATCH_CONFIG_COLOUR_ANSI
10176#endif
10177#endif
10178
10179#if defined(CATCH_CONFIG_COLOUR_WINDOWS)
10180
10181namespace Catch {
10182namespace {
10183
10184class Win32ColourImpl : public IColourImpl {
10185 public:
10186 Win32ColourImpl() : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)) {
10187 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10188 GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo);
10189 originalForegroundAttributes =
10190 csbiInfo.wAttributes &
10191 ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
10192 originalBackgroundAttributes =
10193 csbiInfo.wAttributes &
10194 ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
10195 }
10196
10197 void use(Colour::Code _colourCode) override {
10198 switch (_colourCode) {
10199 case Colour::None:
10200 return setTextAttribute(originalForegroundAttributes);
10201 case Colour::White:
10202 return setTextAttribute(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
10203 case Colour::Red:
10204 return setTextAttribute(FOREGROUND_RED);
10205 case Colour::Green:
10206 return setTextAttribute(FOREGROUND_GREEN);
10207 case Colour::Blue:
10208 return setTextAttribute(FOREGROUND_BLUE);
10209 case Colour::Cyan:
10210 return setTextAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN);
10211 case Colour::Yellow:
10212 return setTextAttribute(FOREGROUND_RED | FOREGROUND_GREEN);
10213 case Colour::Grey:
10214 return setTextAttribute(0);
10215
10216 case Colour::LightGrey:
10217 return setTextAttribute(FOREGROUND_INTENSITY);
10218 case Colour::BrightRed:
10219 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED);
10220 case Colour::BrightGreen:
10221 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN);
10222 case Colour::BrightWhite:
10223 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED |
10224 FOREGROUND_BLUE);
10225 case Colour::BrightYellow:
10226 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
10227
10228 case Colour::Bright:
10229 CATCH_INTERNAL_ERROR("not a colour");
10230
10231 default:
10232 CATCH_ERROR("Unknown colour requested");
10233 }
10234 }
10235
10236 private:
10237 void setTextAttribute(WORD _textAttribute) {
10238 SetConsoleTextAttribute(stdoutHandle, _textAttribute | originalBackgroundAttributes);
10239 }
10240 HANDLE stdoutHandle;
10241 WORD originalForegroundAttributes;
10242 WORD originalBackgroundAttributes;
10243};
10244
10245IColourImpl* platformColourInstance() {
10246 static Win32ColourImpl s_instance;
10247
10248 IConfigPtr config = getCurrentContext().getConfig();
10249 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10250 if (colourMode == UseColour::Auto)
10251 colourMode = UseColour::Yes;
10252 return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance();
10253}
10254
10255} // namespace
10256} // end namespace Catch
10257
10258#elif defined(CATCH_CONFIG_COLOUR_ANSI)
10259
10260#include <unistd.h>
10261
10262namespace Catch {
10263namespace {
10264
10265// use POSIX/ ANSI console terminal codes
10266// Thanks to Adam Strzelecki for original contribution
10267// (http://github.com/nanoant)
10268// https://github.com/philsquared/Catch/pull/131
10269class PosixColourImpl : public IColourImpl {
10270 public:
10271 void use(Colour::Code _colourCode) override {
10272 switch (_colourCode) {
10273 case Colour::None:
10274 case Colour::White:
10275 return setColour("[0m");
10276 case Colour::Red:
10277 return setColour("[0;31m");
10278 case Colour::Green:
10279 return setColour("[0;32m");
10280 case Colour::Blue:
10281 return setColour("[0;34m");
10282 case Colour::Cyan:
10283 return setColour("[0;36m");
10284 case Colour::Yellow:
10285 return setColour("[0;33m");
10286 case Colour::Grey:
10287 return setColour("[1;30m");
10288
10289 case Colour::LightGrey:
10290 return setColour("[0;37m");
10291 case Colour::BrightRed:
10292 return setColour("[1;31m");
10293 case Colour::BrightGreen:
10294 return setColour("[1;32m");
10295 case Colour::BrightWhite:
10296 return setColour("[1;37m");
10297 case Colour::BrightYellow:
10298 return setColour("[1;33m");
10299
10300 case Colour::Bright:
10301 CATCH_INTERNAL_ERROR("not a colour");
10302 default:
10303 CATCH_INTERNAL_ERROR("Unknown colour requested");
10304 }
10305 }
10306 static IColourImpl* instance() {
10307 static PosixColourImpl s_instance;
10308 return &s_instance;
10309 }
10310
10311 private:
10312 void setColour(const char* _escapeCode) {
10313 getCurrentContext().getConfig()->stream() << '\033' << _escapeCode;
10314 }
10315};
10316
10317bool useColourOnPlatform() {
10318 return
10319#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10320 !isDebuggerActive() &&
10321#endif
10322#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10323 isatty(STDOUT_FILENO)
10324#else
10325 false
10326#endif
10327 ;
10328}
10329IColourImpl* platformColourInstance() {
10330 ErrnoGuard guard;
10331 IConfigPtr config = getCurrentContext().getConfig();
10332 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10333 if (colourMode == UseColour::Auto)
10334 colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No;
10335 return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance();
10336}
10337
10338} // namespace
10339} // end namespace Catch
10340
10341#else // not Windows or ANSI ///////////////////////////////////////////////
10342
10343namespace Catch {
10344
10345static IColourImpl* platformColourInstance() {
10346 return NoColourImpl::instance();
10347}
10348
10349} // end namespace Catch
10350
10351#endif // Windows/ ANSI/ None
10352
10353namespace Catch {
10354
10355Colour::Colour(Code _colourCode) {
10356 use(_colourCode);
10357}
10358Colour::Colour(Colour&& other) noexcept {
10359 m_moved = other.m_moved;
10360 other.m_moved = true;
10361}
10362Colour& Colour::operator=(Colour&& other) noexcept {
10363 m_moved = other.m_moved;
10364 other.m_moved = true;
10365 return *this;
10366}
10367
10368Colour::~Colour() {
10369 if (!m_moved)
10370 use(None);
10371}
10372
10373void Colour::use(Code _colourCode) {
10374 static IColourImpl* impl = platformColourInstance();
10375 // Strictly speaking, this cannot possibly happen.
10376 // However, under some conditions it does happen (see #1626),
10377 // and this change is small enough that we can let practicality
10378 // triumph over purity in this case.
10379 if (impl != nullptr) {
10380 impl->use(_colourCode);
10381 }
10382}
10383
10384std::ostream& operator<<(std::ostream& os, Colour const&) {
10385 return os;
10386}
10387
10388} // end namespace Catch
10389
10390#if defined(__clang__)
10391#pragma clang diagnostic pop
10392#endif
10393
10394// end catch_console_colour.cpp
10395// start catch_context.cpp
10396
10397namespace Catch {
10398
10399class Context : public IMutableContext, NonCopyable {
10400
10401 public: // IContext
10402 IResultCapture* getResultCapture() override { return m_resultCapture; }
10403 IRunner* getRunner() override { return m_runner; }
10404
10405 IConfigPtr const& getConfig() const override { return m_config; }
10406
10407 ~Context() override;
10408
10409 public: // IMutableContext
10410 void setResultCapture(IResultCapture* resultCapture) override {
10411 m_resultCapture = resultCapture;
10412 }
10413 void setRunner(IRunner* runner) override { m_runner = runner; }
10414 void setConfig(IConfigPtr const& config) override { m_config = config; }
10415
10416 friend IMutableContext& getCurrentMutableContext();
10417
10418 private:
10419 IConfigPtr m_config;
10420 IRunner* m_runner = nullptr;
10421 IResultCapture* m_resultCapture = nullptr;
10422};
10423
10424IMutableContext* IMutableContext::currentContext = nullptr;
10425
10426void IMutableContext::createContext() {
10427 currentContext = new Context();
10428}
10429
10430void cleanUpContext() {
10431 delete IMutableContext::currentContext;
10432 IMutableContext::currentContext = nullptr;
10433}
10434IContext::~IContext() = default;
10435IMutableContext::~IMutableContext() = default;
10436Context::~Context() = default;
10437
10438SimplePcg32& rng() {
10439 static SimplePcg32 s_rng;
10440 return s_rng;
10441}
10442
10443} // namespace Catch
10444// end catch_context.cpp
10445// start catch_debug_console.cpp
10446
10447// start catch_debug_console.h
10448
10449#include <string>
10450
10451namespace Catch {
10452void writeToDebugConsole(std::string const& text);
10453}
10454
10455// end catch_debug_console.h
10456#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10457#include <android/log.h>
10458
10459namespace Catch {
10460void writeToDebugConsole(std::string const& text) {
10461 __android_log_write(ANDROID_LOG_DEBUG, "Catch", text.c_str());
10462}
10463} // namespace Catch
10464
10465#elif defined(CATCH_PLATFORM_WINDOWS)
10466
10467namespace Catch {
10468void writeToDebugConsole(std::string const& text) {
10469 ::OutputDebugStringA(text.c_str());
10470}
10471} // namespace Catch
10472
10473#else
10474
10475namespace Catch {
10476void writeToDebugConsole(std::string const& text) {
10477 // !TBD: Need a version for Mac/ XCode and other IDEs
10478 Catch::cout() << text;
10479}
10480} // namespace Catch
10481
10482#endif // Platform
10483// end catch_debug_console.cpp
10484// start catch_debugger.cpp
10485
10486#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10487
10488#include <cassert>
10489#include <cstddef>
10490#include <ostream>
10491#include <sys/types.h>
10492#include <unistd.h>
10493
10494#ifdef __apple_build_version__
10495// These headers will only compile with AppleClang (XCode)
10496// For other compilers (Clang, GCC, ... ) we need to exclude them
10497#include <sys/sysctl.h>
10498#endif
10499
10500namespace Catch {
10501#ifdef __apple_build_version__
10502// The following function is taken directly from the following technical note:
10503// https://developer.apple.com/library/archive/qa/qa1361/_index.html
10504
10505// Returns true if the current process is being debugged (either
10506// running under the debugger or has a debugger attached post facto).
10507bool isDebuggerActive() {
10508 int mib[4];
10509 struct kinfo_proc info;
10510 std::size_t size;
10511
10512 // Initialize the flags so that, if sysctl fails for some bizarre
10513 // reason, we get a predictable result.
10514
10515 info.kp_proc.p_flag = 0;
10516
10517 // Initialize mib, which tells sysctl the info we want, in this case
10518 // we're looking for information about a specific process ID.
10519
10520 mib[0] = CTL_KERN;
10521 mib[1] = KERN_PROC;
10522 mib[2] = KERN_PROC_PID;
10523 mib[3] = getpid();
10524
10525 // Call sysctl.
10526
10527 size = sizeof(info);
10528 if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0) {
10529 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if "
10530 "debugger is active **\n"
10531 << std::endl;
10532 return false;
10533 }
10534
10535 // We're being debugged if the P_TRACED flag is set.
10536
10537 return ((info.kp_proc.p_flag & P_TRACED) != 0);
10538}
10539#else
10540bool isDebuggerActive() {
10541 // We need to find another way to determine this for non-appleclang compilers
10542 // on macOS
10543 return false;
10544}
10545#endif
10546} // namespace Catch
10547
10548#elif defined(CATCH_PLATFORM_LINUX)
10549#include <fstream>
10550#include <string>
10551
10552namespace Catch {
10553// The standard POSIX way of detecting a debugger is to attempt to
10554// ptrace() the process, but this needs to be done from a child and not
10555// this process itself to still allow attaching to this process later
10556// if wanted, so is rather heavy. Under Linux we have the PID of the
10557// "debugger" (which doesn't need to be gdb, of course, it could also
10558// be strace, for example) in /proc/$PID/status, so just get it from
10559// there instead.
10560bool isDebuggerActive() {
10561 // Libstdc++ has a bug, where std::ifstream sets errno to 0
10562 // This way our users can properly assert over errno values
10563 ErrnoGuard guard;
10564 std::ifstream in("/proc/self/status");
10565 for (std::string line; std::getline(in, line);) {
10566 static const int PREFIX_LEN = 11;
10567 if (line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) {
10568 // We're traced if the PID is not 0 and no other PID starts
10569 // with 0 digit, so it's enough to check for just a single
10570 // character.
10571 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10572 }
10573 }
10574
10575 return false;
10576}
10577} // namespace Catch
10578#elif defined(_MSC_VER)
10579extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10580namespace Catch {
10581bool isDebuggerActive() {
10582 return IsDebuggerPresent() != 0;
10583}
10584} // namespace Catch
10585#elif defined(__MINGW32__)
10586extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10587namespace Catch {
10588bool isDebuggerActive() {
10589 return IsDebuggerPresent() != 0;
10590}
10591} // namespace Catch
10592#else
10593namespace Catch {
10594bool isDebuggerActive() {
10595 return false;
10596}
10597} // namespace Catch
10598#endif // Platform
10599// end catch_debugger.cpp
10600// start catch_decomposer.cpp
10601
10602namespace Catch {
10603
10604ITransientExpression::~ITransientExpression() = default;
10605
10606void formatReconstructedExpression(std::ostream& os, std::string const& lhs, StringRef op,
10607 std::string const& rhs) {
10608 if (lhs.size() + rhs.size() < 40 && lhs.find('\n') == std::string::npos &&
10609 rhs.find('\n') == std::string::npos)
10610 os << lhs << " " << op << " " << rhs;
10611 else
10612 os << lhs << "\n" << op << "\n" << rhs;
10613}
10614} // namespace Catch
10615// end catch_decomposer.cpp
10616// start catch_enforce.cpp
10617
10618#include <stdexcept>
10619
10620namespace Catch {
10621#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && \
10622 !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10623[[noreturn]]
10624void throw_exception(std::exception const& e) {
10625 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10626 << "The message was: " << e.what() << '\n';
10627 std::terminate();
10628}
10629#endif
10630
10631[[noreturn]]
10632void throw_logic_error(std::string const& msg) {
10633 throw_exception(std::logic_error(msg));
10634}
10635
10636[[noreturn]]
10637void throw_domain_error(std::string const& msg) {
10638 throw_exception(std::domain_error(msg));
10639}
10640
10641[[noreturn]]
10642void throw_runtime_error(std::string const& msg) {
10643 throw_exception(std::runtime_error(msg));
10644}
10645
10646} // namespace Catch
10647// end catch_enforce.cpp
10648// start catch_enum_values_registry.cpp
10649// start catch_enum_values_registry.h
10650
10651#include <memory>
10652#include <vector>
10653
10654namespace Catch {
10655
10656namespace Detail {
10657
10658std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, StringRef allValueNames,
10659 std::vector<int> const& values);
10660
10661class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10662
10663 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10664
10665 EnumInfo const& registerEnum(StringRef enumName, StringRef allEnums,
10666 std::vector<int> const& values) override;
10667};
10668
10669std::vector<StringRef> parseEnums(StringRef enums);
10670
10671} // namespace Detail
10672
10673} // namespace Catch
10674
10675// end catch_enum_values_registry.h
10676
10677#include <cassert>
10678#include <map>
10679
10680namespace Catch {
10681
10682IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10683
10684namespace Detail {
10685
10686namespace {
10687// Extracts the actual name part of an enum instance
10688// In other words, it returns the Blue part of Bikeshed::Colour::Blue
10689StringRef extractInstanceName(StringRef enumInstance) {
10690 // Find last occurrence of ":"
10691 size_t name_start = enumInstance.size();
10692 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
10693 --name_start;
10694 }
10695 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10696}
10697} // namespace
10698
10699std::vector<StringRef> parseEnums(StringRef enums) {
10700 auto enumValues = splitStringRef(enums, ',');
10701 std::vector<StringRef> parsed;
10702 parsed.reserve(enumValues.size());
10703 for (auto const& enumValue : enumValues) {
10704 parsed.push_back(trim(extractInstanceName(enumValue)));
10705 }
10706 return parsed;
10707}
10708
10709EnumInfo::~EnumInfo() {}
10710
10711StringRef EnumInfo::lookup(int value) const {
10712 for (auto const& valueToName : m_values) {
10713 if (valueToName.first == value)
10714 return valueToName.second;
10715 }
10716 return "{** unexpected enum value **}"_sr;
10717}
10718
10719std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, StringRef allValueNames,
10720 std::vector<int> const& values) {
10721 std::unique_ptr<EnumInfo> enumInfo(new EnumInfo);
10722 enumInfo->m_name = enumName;
10723 enumInfo->m_values.reserve(values.size());
10724
10725 const auto valueNames = Catch::Detail::parseEnums(allValueNames);
10726 assert(valueNames.size() == values.size());
10727 std::size_t i = 0;
10728 for (auto value : values)
10729 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10730
10731 return enumInfo;
10732}
10733
10734EnumInfo const& EnumValuesRegistry::registerEnum(StringRef enumName, StringRef allValueNames,
10735 std::vector<int> const& values) {
10736 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10737 return *m_enumInfos.back();
10738}
10739
10740} // namespace Detail
10741} // namespace Catch
10742
10743// end catch_enum_values_registry.cpp
10744// start catch_errno_guard.cpp
10745
10746#include <cerrno>
10747
10748namespace Catch {
10749ErrnoGuard::ErrnoGuard() : m_oldErrno(errno) {}
10750ErrnoGuard::~ErrnoGuard() {
10751 errno = m_oldErrno;
10752}
10753} // namespace Catch
10754// end catch_errno_guard.cpp
10755// start catch_exception_translator_registry.cpp
10756
10757// start catch_exception_translator_registry.h
10758
10759#include <memory>
10760#include <string>
10761#include <vector>
10762
10763namespace Catch {
10764
10765class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10766 public:
10767 ~ExceptionTranslatorRegistry();
10768 virtual void registerTranslator(const IExceptionTranslator* translator);
10769 std::string translateActiveException() const override;
10770 std::string tryTranslators() const;
10771
10772 private:
10773 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10774};
10775} // namespace Catch
10776
10777// end catch_exception_translator_registry.h
10778#ifdef __OBJC__
10779#import "Foundation/Foundation.h"
10780#endif
10781
10782namespace Catch {
10783
10784ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {}
10785
10786void ExceptionTranslatorRegistry::registerTranslator(const IExceptionTranslator* translator) {
10787 m_translators.push_back(std::unique_ptr<const IExceptionTranslator>(translator));
10788}
10789
10790#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10791std::string ExceptionTranslatorRegistry::translateActiveException() const {
10792 try {
10793#ifdef __OBJC__
10794 // In Objective-C try objective-c exceptions first
10795 @try {
10796 return tryTranslators();
10797 } @catch (NSException* exception) {
10798 return Catch::Detail::stringify([exception description]);
10799 }
10800#else
10801 // Compiling a mixed mode project with MSVC means that CLR
10802 // exceptions will be caught in (...) as well. However, these
10803 // do not fill-in std::current_exception and thus lead to crash
10804 // when attempting rethrow.
10805 // /EHa switch also causes structured exceptions to be caught
10806 // here, but they fill-in current_exception properly, so
10807 // at worst the output should be a little weird, instead of
10808 // causing a crash.
10809 if (std::current_exception() == nullptr) {
10810 return "Non C++ exception. Possibly a CLR exception.";
10811 }
10812 return tryTranslators();
10813#endif
10814 } catch (TestFailureException&) {
10815 std::rethrow_exception(std::current_exception());
10816 } catch (std::exception& ex) {
10817 return ex.what();
10818 } catch (std::string& msg) {
10819 return msg;
10820 } catch (const char* msg) {
10821 return msg;
10822 } catch (...) {
10823 return "Unknown exception";
10824 }
10825}
10826
10827std::string ExceptionTranslatorRegistry::tryTranslators() const {
10828 if (m_translators.empty()) {
10829 std::rethrow_exception(std::current_exception());
10830 } else {
10831 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10832 }
10833}
10834
10835#else // ^^ Exceptions are enabled // Exceptions are disabled vv
10836std::string ExceptionTranslatorRegistry::translateActiveException() const {
10837 CATCH_INTERNAL_ERROR("Attempted to translate active exception under "
10838 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10839}
10840
10841std::string ExceptionTranslatorRegistry::tryTranslators() const {
10842 CATCH_INTERNAL_ERROR("Attempted to use exception translators under "
10843 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10844}
10845#endif
10846
10847} // namespace Catch
10848// end catch_exception_translator_registry.cpp
10849// start catch_fatal_condition.cpp
10850
10851#include <algorithm>
10852
10853#if !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
10854
10855namespace Catch {
10856
10857// If neither SEH nor signal handling is required, the handler impls
10858// do not have to do anything, and can be empty.
10859void FatalConditionHandler::engage_platform() {}
10860void FatalConditionHandler::disengage_platform() {}
10861FatalConditionHandler::FatalConditionHandler() = default;
10862FatalConditionHandler::~FatalConditionHandler() = default;
10863
10864} // end namespace Catch
10865
10866#endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
10867
10868#if defined(CATCH_CONFIG_WINDOWS_SEH) && defined(CATCH_CONFIG_POSIX_SIGNALS)
10869#error \
10870 "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10871#endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
10872
10873#if defined(CATCH_CONFIG_WINDOWS_SEH) || defined(CATCH_CONFIG_POSIX_SIGNALS)
10874
10875namespace {
10877void reportFatal(char const* const message) {
10878 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition(message);
10879}
10880
10884constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10885} // end unnamed namespace
10886
10887#endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
10888
10889#if defined(CATCH_CONFIG_WINDOWS_SEH)
10890
10891namespace Catch {
10892
10893struct SignalDefs {
10894 DWORD id;
10895 const char* name;
10896};
10897
10898// There is no 1-1 mapping between signals and windows exceptions.
10899// Windows can easily distinguish between SO and SigSegV,
10900// but SigInt, SigTerm, etc are handled differently.
10901static SignalDefs signalDefs[] = {
10902 {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal"},
10903 {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"},
10904 {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal"},
10905 {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"},
10906};
10907
10908static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10909 for (auto const& def : signalDefs) {
10910 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10911 reportFatal(def.name);
10912 }
10913 }
10914 // If its not an exception we care about, pass it along.
10915 // This stops us from eating debugger breaks etc.
10916 return EXCEPTION_CONTINUE_SEARCH;
10917}
10918
10919// Since we do not support multiple instantiations, we put these
10920// into global variables and rely on cleaning them up in outlined
10921// constructors/destructors
10922static PVOID exceptionHandlerHandle = nullptr;
10923
10924// For MSVC, we reserve part of the stack memory for handling
10925// memory overflow structured exception.
10926FatalConditionHandler::FatalConditionHandler() {
10927 ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
10928 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10929 // We do not want to fully error out, because needing
10930 // the stack reserve should be rare enough anyway.
10931 Catch::cerr() << "Failed to reserve piece of stack."
10932 << " Stack overflows will not be reported successfully.";
10933 }
10934}
10935
10936// We do not attempt to unset the stack guarantee, because
10937// Windows does not support lowering the stack size guarantee.
10938FatalConditionHandler::~FatalConditionHandler() = default;
10939
10940void FatalConditionHandler::engage_platform() {
10941 // Register as first handler in current chain
10942 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10943 if (!exceptionHandlerHandle) {
10944 CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
10945 }
10946}
10947
10948void FatalConditionHandler::disengage_platform() {
10949 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10950 CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
10951 }
10952 exceptionHandlerHandle = nullptr;
10953}
10954
10955} // end namespace Catch
10956
10957#endif // CATCH_CONFIG_WINDOWS_SEH
10958
10959#if defined(CATCH_CONFIG_POSIX_SIGNALS)
10960
10961#include <signal.h>
10962
10963namespace Catch {
10964
10965struct SignalDefs {
10966 int id;
10967 const char* name;
10968};
10969
10970static SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"},
10971 {SIGILL, "SIGILL - Illegal instruction signal"},
10972 {SIGFPE, "SIGFPE - Floating point error signal"},
10973 {SIGSEGV, "SIGSEGV - Segmentation violation signal"},
10974 {SIGTERM, "SIGTERM - Termination request signal"},
10975 {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}};
10976
10977// Older GCCs trigger -Wmissing-field-initializers for T foo = {}
10978// which is zero initialization, but not explicit. We want to avoid
10979// that.
10980#if defined(__GNUC__)
10981#pragma GCC diagnostic push
10982#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10983#endif
10984
10985static char* altStackMem = nullptr;
10986static std::size_t altStackSize = 0;
10987static stack_t oldSigStack{};
10988static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10989
10990static void restorePreviousSignalHandlers() {
10991 // We set signal handlers back to the previous ones. Hopefully
10992 // nobody overwrote them in the meantime, and doesn't expect
10993 // their signal handlers to live past ours given that they
10994 // installed them after ours..
10995 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
10996 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10997 }
10998 // Return the old stack
10999 sigaltstack(&oldSigStack, nullptr);
11000}
11001
11002static void handleSignal(int sig) {
11003 char const* name = "<unknown signal>";
11004 for (auto const& def : signalDefs) {
11005 if (sig == def.id) {
11006 name = def.name;
11007 break;
11008 }
11009 }
11010 // We need to restore previous signal handlers and let them do
11011 // their thing, so that the users can have the debugger break
11012 // when a signal is raised, and so on.
11013 restorePreviousSignalHandlers();
11014 reportFatal(name);
11015 raise(sig);
11016}
11017
11018FatalConditionHandler::FatalConditionHandler() {
11019 assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
11020 if (altStackSize == 0) {
11021 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
11022 }
11023 altStackMem = new char[altStackSize]();
11024}
11025
11026FatalConditionHandler::~FatalConditionHandler() {
11027 delete[] altStackMem;
11028 // We signal that another instance can be constructed by zeroing
11029 // out the pointer.
11030 altStackMem = nullptr;
11031}
11032
11033void FatalConditionHandler::engage_platform() {
11034 stack_t sigStack;
11035 sigStack.ss_sp = altStackMem;
11036 sigStack.ss_size = altStackSize;
11037 sigStack.ss_flags = 0;
11038 sigaltstack(&sigStack, &oldSigStack);
11039 struct sigaction sa = {};
11040
11041 sa.sa_handler = handleSignal;
11042 sa.sa_flags = SA_ONSTACK;
11043 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11044 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
11045 }
11046}
11047
11048#if defined(__GNUC__)
11049#pragma GCC diagnostic pop
11050#endif
11051
11052void FatalConditionHandler::disengage_platform() {
11053 restorePreviousSignalHandlers();
11054}
11055
11056} // end namespace Catch
11057
11058#endif // CATCH_CONFIG_POSIX_SIGNALS
11059// end catch_fatal_condition.cpp
11060// start catch_generators.cpp
11061
11062#include <limits>
11063#include <set>
11064
11065namespace Catch {
11066
11067IGeneratorTracker::~IGeneratorTracker() {}
11068
11069const char* GeneratorException::what() const noexcept {
11070 return m_msg;
11071}
11072
11073namespace Generators {
11074
11075GeneratorUntypedBase::~GeneratorUntypedBase() {}
11076
11077auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
11078 -> IGeneratorTracker& {
11079 return getResultCapture().acquireGeneratorTracker(generatorName, lineInfo);
11080}
11081
11082} // namespace Generators
11083} // namespace Catch
11084// end catch_generators.cpp
11085// start catch_interfaces_capture.cpp
11086
11087namespace Catch {
11088IResultCapture::~IResultCapture() = default;
11089}
11090// end catch_interfaces_capture.cpp
11091// start catch_interfaces_config.cpp
11092
11093namespace Catch {
11094IConfig::~IConfig() = default;
11095}
11096// end catch_interfaces_config.cpp
11097// start catch_interfaces_exception.cpp
11098
11099namespace Catch {
11100IExceptionTranslator::~IExceptionTranslator() = default;
11101IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
11102} // namespace Catch
11103// end catch_interfaces_exception.cpp
11104// start catch_interfaces_registry_hub.cpp
11105
11106namespace Catch {
11107IRegistryHub::~IRegistryHub() = default;
11108IMutableRegistryHub::~IMutableRegistryHub() = default;
11109} // namespace Catch
11110// end catch_interfaces_registry_hub.cpp
11111// start catch_interfaces_reporter.cpp
11112
11113// start catch_reporter_listening.h
11114
11115namespace Catch {
11116
11117class ListeningReporter : public IStreamingReporter {
11118 using Reporters = std::vector<IStreamingReporterPtr>;
11119 Reporters m_listeners;
11120 IStreamingReporterPtr m_reporter = nullptr;
11121 ReporterPreferences m_preferences;
11122
11123 public:
11124 ListeningReporter();
11125
11126 void addListener(IStreamingReporterPtr&& listener);
11127 void addReporter(IStreamingReporterPtr&& reporter);
11128
11129 public: // IStreamingReporter
11130 ReporterPreferences getPreferences() const override;
11131
11132 void noMatchingTestCases(std::string const& spec) override;
11133
11134 void reportInvalidArguments(std::string const& arg) override;
11135
11136 static std::set<Verbosity> getSupportedVerbosities();
11137
11138#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11139 void benchmarkPreparing(std::string const& name) override;
11140 void benchmarkStarting(BenchmarkInfo const& benchmarkInfo) override;
11141 void benchmarkEnded(BenchmarkStats<> const& benchmarkStats) override;
11142 void benchmarkFailed(std::string const&) override;
11143#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11144
11145 void testRunStarting(TestRunInfo const& testRunInfo) override;
11146 void testGroupStarting(GroupInfo const& groupInfo) override;
11147 void testCaseStarting(TestCaseInfo const& testInfo) override;
11148 void sectionStarting(SectionInfo const& sectionInfo) override;
11149 void assertionStarting(AssertionInfo const& assertionInfo) override;
11150
11151 // The return value indicates if the messages buffer should be cleared:
11152 bool assertionEnded(AssertionStats const& assertionStats) override;
11153 void sectionEnded(SectionStats const& sectionStats) override;
11154 void testCaseEnded(TestCaseStats const& testCaseStats) override;
11155 void testGroupEnded(TestGroupStats const& testGroupStats) override;
11156 void testRunEnded(TestRunStats const& testRunStats) override;
11157
11158 void skipTest(TestCaseInfo const& testInfo) override;
11159 bool isMulti() const override;
11160};
11161
11162} // end namespace Catch
11163
11164// end catch_reporter_listening.h
11165namespace Catch {
11166
11167ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig)
11168 : m_stream(&_fullConfig->stream()), m_fullConfig(_fullConfig) {}
11169
11170ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream)
11171 : m_stream(&_stream), m_fullConfig(_fullConfig) {}
11172
11173std::ostream& ReporterConfig::stream() const {
11174 return *m_stream;
11175}
11176IConfigPtr ReporterConfig::fullConfig() const {
11177 return m_fullConfig;
11178}
11179
11180TestRunInfo::TestRunInfo(std::string const& _name) : name(_name) {}
11181
11182GroupInfo::GroupInfo(std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount)
11183 : name(_name), groupIndex(_groupIndex), groupsCounts(_groupsCount) {}
11184
11185AssertionStats::AssertionStats(AssertionResult const& _assertionResult,
11186 std::vector<MessageInfo> const& _infoMessages, Totals const& _totals)
11187 : assertionResult(_assertionResult), infoMessages(_infoMessages), totals(_totals) {
11188 assertionResult.m_resultData.lazyExpression.m_transientExpression =
11189 _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11190
11191 if (assertionResult.hasMessage()) {
11192 // Copy message into messages list.
11193 // !TBD This should have been done earlier, somewhere
11194 MessageBuilder builder(assertionResult.getTestMacroName(), assertionResult.getSourceInfo(),
11195 assertionResult.getResultType());
11196 builder << assertionResult.getMessage();
11197 builder.m_info.message = builder.m_stream.str();
11198
11199 infoMessages.push_back(builder.m_info);
11200 }
11201}
11202
11203AssertionStats::~AssertionStats() = default;
11204
11205SectionStats::SectionStats(SectionInfo const& _sectionInfo, Counts const& _assertions,
11206 double _durationInSeconds, bool _missingAssertions)
11207 : sectionInfo(_sectionInfo), assertions(_assertions), durationInSeconds(_durationInSeconds),
11208 missingAssertions(_missingAssertions) {}
11209
11210SectionStats::~SectionStats() = default;
11211
11212TestCaseStats::TestCaseStats(TestCaseInfo const& _testInfo, Totals const& _totals,
11213 std::string const& _stdOut, std::string const& _stdErr, bool _aborting)
11214 : testInfo(_testInfo), totals(_totals), stdOut(_stdOut), stdErr(_stdErr), aborting(_aborting) {}
11215
11216TestCaseStats::~TestCaseStats() = default;
11217
11218TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting)
11219 : groupInfo(_groupInfo), totals(_totals), aborting(_aborting) {}
11220
11221TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo)
11222 : groupInfo(_groupInfo), aborting(false) {}
11223
11224TestGroupStats::~TestGroupStats() = default;
11225
11226TestRunStats::TestRunStats(TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting)
11227 : runInfo(_runInfo), totals(_totals), aborting(_aborting) {}
11228
11229TestRunStats::~TestRunStats() = default;
11230
11231void IStreamingReporter::fatalErrorEncountered(StringRef) {}
11232bool IStreamingReporter::isMulti() const {
11233 return false;
11234}
11235
11236IReporterFactory::~IReporterFactory() = default;
11237IReporterRegistry::~IReporterRegistry() = default;
11238
11239} // end namespace Catch
11240// end catch_interfaces_reporter.cpp
11241// start catch_interfaces_runner.cpp
11242
11243namespace Catch {
11244IRunner::~IRunner() = default;
11245}
11246// end catch_interfaces_runner.cpp
11247// start catch_interfaces_testcase.cpp
11248
11249namespace Catch {
11250ITestInvoker::~ITestInvoker() = default;
11251ITestCaseRegistry::~ITestCaseRegistry() = default;
11252} // namespace Catch
11253// end catch_interfaces_testcase.cpp
11254// start catch_leak_detector.cpp
11255
11256#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11257#include <crtdbg.h>
11258
11259namespace Catch {
11260
11261LeakDetector::LeakDetector() {
11262 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11263 flag |= _CRTDBG_LEAK_CHECK_DF;
11264 flag |= _CRTDBG_ALLOC_MEM_DF;
11265 _CrtSetDbgFlag(flag);
11266 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11267 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11268 // Change this to leaking allocation's number to break there
11269 _CrtSetBreakAlloc(-1);
11270}
11271} // namespace Catch
11272
11273#else
11274
11275Catch::LeakDetector::LeakDetector() {}
11276
11277#endif
11278
11279Catch::LeakDetector::~LeakDetector() {
11280 Catch::cleanUp();
11281}
11282// end catch_leak_detector.cpp
11283// start catch_list.cpp
11284
11285// start catch_list.h
11286
11287#include <set>
11288
11289namespace Catch {
11290
11291std::size_t listTests(Config const& config);
11292
11293std::size_t listTestsNamesOnly(Config const& config);
11294
11295struct TagInfo {
11296 void add(std::string const& spelling);
11297 std::string all() const;
11298
11299 std::set<std::string> spellings;
11300 std::size_t count = 0;
11301};
11302
11303std::size_t listTags(Config const& config);
11304
11305std::size_t listReporters();
11306
11307Option<std::size_t> list(std::shared_ptr<Config> const& config);
11308
11309} // end namespace Catch
11310
11311// end catch_list.h
11312// start catch_text.h
11313
11314namespace Catch {
11315using namespace clara::TextFlow;
11316}
11317
11318// end catch_text.h
11319#include <algorithm>
11320#include <iomanip>
11321#include <limits>
11322
11323namespace Catch {
11324
11325std::size_t listTests(Config const& config) {
11326 TestSpec const& testSpec = config.testSpec();
11327 if (config.hasTestFilters())
11328 Catch::cout() << "Matching test cases:\n";
11329 else {
11330 Catch::cout() << "All available test cases:\n";
11331 }
11332
11333 auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
11334 for (auto const& testCaseInfo : matchedTestCases) {
11335 Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None;
11336 Colour colourGuard(colour);
11337
11338 Catch::cout() << Column(testCaseInfo.name).initialIndent(2).indent(4) << "\n";
11339 if (config.verbosity() >= Verbosity::High) {
11340 Catch::cout() << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4)
11341 << std::endl;
11342 std::string description = testCaseInfo.description;
11343 if (description.empty())
11344 description = "(NO DESCRIPTION)";
11345 Catch::cout() << Column(description).indent(4) << std::endl;
11346 }
11347 if (!testCaseInfo.tags.empty())
11348 Catch::cout() << Column(testCaseInfo.tagsAsString()).indent(6) << "\n";
11349 }
11350
11351 if (!config.hasTestFilters())
11352 Catch::cout() << pluralise(matchedTestCases.size(), "test case") << '\n' << std::endl;
11353 else
11354 Catch::cout() << pluralise(matchedTestCases.size(), "matching test case") << '\n'
11355 << std::endl;
11356 return matchedTestCases.size();
11357}
11358
11359std::size_t listTestsNamesOnly(Config const& config) {
11360 TestSpec const& testSpec = config.testSpec();
11361 std::size_t matchedTests = 0;
11362 std::vector<TestCase> matchedTestCases =
11363 filterTests(getAllTestCasesSorted(config), testSpec, config);
11364 for (auto const& testCaseInfo : matchedTestCases) {
11365 matchedTests++;
11366 if (startsWith(testCaseInfo.name, '#'))
11367 Catch::cout() << '"' << testCaseInfo.name << '"';
11368 else
11369 Catch::cout() << testCaseInfo.name;
11370 if (config.verbosity() >= Verbosity::High)
11371 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11372 Catch::cout() << std::endl;
11373 }
11374 return matchedTests;
11375}
11376
11377void TagInfo::add(std::string const& spelling) {
11378 ++count;
11379 spellings.insert(spelling);
11380}
11381
11382std::string TagInfo::all() const {
11383 size_t size = 0;
11384 for (auto const& spelling : spellings) {
11385 // Add 2 for the brackes
11386 size += spelling.size() + 2;
11387 }
11388
11389 std::string out;
11390 out.reserve(size);
11391 for (auto const& spelling : spellings) {
11392 out += '[';
11393 out += spelling;
11394 out += ']';
11395 }
11396 return out;
11397}
11398
11399std::size_t listTags(Config const& config) {
11400 TestSpec const& testSpec = config.testSpec();
11401 if (config.hasTestFilters())
11402 Catch::cout() << "Tags for matching test cases:\n";
11403 else {
11404 Catch::cout() << "All available tags:\n";
11405 }
11406
11407 std::map<std::string, TagInfo> tagCounts;
11408
11409 std::vector<TestCase> matchedTestCases =
11410 filterTests(getAllTestCasesSorted(config), testSpec, config);
11411 for (auto const& testCase : matchedTestCases) {
11412 for (auto const& tagName : testCase.getTestCaseInfo().tags) {
11413 std::string lcaseTagName = toLower(tagName);
11414 auto countIt = tagCounts.find(lcaseTagName);
11415 if (countIt == tagCounts.end())
11416 countIt = tagCounts.insert(std::make_pair(lcaseTagName, TagInfo())).first;
11417 countIt->second.add(tagName);
11418 }
11419 }
11420
11421 for (auto const& tagCount : tagCounts) {
11423 rss << " " << std::setw(2) << tagCount.second.count << " ";
11424 auto str = rss.str();
11425 auto wrapper = Column(tagCount.second.all())
11426 .initialIndent(0)
11427 .indent(str.size())
11428 .width(CATCH_CONFIG_CONSOLE_WIDTH - 10);
11429 Catch::cout() << str << wrapper << '\n';
11430 }
11431 Catch::cout() << pluralise(tagCounts.size(), "tag") << '\n' << std::endl;
11432 return tagCounts.size();
11433}
11434
11435std::size_t listReporters() {
11436 Catch::cout() << "Available reporters:\n";
11437 IReporterRegistry::FactoryMap const& factories =
11438 getRegistryHub().getReporterRegistry().getFactories();
11439 std::size_t maxNameLen = 0;
11440 for (auto const& factoryKvp : factories)
11441 maxNameLen = (std::max)(maxNameLen, factoryKvp.first.size());
11442
11443 for (auto const& factoryKvp : factories) {
11444 Catch::cout() << Column(factoryKvp.first + ":").indent(2).width(5 + maxNameLen) +
11445 Column(factoryKvp.second->getDescription())
11446 .initialIndent(0)
11447 .indent(2)
11448 .width(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)
11449 << "\n";
11450 }
11451 Catch::cout() << std::endl;
11452 return factories.size();
11453}
11454
11455Option<std::size_t> list(std::shared_ptr<Config> const& config) {
11456 Option<std::size_t> listedCount;
11457 getCurrentMutableContext().setConfig(config);
11458 if (config->listTests())
11459 listedCount = listedCount.valueOr(0) + listTests(*config);
11460 if (config->listTestNamesOnly())
11461 listedCount = listedCount.valueOr(0) + listTestsNamesOnly(*config);
11462 if (config->listTags())
11463 listedCount = listedCount.valueOr(0) + listTags(*config);
11464 if (config->listReporters())
11465 listedCount = listedCount.valueOr(0) + listReporters();
11466 return listedCount;
11467}
11468
11469} // end namespace Catch
11470// end catch_list.cpp
11471// start catch_matchers.cpp
11472
11473namespace Catch {
11474namespace Matchers {
11475namespace Impl {
11476
11477std::string MatcherUntypedBase::toString() const {
11478 if (m_cachedToString.empty())
11479 m_cachedToString = describe();
11480 return m_cachedToString;
11481}
11482
11483MatcherUntypedBase::~MatcherUntypedBase() = default;
11484
11485} // namespace Impl
11486} // namespace Matchers
11487
11488using namespace Matchers;
11490
11491} // namespace Catch
11492// end catch_matchers.cpp
11493// start catch_matchers_exception.cpp
11494
11495namespace Catch {
11496namespace Matchers {
11497namespace Exception {
11498
11499bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11500 return ex.what() == m_message;
11501}
11502
11503std::string ExceptionMessageMatcher::describe() const {
11504 return "exception message matches \"" + m_message + "\"";
11505}
11506
11507} // namespace Exception
11508Exception::ExceptionMessageMatcher Message(std::string const& message) {
11509 return Exception::ExceptionMessageMatcher(message);
11510}
11511
11512// namespace Exception
11513} // namespace Matchers
11514} // namespace Catch
11515// end catch_matchers_exception.cpp
11516// start catch_matchers_floating.cpp
11517
11518// start catch_polyfills.hpp
11519
11520namespace Catch {
11521bool isnan(float f);
11522bool isnan(double d);
11523} // namespace Catch
11524
11525// end catch_polyfills.hpp
11526// start catch_to_string.hpp
11527
11528#include <string>
11529
11530namespace Catch {
11531template <typename T> std::string to_string(T const& t) {
11532#if defined(CATCH_CONFIG_CPP11_TO_STRING)
11533 return std::to_string(t);
11534#else
11536 rss << t;
11537 return rss.str();
11538#endif
11539}
11540} // end namespace Catch
11541
11542// end catch_to_string.hpp
11543#include <algorithm>
11544#include <cmath>
11545#include <cstdint>
11546#include <cstdlib>
11547#include <cstring>
11548#include <iomanip>
11549#include <limits>
11550#include <sstream>
11551#include <type_traits>
11552
11553namespace Catch {
11554namespace {
11555
11556int32_t convert(float f) {
11557 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
11558 int32_t i;
11559 std::memcpy(&i, &f, sizeof(f));
11560 return i;
11561}
11562
11563int64_t convert(double d) {
11564 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
11565 int64_t i;
11566 std::memcpy(&i, &d, sizeof(d));
11567 return i;
11568}
11569
11570template <typename FP> bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11571 // Comparison with NaN should always be false.
11572 // This way we can rule it out before getting into the ugly details
11573 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11574 return false;
11575 }
11576
11577 auto lc = convert(lhs);
11578 auto rc = convert(rhs);
11579
11580 if ((lc < 0) != (rc < 0)) {
11581 // Potentially we can have +0 and -0
11582 return lhs == rhs;
11583 }
11584
11585 // static cast as a workaround for IBM XLC
11586 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11587 return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11588}
11589
11590#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11591
11592float nextafter(float x, float y) {
11593 return ::nextafterf(x, y);
11594}
11595
11596double nextafter(double x, double y) {
11597 return ::nextafter(x, y);
11598}
11599
11600#endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11601
11602template <typename FP> FP step(FP start, FP direction, uint64_t steps) {
11603 for (uint64_t i = 0; i < steps; ++i) {
11604#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11605 start = Catch::nextafter(start, direction);
11606#else
11607 start = std::nextafter(start, direction);
11608#endif
11609 }
11610 return start;
11611}
11612
11613// Performs equivalent check of std::fabs(lhs - rhs) <= margin
11614// But without the subtraction to allow for INFINITY in comparison
11615bool marginComparison(double lhs, double rhs, double margin) {
11616 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11617}
11618
11619template <typename FloatingPoint> void write(std::ostream& out, FloatingPoint num) {
11620 out << std::scientific
11621 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) << num;
11622}
11623
11624} // end anonymous namespace
11625
11626namespace Matchers {
11627namespace Floating {
11628
11629enum class FloatingPointKind : uint8_t { Float, Double };
11630
11631WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11632 : m_target{target}, m_margin{margin} {
11633 CATCH_ENFORCE(margin >= 0,
11634 "Invalid margin: " << margin << '.' << " Margin has to be non-negative.");
11635}
11636
11637// Performs equivalent check of std::fabs(lhs - rhs) <= margin
11638// But without the subtraction to allow for INFINITY in comparison
11639bool WithinAbsMatcher::match(double const& matchee) const {
11640 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11641}
11642
11643std::string WithinAbsMatcher::describe() const {
11644 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " +
11645 ::Catch::Detail::stringify(m_target);
11646}
11647
11648WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
11649 : m_target{target}, m_ulps{ulps}, m_type{baseType} {
11650 CATCH_ENFORCE(m_type == FloatingPointKind::Double ||
11651 m_ulps < (std::numeric_limits<uint32_t>::max)(),
11652 "Provided ULP is impossibly large for a float comparison.");
11653}
11654
11655#if defined(__clang__)
11656#pragma clang diagnostic push
11657// Clang <3.5 reports on the default branch in the switch below
11658#pragma clang diagnostic ignored "-Wunreachable-code"
11659#endif
11660
11661bool WithinUlpsMatcher::match(double const& matchee) const {
11662 switch (m_type) {
11663 case FloatingPointKind::Float:
11664 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target),
11665 m_ulps);
11666 case FloatingPointKind::Double:
11667 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11668 default:
11669 CATCH_INTERNAL_ERROR("Unknown FloatingPointKind value");
11670 }
11671}
11672
11673#if defined(__clang__)
11674#pragma clang diagnostic pop
11675#endif
11676
11677std::string WithinUlpsMatcher::describe() const {
11678 std::stringstream ret;
11679
11680 ret << "is within " << m_ulps << " ULPs of ";
11681
11682 if (m_type == FloatingPointKind::Float) {
11683 write(ret, static_cast<float>(m_target));
11684 ret << 'f';
11685 } else {
11686 write(ret, m_target);
11687 }
11688
11689 ret << " ([";
11690 if (m_type == FloatingPointKind::Double) {
11691 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11692 ret << ", ";
11693 write(ret, step(m_target, static_cast<double>(INFINITY), m_ulps));
11694 } else {
11695 // We have to cast INFINITY to float because of MinGW, see #1782
11696 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11697 ret << ", ";
11698 write(ret, step(static_cast<float>(m_target), static_cast<float>(INFINITY), m_ulps));
11699 }
11700 ret << "])";
11701
11702 return ret.str();
11703}
11704
11705WithinRelMatcher::WithinRelMatcher(double target, double epsilon)
11706 : m_target(target), m_epsilon(epsilon) {
11707 CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
11708 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
11709}
11710
11711bool WithinRelMatcher::match(double const& matchee) const {
11712 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11713 return marginComparison(matchee, m_target, std::isinf(relMargin) ? 0 : relMargin);
11714}
11715
11716std::string WithinRelMatcher::describe() const {
11717 Catch::ReusableStringStream sstr;
11718 sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
11719 return sstr.str();
11720}
11721
11722} // namespace Floating
11723
11724Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11725 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11726}
11727
11728Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11729 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11730}
11731
11732Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11733 return Floating::WithinAbsMatcher(target, margin);
11734}
11735
11736Floating::WithinRelMatcher WithinRel(double target, double eps) {
11737 return Floating::WithinRelMatcher(target, eps);
11738}
11739
11740Floating::WithinRelMatcher WithinRel(double target) {
11741 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11742}
11743
11744Floating::WithinRelMatcher WithinRel(float target, float eps) {
11745 return Floating::WithinRelMatcher(target, eps);
11746}
11747
11748Floating::WithinRelMatcher WithinRel(float target) {
11749 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11750}
11751
11752} // namespace Matchers
11753} // namespace Catch
11754// end catch_matchers_floating.cpp
11755// start catch_matchers_generic.cpp
11756
11757std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11758 if (desc.empty()) {
11759 return "matches undescribed predicate";
11760 } else {
11761 return "matches predicate: \"" + desc + '"';
11762 }
11763}
11764// end catch_matchers_generic.cpp
11765// start catch_matchers_string.cpp
11766
11767#include <regex>
11768
11769namespace Catch {
11770namespace Matchers {
11771
11772namespace StdString {
11773
11774CasedString::CasedString(std::string const& str, CaseSensitive::Choice caseSensitivity)
11775 : m_caseSensitivity(caseSensitivity), m_str(adjustString(str)) {}
11776std::string CasedString::adjustString(std::string const& str) const {
11777 return m_caseSensitivity == CaseSensitive::No ? toLower(str) : str;
11778}
11779std::string CasedString::caseSensitivitySuffix() const {
11780 return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)" : std::string();
11781}
11782
11783StringMatcherBase::StringMatcherBase(std::string const& operation, CasedString const& comparator)
11784 : m_comparator(comparator), m_operation(operation) {}
11785
11786std::string StringMatcherBase::describe() const {
11787 std::string description;
11788 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11789 m_comparator.caseSensitivitySuffix().size());
11790 description += m_operation;
11791 description += ": \"";
11792 description += m_comparator.m_str;
11793 description += "\"";
11794 description += m_comparator.caseSensitivitySuffix();
11795 return description;
11796}
11797
11798EqualsMatcher::EqualsMatcher(CasedString const& comparator)
11799 : StringMatcherBase("equals", comparator) {}
11800
11801bool EqualsMatcher::match(std::string const& source) const {
11802 return m_comparator.adjustString(source) == m_comparator.m_str;
11803}
11804
11805ContainsMatcher::ContainsMatcher(CasedString const& comparator)
11806 : StringMatcherBase("contains", comparator) {}
11807
11808bool ContainsMatcher::match(std::string const& source) const {
11809 return contains(m_comparator.adjustString(source), m_comparator.m_str);
11810}
11811
11812StartsWithMatcher::StartsWithMatcher(CasedString const& comparator)
11813 : StringMatcherBase("starts with", comparator) {}
11814
11815bool StartsWithMatcher::match(std::string const& source) const {
11816 return startsWith(m_comparator.adjustString(source), m_comparator.m_str);
11817}
11818
11819EndsWithMatcher::EndsWithMatcher(CasedString const& comparator)
11820 : StringMatcherBase("ends with", comparator) {}
11821
11822bool EndsWithMatcher::match(std::string const& source) const {
11823 return endsWith(m_comparator.adjustString(source), m_comparator.m_str);
11824}
11825
11826RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity)
11827 : m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11828
11829bool RegexMatcher::match(std::string const& matchee) const {
11830 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11831 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11832 flags |= std::regex::icase;
11833 }
11834 auto reg = std::regex(m_regex, flags);
11835 return std::regex_match(matchee, reg);
11836}
11837
11838std::string RegexMatcher::describe() const {
11839 return "matches " + ::Catch::Detail::stringify(m_regex) +
11840 ((m_caseSensitivity == CaseSensitive::Choice::Yes) ? " case sensitively"
11841 : " case insensitively");
11842}
11843
11844} // namespace StdString
11845
11846StdString::EqualsMatcher Equals(std::string const& str, CaseSensitive::Choice caseSensitivity) {
11847 return StdString::EqualsMatcher(StdString::CasedString(str, caseSensitivity));
11848}
11849StdString::ContainsMatcher Contains(std::string const& str, CaseSensitive::Choice caseSensitivity) {
11850 return StdString::ContainsMatcher(StdString::CasedString(str, caseSensitivity));
11851}
11852StdString::EndsWithMatcher EndsWith(std::string const& str, CaseSensitive::Choice caseSensitivity) {
11853 return StdString::EndsWithMatcher(StdString::CasedString(str, caseSensitivity));
11854}
11855StdString::StartsWithMatcher StartsWith(std::string const& str,
11856 CaseSensitive::Choice caseSensitivity) {
11857 return StdString::StartsWithMatcher(StdString::CasedString(str, caseSensitivity));
11858}
11859
11860StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11861 return StdString::RegexMatcher(regex, caseSensitivity);
11862}
11863
11864} // namespace Matchers
11865} // namespace Catch
11866// end catch_matchers_string.cpp
11867// start catch_message.cpp
11868
11869// start catch_uncaught_exceptions.h
11870
11871namespace Catch {
11872bool uncaught_exceptions();
11873} // end namespace Catch
11874
11875// end catch_uncaught_exceptions.h
11876#include <cassert>
11877#include <stack>
11878
11879namespace Catch {
11880
11881MessageInfo::MessageInfo(StringRef const& _macroName, SourceLineInfo const& _lineInfo,
11882 ResultWas::OfType _type)
11883 : macroName(_macroName), lineInfo(_lineInfo), type(_type), sequence(++globalCount) {}
11884
11885bool MessageInfo::operator==(MessageInfo const& other) const {
11886 return sequence == other.sequence;
11887}
11888
11889bool MessageInfo::operator<(MessageInfo const& other) const {
11890 return sequence < other.sequence;
11891}
11892
11893// This may need protecting if threading support is added
11894unsigned int MessageInfo::globalCount = 0;
11895
11897
11898Catch::MessageBuilder::MessageBuilder(StringRef const& macroName, SourceLineInfo const& lineInfo,
11899 ResultWas::OfType type)
11900 : m_info(macroName, lineInfo, type) {}
11901
11903
11904ScopedMessage::ScopedMessage(MessageBuilder const& builder) : m_info(builder.m_info), m_moved() {
11905 m_info.message = builder.m_stream.str();
11906 getResultCapture().pushScopedMessage(m_info);
11907}
11908
11909ScopedMessage::ScopedMessage(ScopedMessage&& old) : m_info(old.m_info), m_moved() {
11910 old.m_moved = true;
11911}
11912
11913ScopedMessage::~ScopedMessage() {
11914 if (!uncaught_exceptions() && !m_moved) {
11915 getResultCapture().popScopedMessage(m_info);
11916 }
11917}
11918
11919Capturer::Capturer(StringRef macroName, SourceLineInfo const& lineInfo,
11920 ResultWas::OfType resultType, StringRef names) {
11921 auto trimmed = [&](size_t start, size_t end) {
11922 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
11923 ++start;
11924 }
11925 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
11926 --end;
11927 }
11928 return names.substr(start, end - start + 1);
11929 };
11930 auto skipq = [&](size_t start, char quote) {
11931 for (auto i = start + 1; i < names.size(); ++i) {
11932 if (names[i] == quote)
11933 return i;
11934 if (names[i] == '\\')
11935 ++i;
11936 }
11937 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11938 };
11939
11940 size_t start = 0;
11941 std::stack<char> openings;
11942 for (size_t pos = 0; pos < names.size(); ++pos) {
11943 char c = names[pos];
11944 switch (c) {
11945 case '[':
11946 case '{':
11947 case '(':
11948 // It is basically impossible to disambiguate between
11949 // comparison and start of template args in this context
11950 // case '<':
11951 openings.push(c);
11952 break;
11953 case ']':
11954 case '}':
11955 case ')':
11956 // case '>':
11957 openings.pop();
11958 break;
11959 case '"':
11960 case '\'':
11961 pos = skipq(pos, c);
11962 break;
11963 case ',':
11964 if (start != pos && openings.empty()) {
11965 m_messages.emplace_back(macroName, lineInfo, resultType);
11966 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
11967 m_messages.back().message += " := ";
11968 start = pos;
11969 }
11970 }
11971 }
11972 assert(openings.empty() && "Mismatched openings");
11973 m_messages.emplace_back(macroName, lineInfo, resultType);
11974 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
11975 m_messages.back().message += " := ";
11976}
11977Capturer::~Capturer() {
11978 if (!uncaught_exceptions()) {
11979 assert(m_captured == m_messages.size());
11980 for (size_t i = 0; i < m_captured; ++i)
11981 m_resultCapture.popScopedMessage(m_messages[i]);
11982 }
11983}
11984
11985void Capturer::captureValue(size_t index, std::string const& value) {
11986 assert(index < m_messages.size());
11987 m_messages[index].message += value;
11988 m_resultCapture.pushScopedMessage(m_messages[index]);
11989 m_captured++;
11990}
11991
11992} // end namespace Catch
11993// end catch_message.cpp
11994// start catch_output_redirect.cpp
11995
11996// start catch_output_redirect.h
11997#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11998#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11999
12000#include <cstdio>
12001#include <iosfwd>
12002#include <string>
12003
12004namespace Catch {
12005
12006class RedirectedStream {
12007 std::ostream& m_originalStream;
12008 std::ostream& m_redirectionStream;
12009 std::streambuf* m_prevBuf;
12010
12011 public:
12012 RedirectedStream(std::ostream& originalStream, std::ostream& redirectionStream);
12013 ~RedirectedStream();
12014};
12015
12016class RedirectedStdOut {
12017 ReusableStringStream m_rss;
12018 RedirectedStream m_cout;
12019
12020 public:
12021 RedirectedStdOut();
12022 auto str() const -> std::string;
12023};
12024
12025// StdErr has two constituent streams in C++, std::cerr and std::clog
12026// This means that we need to redirect 2 streams into 1 to keep proper
12027// order of writes
12028class RedirectedStdErr {
12029 ReusableStringStream m_rss;
12030 RedirectedStream m_cerr;
12031 RedirectedStream m_clog;
12032
12033 public:
12034 RedirectedStdErr();
12035 auto str() const -> std::string;
12036};
12037
12038class RedirectedStreams {
12039 public:
12040 RedirectedStreams(RedirectedStreams const&) = delete;
12041 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
12042 RedirectedStreams(RedirectedStreams&&) = delete;
12043 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
12044
12045 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
12046 ~RedirectedStreams();
12047
12048 private:
12049 std::string& m_redirectedCout;
12050 std::string& m_redirectedCerr;
12051 RedirectedStdOut m_redirectedStdOut;
12052 RedirectedStdErr m_redirectedStdErr;
12053};
12054
12055#if defined(CATCH_CONFIG_NEW_CAPTURE)
12056
12057// Windows's implementation of std::tmpfile is terrible (it tries
12058// to create a file inside system folder, thus requiring elevated
12059// privileges for the binary), so we have to use tmpnam(_s) and
12060// create the file ourselves there.
12061class TempFile {
12062 public:
12063 TempFile(TempFile const&) = delete;
12064 TempFile& operator=(TempFile const&) = delete;
12065 TempFile(TempFile&&) = delete;
12066 TempFile& operator=(TempFile&&) = delete;
12067
12068 TempFile();
12069 ~TempFile();
12070
12071 std::FILE* getFile();
12072 std::string getContents();
12073
12074 private:
12075 std::FILE* m_file = nullptr;
12076#if defined(_MSC_VER)
12077 char m_buffer[L_tmpnam] = {0};
12078#endif
12079};
12080
12081class OutputRedirect {
12082 public:
12083 OutputRedirect(OutputRedirect const&) = delete;
12084 OutputRedirect& operator=(OutputRedirect const&) = delete;
12085 OutputRedirect(OutputRedirect&&) = delete;
12086 OutputRedirect& operator=(OutputRedirect&&) = delete;
12087
12088 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12089 ~OutputRedirect();
12090
12091 private:
12092 int m_originalStdout = -1;
12093 int m_originalStderr = -1;
12094 TempFile m_stdoutFile;
12095 TempFile m_stderrFile;
12096 std::string& m_stdoutDest;
12097 std::string& m_stderrDest;
12098};
12099
12100#endif
12101
12102} // end namespace Catch
12103
12104#endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12105// end catch_output_redirect.h
12106#include <cstdio>
12107#include <cstring>
12108#include <fstream>
12109#include <sstream>
12110#include <stdexcept>
12111
12112#if defined(CATCH_CONFIG_NEW_CAPTURE)
12113#if defined(_MSC_VER)
12114#include <io.h> //_dup and _dup2
12115#define dup _dup
12116#define dup2 _dup2
12117#define fileno _fileno
12118#else
12119#include <unistd.h> // dup and dup2
12120#endif
12121#endif
12122
12123namespace Catch {
12124
12125RedirectedStream::RedirectedStream(std::ostream& originalStream, std::ostream& redirectionStream)
12126 : m_originalStream(originalStream), m_redirectionStream(redirectionStream),
12127 m_prevBuf(m_originalStream.rdbuf()) {
12128 m_originalStream.rdbuf(m_redirectionStream.rdbuf());
12129}
12130
12131RedirectedStream::~RedirectedStream() {
12132 m_originalStream.rdbuf(m_prevBuf);
12133}
12134
12135RedirectedStdOut::RedirectedStdOut() : m_cout(Catch::cout(), m_rss.get()) {}
12136auto RedirectedStdOut::str() const -> std::string {
12137 return m_rss.str();
12138}
12139
12140RedirectedStdErr::RedirectedStdErr()
12141 : m_cerr(Catch::cerr(), m_rss.get()), m_clog(Catch::clog(), m_rss.get()) {}
12142auto RedirectedStdErr::str() const -> std::string {
12143 return m_rss.str();
12144}
12145
12146RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12147 : m_redirectedCout(redirectedCout), m_redirectedCerr(redirectedCerr) {}
12148
12149RedirectedStreams::~RedirectedStreams() {
12150 m_redirectedCout += m_redirectedStdOut.str();
12151 m_redirectedCerr += m_redirectedStdErr.str();
12152}
12153
12154#if defined(CATCH_CONFIG_NEW_CAPTURE)
12155
12156#if defined(_MSC_VER)
12157TempFile::TempFile() {
12158 if (tmpnam_s(m_buffer)) {
12159 CATCH_RUNTIME_ERROR("Could not get a temp filename");
12160 }
12161 if (fopen_s(&m_file, m_buffer, "w+")) {
12162 char buffer[100];
12163 if (strerror_s(buffer, errno)) {
12164 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12165 }
12166 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer
12167 << "' because: " << buffer);
12168 }
12169}
12170#else
12171TempFile::TempFile() {
12172 m_file = std::tmpfile();
12173 if (!m_file) {
12174 CATCH_RUNTIME_ERROR("Could not create a temp file.");
12175 }
12176}
12177
12178#endif
12179
12180TempFile::~TempFile() {
12181 // TBD: What to do about errors here?
12182 std::fclose(m_file);
12183 // We manually create the file on Windows only, on Linux
12184 // it will be autodeleted
12185#if defined(_MSC_VER)
12186 std::remove(m_buffer);
12187#endif
12188}
12189
12190FILE* TempFile::getFile() {
12191 return m_file;
12192}
12193
12194std::string TempFile::getContents() {
12195 std::stringstream sstr;
12196 char buffer[100] = {};
12197 std::rewind(m_file);
12198 while (std::fgets(buffer, sizeof(buffer), m_file)) {
12199 sstr << buffer;
12200 }
12201 return sstr.str();
12202}
12203
12204OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest)
12205 : m_originalStdout(dup(1)), m_originalStderr(dup(2)), m_stdoutDest(stdout_dest),
12206 m_stderrDest(stderr_dest) {
12207 dup2(fileno(m_stdoutFile.getFile()), 1);
12208 dup2(fileno(m_stderrFile.getFile()), 2);
12209}
12210
12211OutputRedirect::~OutputRedirect() {
12212 Catch::cout() << std::flush;
12213 fflush(stdout);
12214 // Since we support overriding these streams, we flush cerr
12215 // even though std::cerr is unbuffered
12216 Catch::cerr() << std::flush;
12217 Catch::clog() << std::flush;
12218 fflush(stderr);
12219
12220 dup2(m_originalStdout, 1);
12221 dup2(m_originalStderr, 2);
12222
12223 m_stdoutDest += m_stdoutFile.getContents();
12224 m_stderrDest += m_stderrFile.getContents();
12225}
12226
12227#endif // CATCH_CONFIG_NEW_CAPTURE
12228
12229} // namespace Catch
12230
12231#if defined(CATCH_CONFIG_NEW_CAPTURE)
12232#if defined(_MSC_VER)
12233#undef dup
12234#undef dup2
12235#undef fileno
12236#endif
12237#endif
12238// end catch_output_redirect.cpp
12239// start catch_polyfills.cpp
12240
12241#include <cmath>
12242
12243namespace Catch {
12244
12245#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12246bool isnan(float f) {
12247 return std::isnan(f);
12248}
12249bool isnan(double d) {
12250 return std::isnan(d);
12251}
12252#else
12253// For now we only use this for embarcadero
12254bool isnan(float f) {
12255 return std::_isnan(f);
12256}
12257bool isnan(double d) {
12258 return std::_isnan(d);
12259}
12260#endif
12261
12262} // end namespace Catch
12263// end catch_polyfills.cpp
12264// start catch_random_number_generator.cpp
12265
12266namespace Catch {
12267
12268namespace {
12269
12270#if defined(_MSC_VER)
12271#pragma warning(push)
12272#pragma warning(disable : 4146) // we negate uint32 during the rotate
12273#endif
12274// Safe rotr implementation thanks to John Regehr
12275uint32_t rotate_right(uint32_t val, uint32_t count) {
12276 const uint32_t mask = 31;
12277 count &= mask;
12278 return (val >> count) | (val << (-count & mask));
12279}
12280
12281#if defined(_MSC_VER)
12282#pragma warning(pop)
12283#endif
12284
12285} // namespace
12286
12287SimplePcg32::SimplePcg32(result_type seed_) {
12288 seed(seed_);
12289}
12290
12291void SimplePcg32::seed(result_type seed_) {
12292 m_state = 0;
12293 (*this)();
12294 m_state += seed_;
12295 (*this)();
12296}
12297
12298void SimplePcg32::discard(uint64_t skip) {
12299 // We could implement this to run in O(log n) steps, but this
12300 // should suffice for our use case.
12301 for (uint64_t s = 0; s < skip; ++s) {
12302 static_cast<void>((*this)());
12303 }
12304}
12305
12306SimplePcg32::result_type SimplePcg32::operator()() {
12307 // prepare the output value
12308 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12309 const auto output = rotate_right(xorshifted, m_state >> 59u);
12310
12311 // advance state
12312 m_state = m_state * 6364136223846793005ULL + s_inc;
12313
12314 return output;
12315}
12316
12317bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12318 return lhs.m_state == rhs.m_state;
12319}
12320
12321bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12322 return lhs.m_state != rhs.m_state;
12323}
12324} // namespace Catch
12325// end catch_random_number_generator.cpp
12326// start catch_registry_hub.cpp
12327
12328// start catch_test_case_registry_impl.h
12329
12330#include <algorithm>
12331#include <ios>
12332#include <set>
12333#include <vector>
12334
12335namespace Catch {
12336
12337class TestCase;
12338struct IConfig;
12339
12340std::vector<TestCase> sortTests(IConfig const& config,
12341 std::vector<TestCase> const& unsortedTestCases);
12342
12343bool isThrowSafe(TestCase const& testCase, IConfig const& config);
12344bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config);
12345
12346void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions);
12347
12348std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases, TestSpec const& testSpec,
12349 IConfig const& config);
12350std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config);
12351
12352class TestRegistry : public ITestCaseRegistry {
12353 public:
12354 virtual ~TestRegistry() = default;
12355
12356 virtual void registerTest(TestCase const& testCase);
12357
12358 std::vector<TestCase> const& getAllTests() const override;
12359 std::vector<TestCase> const& getAllTestsSorted(IConfig const& config) const override;
12360
12361 private:
12362 std::vector<TestCase> m_functions;
12363 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12364 mutable std::vector<TestCase> m_sortedFunctions;
12365 std::size_t m_unnamedCount = 0;
12366 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12367};
12368
12370
12371class TestInvokerAsFunction : public ITestInvoker {
12372 void (*m_testAsFunction)();
12373
12374 public:
12375 TestInvokerAsFunction(void (*testAsFunction)()) noexcept;
12376
12377 void invoke() const override;
12378};
12379
12380std::string extractClassName(StringRef const& classOrQualifiedMethodName);
12381
12383
12384} // end namespace Catch
12385
12386// end catch_test_case_registry_impl.h
12387// start catch_reporter_registry.h
12388
12389#include <map>
12390
12391namespace Catch {
12392
12393class ReporterRegistry : public IReporterRegistry {
12394
12395 public:
12396 ~ReporterRegistry() override;
12397
12398 IStreamingReporterPtr create(std::string const& name, IConfigPtr const& config) const override;
12399
12400 void registerReporter(std::string const& name, IReporterFactoryPtr const& factory);
12401 void registerListener(IReporterFactoryPtr const& factory);
12402
12403 FactoryMap const& getFactories() const override;
12404 Listeners const& getListeners() const override;
12405
12406 private:
12407 FactoryMap m_factories;
12408 Listeners m_listeners;
12409};
12410} // namespace Catch
12411
12412// end catch_reporter_registry.h
12413// start catch_tag_alias_registry.h
12414
12415// start catch_tag_alias.h
12416
12417#include <string>
12418
12419namespace Catch {
12420
12421struct TagAlias {
12422 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12423
12424 std::string tag;
12425 SourceLineInfo lineInfo;
12426};
12427
12428} // end namespace Catch
12429
12430// end catch_tag_alias.h
12431#include <map>
12432
12433namespace Catch {
12434
12435class TagAliasRegistry : public ITagAliasRegistry {
12436 public:
12437 ~TagAliasRegistry() override;
12438 TagAlias const* find(std::string const& alias) const override;
12439 std::string expandAliases(std::string const& unexpandedTestSpec) const override;
12440 void add(std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo);
12441
12442 private:
12443 std::map<std::string, TagAlias> m_registry;
12444};
12445
12446} // end namespace Catch
12447
12448// end catch_tag_alias_registry.h
12449// start catch_startup_exception_registry.h
12450
12451#include <exception>
12452#include <vector>
12453
12454namespace Catch {
12455
12456class StartupExceptionRegistry {
12457#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12458 public:
12459 void add(std::exception_ptr const& exception) noexcept;
12460 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12461
12462 private:
12463 std::vector<std::exception_ptr> m_exceptions;
12464#endif
12465};
12466
12467} // end namespace Catch
12468
12469// end catch_startup_exception_registry.h
12470// start catch_singletons.hpp
12471
12472namespace Catch {
12473
12474struct ISingleton {
12475 virtual ~ISingleton();
12476};
12477
12478void addSingleton(ISingleton* singleton);
12479void cleanupSingletons();
12480
12481template <typename SingletonImplT, typename InterfaceT = SingletonImplT,
12482 typename MutableInterfaceT = InterfaceT>
12483class Singleton : SingletonImplT, public ISingleton {
12484
12485 static auto getInternal() -> Singleton* {
12486 static Singleton* s_instance = nullptr;
12487 if (!s_instance) {
12488 s_instance = new Singleton;
12489 addSingleton(s_instance);
12490 }
12491 return s_instance;
12492 }
12493
12494 public:
12495 static auto get() -> InterfaceT const& { return *getInternal(); }
12496 static auto getMutable() -> MutableInterfaceT& { return *getInternal(); }
12497};
12498
12499} // namespace Catch
12500
12501// end catch_singletons.hpp
12502namespace Catch {
12503
12504namespace {
12505
12506class RegistryHub : public IRegistryHub, public IMutableRegistryHub, private NonCopyable {
12507
12508 public: // IRegistryHub
12509 RegistryHub() = default;
12510 IReporterRegistry const& getReporterRegistry() const override { return m_reporterRegistry; }
12511 ITestCaseRegistry const& getTestCaseRegistry() const override { return m_testCaseRegistry; }
12512 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12513 return m_exceptionTranslatorRegistry;
12514 }
12515 ITagAliasRegistry const& getTagAliasRegistry() const override { return m_tagAliasRegistry; }
12516 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12517 return m_exceptionRegistry;
12518 }
12519
12520 public: // IMutableRegistryHub
12521 void registerReporter(std::string const& name, IReporterFactoryPtr const& factory) override {
12522 m_reporterRegistry.registerReporter(name, factory);
12523 }
12524 void registerListener(IReporterFactoryPtr const& factory) override {
12525 m_reporterRegistry.registerListener(factory);
12526 }
12527 void registerTest(TestCase const& testInfo) override {
12528 m_testCaseRegistry.registerTest(testInfo);
12529 }
12530 void registerTranslator(const IExceptionTranslator* translator) override {
12531 m_exceptionTranslatorRegistry.registerTranslator(translator);
12532 }
12533 void registerTagAlias(std::string const& alias, std::string const& tag,
12534 SourceLineInfo const& lineInfo) override {
12535 m_tagAliasRegistry.add(alias, tag, lineInfo);
12536 }
12537 void registerStartupException() noexcept override {
12538#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12539 m_exceptionRegistry.add(std::current_exception());
12540#else
12541 CATCH_INTERNAL_ERROR("Attempted to register active exception under "
12542 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12543#endif
12544 }
12545 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12546 return m_enumValuesRegistry;
12547 }
12548
12549 private:
12550 TestRegistry m_testCaseRegistry;
12551 ReporterRegistry m_reporterRegistry;
12552 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12553 TagAliasRegistry m_tagAliasRegistry;
12554 StartupExceptionRegistry m_exceptionRegistry;
12555 Detail::EnumValuesRegistry m_enumValuesRegistry;
12556};
12557} // namespace
12558
12559using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12560
12561IRegistryHub const& getRegistryHub() {
12562 return RegistryHubSingleton::get();
12563}
12564IMutableRegistryHub& getMutableRegistryHub() {
12565 return RegistryHubSingleton::getMutable();
12566}
12567void cleanUp() {
12568 cleanupSingletons();
12569 cleanUpContext();
12570}
12571std::string translateActiveException() {
12572 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12573}
12574
12575} // end namespace Catch
12576// end catch_registry_hub.cpp
12577// start catch_reporter_registry.cpp
12578
12579namespace Catch {
12580
12581ReporterRegistry::~ReporterRegistry() = default;
12582
12583IStreamingReporterPtr ReporterRegistry::create(std::string const& name,
12584 IConfigPtr const& config) const {
12585 auto it = m_factories.find(name);
12586 if (it == m_factories.end())
12587 return nullptr;
12588 return it->second->create(ReporterConfig(config));
12589}
12590
12591void ReporterRegistry::registerReporter(std::string const& name,
12592 IReporterFactoryPtr const& factory) {
12593 m_factories.emplace(name, factory);
12594}
12595void ReporterRegistry::registerListener(IReporterFactoryPtr const& factory) {
12596 m_listeners.push_back(factory);
12597}
12598
12599IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12600 return m_factories;
12601}
12602IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12603 return m_listeners;
12604}
12605
12606} // namespace Catch
12607// end catch_reporter_registry.cpp
12608// start catch_result_type.cpp
12609
12610namespace Catch {
12611
12612bool isOk(ResultWas::OfType resultType) {
12613 return (resultType & ResultWas::FailureBit) == 0;
12614}
12615bool isJustInfo(int flags) {
12616 return flags == ResultWas::Info;
12617}
12618
12619ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs) {
12620 return static_cast<ResultDisposition::Flags>(static_cast<int>(lhs) | static_cast<int>(rhs));
12621}
12622
12623bool shouldContinueOnFailure(int flags) {
12624 return (flags & ResultDisposition::ContinueOnFailure) != 0;
12625}
12626bool shouldSuppressFailure(int flags) {
12627 return (flags & ResultDisposition::SuppressFail) != 0;
12628}
12629
12630} // end namespace Catch
12631// end catch_result_type.cpp
12632// start catch_run_context.cpp
12633
12634#include <algorithm>
12635#include <cassert>
12636#include <sstream>
12637
12638namespace Catch {
12639
12640namespace Generators {
12641struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12642 GeneratorBasePtr m_generator;
12643
12644 GeneratorTracker(TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx,
12645 ITracker* parent)
12646 : TrackerBase(nameAndLocation, ctx, parent) {}
12647 ~GeneratorTracker();
12648
12649 static GeneratorTracker& acquire(TrackerContext& ctx,
12650 TestCaseTracking::NameAndLocation const& nameAndLocation) {
12651 std::shared_ptr<GeneratorTracker> tracker;
12652
12653 ITracker& currentTracker = ctx.currentTracker();
12654 // Under specific circumstances, the generator we want
12655 // to acquire is also the current tracker. If this is
12656 // the case, we have to avoid looking through current
12657 // tracker's children, and instead return the current
12658 // tracker.
12659 // A case where this check is important is e.g.
12660 // for (int i = 0; i < 5; ++i) {
12661 // int n = GENERATE(1, 2);
12662 // }
12663 //
12664 // without it, the code above creates 5 nested generators.
12665 if (currentTracker.nameAndLocation() == nameAndLocation) {
12666 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12667 assert(thisTracker);
12668 assert(thisTracker->isGeneratorTracker());
12669 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12670 } else if (TestCaseTracking::ITrackerPtr childTracker =
12671 currentTracker.findChild(nameAndLocation)) {
12672 assert(childTracker);
12673 assert(childTracker->isGeneratorTracker());
12674 tracker = std::static_pointer_cast<GeneratorTracker>(childTracker);
12675 } else {
12676 tracker = std::make_shared<GeneratorTracker>(nameAndLocation, ctx, &currentTracker);
12677 currentTracker.addChild(tracker);
12678 }
12679
12680 if (!tracker->isComplete()) {
12681 tracker->open();
12682 }
12683
12684 return *tracker;
12685 }
12686
12687 // TrackerBase interface
12688 bool isGeneratorTracker() const override { return true; }
12689 auto hasGenerator() const -> bool override { return !!m_generator; }
12690 void close() override {
12691 TrackerBase::close();
12692 // If a generator has a child (it is followed by a section)
12693 // and none of its children have started, then we must wait
12694 // until later to start consuming its values.
12695 // This catches cases where `GENERATE` is placed between two
12696 // `SECTION`s.
12697 // **The check for m_children.empty cannot be removed**.
12698 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
12699 const bool should_wait_for_child = [&]() {
12700 // No children -> nobody to wait for
12701 if (m_children.empty()) {
12702 return false;
12703 }
12704 // If at least one child started executing, don't wait
12705 if (std::find_if(m_children.begin(), m_children.end(),
12706 [](TestCaseTracking::ITrackerPtr tracker) {
12707 return tracker->hasStarted();
12708 }) != m_children.end()) {
12709 return false;
12710 }
12711
12712 // No children have started. We need to check if they _can_
12713 // start, and thus we should wait for them, or they cannot
12714 // start (due to filters), and we shouldn't wait for them
12715 auto* parent = m_parent;
12716 // This is safe: there is always at least one section
12717 // tracker in a test case tracking tree
12718 while (!parent->isSectionTracker()) {
12719 parent = &(parent->parent());
12720 }
12721 assert(parent && "Missing root (test case) level section");
12722
12723 auto const& parentSection = static_cast<SectionTracker&>(*parent);
12724 auto const& filters = parentSection.getFilters();
12725 // No filters -> no restrictions on running sections
12726 if (filters.empty()) {
12727 return true;
12728 }
12729
12730 for (auto const& child : m_children) {
12731 if (child->isSectionTracker() &&
12732 std::find(filters.begin(), filters.end(),
12733 static_cast<SectionTracker&>(*child).trimmedName()) !=
12734 filters.end()) {
12735 return true;
12736 }
12737 }
12738 return false;
12739 }();
12740
12741 // This check is a bit tricky, because m_generator->next()
12742 // has a side-effect, where it consumes generator's current
12743 // value, but we do not want to invoke the side-effect if
12744 // this generator is still waiting for any child to start.
12745 if (should_wait_for_child || (m_runState == CompletedSuccessfully && m_generator->next())) {
12746 m_children.clear();
12747 m_runState = Executing;
12748 }
12749 }
12750
12751 // IGeneratorTracker interface
12752 auto getGenerator() const -> GeneratorBasePtr const& override { return m_generator; }
12753 void setGenerator(GeneratorBasePtr&& generator) override { m_generator = std::move(generator); }
12754};
12755GeneratorTracker::~GeneratorTracker() {}
12756} // namespace Generators
12757
12758RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12759 : m_runInfo(_config->name()), m_context(getCurrentMutableContext()), m_config(_config),
12760 m_reporter(std::move(reporter)), m_lastAssertionInfo{StringRef(), SourceLineInfo("", 0),
12761 StringRef(), ResultDisposition::Normal},
12762 m_includeSuccessfulResults(m_config->includeSuccessfulResults() ||
12763 m_reporter->getPreferences().shouldReportAllAssertions) {
12764 m_context.setRunner(this);
12765 m_context.setConfig(m_config);
12766 m_context.setResultCapture(this);
12767 m_reporter->testRunStarting(m_runInfo);
12768}
12769
12770RunContext::~RunContext() {
12771 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12772}
12773
12774void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex,
12775 std::size_t groupsCount) {
12776 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12777}
12778
12779void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals,
12780 std::size_t groupIndex, std::size_t groupsCount) {
12781 m_reporter->testGroupEnded(
12782 TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12783}
12784
12785Totals RunContext::runTest(TestCase const& testCase) {
12786 Totals prevTotals = m_totals;
12787
12788 std::string redirectedCout;
12789 std::string redirectedCerr;
12790
12791 auto const& testInfo = testCase.getTestCaseInfo();
12792
12793 m_reporter->testCaseStarting(testInfo);
12794
12795 m_activeTestCase = &testCase;
12796
12797 ITracker& rootTracker = m_trackerContext.startRun();
12798 assert(rootTracker.isSectionTracker());
12799 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12800 do {
12801 m_trackerContext.startCycle();
12802 m_testCaseTracker = &SectionTracker::acquire(
12803 m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12804 runCurrentTest(redirectedCout, redirectedCerr);
12805 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12806
12807 Totals deltaTotals = m_totals.delta(prevTotals);
12808 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12809 deltaTotals.assertions.failed++;
12810 deltaTotals.testCases.passed--;
12811 deltaTotals.testCases.failed++;
12812 }
12813 m_totals.testCases += deltaTotals.testCases;
12814 m_reporter->testCaseEnded(
12815 TestCaseStats(testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting()));
12816
12817 m_activeTestCase = nullptr;
12818 m_testCaseTracker = nullptr;
12819
12820 return deltaTotals;
12821}
12822
12823IConfigPtr RunContext::config() const {
12824 return m_config;
12825}
12826
12827IStreamingReporter& RunContext::reporter() const {
12828 return *m_reporter;
12829}
12830
12831void RunContext::assertionEnded(AssertionResult const& result) {
12832 if (result.getResultType() == ResultWas::Ok) {
12833 m_totals.assertions.passed++;
12834 m_lastAssertionPassed = true;
12835 } else if (!result.isOk()) {
12836 m_lastAssertionPassed = false;
12837 if (m_activeTestCase->getTestCaseInfo().okToFail())
12838 m_totals.assertions.failedButOk++;
12839 else
12840 m_totals.assertions.failed++;
12841 } else {
12842 m_lastAssertionPassed = true;
12843 }
12844
12845 // We have no use for the return value (whether messages should be cleared),
12846 // because messages were made scoped and should be let to clear themselves
12847 // out.
12848 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12849
12850 if (result.getResultType() != ResultWas::Warning)
12851 m_messageScopes.clear();
12852
12853 // Reset working state
12854 resetAssertionInfo();
12855 m_lastResult = result;
12856}
12857void RunContext::resetAssertionInfo() {
12858 m_lastAssertionInfo.macroName = StringRef();
12859 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12860}
12861
12862bool RunContext::sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) {
12863 ITracker& sectionTracker = SectionTracker::acquire(
12864 m_trackerContext,
12865 TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12866 if (!sectionTracker.isOpen())
12867 return false;
12868 m_activeSections.push_back(&sectionTracker);
12869
12870 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12871
12872 m_reporter->sectionStarting(sectionInfo);
12873
12874 assertions = m_totals.assertions;
12875
12876 return true;
12877}
12878auto RunContext::acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
12879 -> IGeneratorTracker& {
12880 using namespace Generators;
12881 GeneratorTracker& tracker = GeneratorTracker::acquire(
12882 m_trackerContext,
12883 TestCaseTracking::NameAndLocation(static_cast<std::string>(generatorName), lineInfo));
12884 m_lastAssertionInfo.lineInfo = lineInfo;
12885 return tracker;
12886}
12887
12888bool RunContext::testForMissingAssertions(Counts& assertions) {
12889 if (assertions.total() != 0)
12890 return false;
12891 if (!m_config->warnAboutMissingAssertions())
12892 return false;
12893 if (m_trackerContext.currentTracker().hasChildren())
12894 return false;
12895 m_totals.assertions.failed++;
12896 assertions.failed++;
12897 return true;
12898}
12899
12900void RunContext::sectionEnded(SectionEndInfo const& endInfo) {
12901 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12902 bool missingAssertions = testForMissingAssertions(assertions);
12903
12904 if (!m_activeSections.empty()) {
12905 m_activeSections.back()->close();
12906 m_activeSections.pop_back();
12907 }
12908
12909 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions,
12910 endInfo.durationInSeconds, missingAssertions));
12911 m_messages.clear();
12912 m_messageScopes.clear();
12913}
12914
12915void RunContext::sectionEndedEarly(SectionEndInfo const& endInfo) {
12916 if (m_unfinishedSections.empty())
12917 m_activeSections.back()->fail();
12918 else
12919 m_activeSections.back()->close();
12920 m_activeSections.pop_back();
12921
12922 m_unfinishedSections.push_back(endInfo);
12923}
12924
12925#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12926void RunContext::benchmarkPreparing(std::string const& name) {
12927 m_reporter->benchmarkPreparing(name);
12928}
12929void RunContext::benchmarkStarting(BenchmarkInfo const& info) {
12930 m_reporter->benchmarkStarting(info);
12931}
12932void RunContext::benchmarkEnded(BenchmarkStats<> const& stats) {
12933 m_reporter->benchmarkEnded(stats);
12934}
12935void RunContext::benchmarkFailed(std::string const& error) {
12936 m_reporter->benchmarkFailed(error);
12937}
12938#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12939
12940void RunContext::pushScopedMessage(MessageInfo const& message) {
12941 m_messages.push_back(message);
12942}
12943
12944void RunContext::popScopedMessage(MessageInfo const& message) {
12945 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12946}
12947
12948void RunContext::emplaceUnscopedMessage(MessageBuilder const& builder) {
12949 m_messageScopes.emplace_back(builder);
12950}
12951
12952std::string RunContext::getCurrentTestName() const {
12953 return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string();
12954}
12955
12956const AssertionResult* RunContext::getLastResult() const {
12957 return &(*m_lastResult);
12958}
12959
12960void RunContext::exceptionEarlyReported() {
12961 m_shouldReportUnexpected = false;
12962}
12963
12964void RunContext::handleFatalErrorCondition(StringRef message) {
12965 // First notify reporter that bad things happened
12966 m_reporter->fatalErrorEncountered(message);
12967
12968 // Don't rebuild the result -- the stringification itself can cause more fatal
12969 // errors Instead, fake a result data.
12970 AssertionResultData tempResult(ResultWas::FatalErrorCondition, {false});
12971 tempResult.message = static_cast<std::string>(message);
12972 AssertionResult result(m_lastAssertionInfo, tempResult);
12973
12974 assertionEnded(result);
12975
12976 handleUnfinishedSections();
12977
12978 // Recreate section for test case (as we will lose the one that was in scope)
12979 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12980 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12981
12982 Counts assertions;
12983 assertions.failed = 1;
12984 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12985 m_reporter->sectionEnded(testCaseSectionStats);
12986
12987 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12988
12989 Totals deltaTotals;
12990 deltaTotals.testCases.failed = 1;
12991 deltaTotals.assertions.failed = 1;
12992 m_reporter->testCaseEnded(
12993 TestCaseStats(testInfo, deltaTotals, std::string(), std::string(), false));
12994 m_totals.testCases.failed++;
12995 testGroupEnded(std::string(), m_totals, 1, 1);
12996 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12997}
12998
12999bool RunContext::lastAssertionPassed() {
13000 return m_lastAssertionPassed;
13001}
13002
13003void RunContext::assertionPassed() {
13004 m_lastAssertionPassed = true;
13005 ++m_totals.assertions.passed;
13006 resetAssertionInfo();
13007 m_messageScopes.clear();
13008}
13009
13010bool RunContext::aborting() const {
13011 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
13012}
13013
13014void RunContext::runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr) {
13015 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
13016 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13017 m_reporter->sectionStarting(testCaseSection);
13018 Counts prevAssertions = m_totals.assertions;
13019 double duration = 0;
13020 m_shouldReportUnexpected = true;
13021 m_lastAssertionInfo = {"TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(),
13022 ResultDisposition::Normal};
13023
13024 seedRng(*m_config);
13025
13026 Timer timer;
13027 CATCH_TRY {
13028 if (m_reporter->getPreferences().shouldRedirectStdOut) {
13029#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
13030 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
13031
13032 timer.start();
13033 invokeActiveTestCase();
13034#else
13035 OutputRedirect r(redirectedCout, redirectedCerr);
13036 timer.start();
13037 invokeActiveTestCase();
13038#endif
13039 } else {
13040 timer.start();
13041 invokeActiveTestCase();
13042 }
13043 duration = timer.getElapsedSeconds();
13044 }
13045 CATCH_CATCH_ANON(TestFailureException&) {
13046 // This just means the test was aborted due to failure
13047 }
13048 CATCH_CATCH_ALL {
13049 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE
13050 // assertions are reported without translation at the point of origin.
13051 if (m_shouldReportUnexpected) {
13052 AssertionReaction dummyReaction;
13053 handleUnexpectedInflightException(m_lastAssertionInfo, translateActiveException(),
13054 dummyReaction);
13055 }
13056 }
13057 Counts assertions = m_totals.assertions - prevAssertions;
13058 bool missingAssertions = testForMissingAssertions(assertions);
13059
13060 m_testCaseTracker->close();
13061 handleUnfinishedSections();
13062 m_messages.clear();
13063 m_messageScopes.clear();
13064
13065 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13066 m_reporter->sectionEnded(testCaseSectionStats);
13067}
13068
13069void RunContext::invokeActiveTestCase() {
13070 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13071 m_activeTestCase->invoke();
13072}
13073
13074void RunContext::handleUnfinishedSections() {
13075 // If sections ended prematurely due to an exception we stored their
13076 // infos here so we can tear them down outside the unwind process.
13077 for (auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd;
13078 ++it)
13079 sectionEnded(*it);
13080 m_unfinishedSections.clear();
13081}
13082
13083void RunContext::handleExpr(AssertionInfo const& info, ITransientExpression const& expr,
13084 AssertionReaction& reaction) {
13085 m_reporter->assertionStarting(info);
13086
13087 bool negated = isFalseTest(info.resultDisposition);
13088 bool result = expr.getResult() != negated;
13089
13090 if (result) {
13091 if (!m_includeSuccessfulResults) {
13092 assertionPassed();
13093 } else {
13094 reportExpr(info, ResultWas::Ok, &expr, negated);
13095 }
13096 } else {
13097 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated);
13098 populateReaction(reaction);
13099 }
13100}
13101void RunContext::reportExpr(AssertionInfo const& info, ResultWas::OfType resultType,
13102 ITransientExpression const* expr, bool negated) {
13103
13104 m_lastAssertionInfo = info;
13105 AssertionResultData data(resultType, LazyExpression(negated));
13106
13107 AssertionResult assertionResult{info, data};
13108 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13109
13110 assertionEnded(assertionResult);
13111}
13112
13113void RunContext::handleMessage(AssertionInfo const& info, ResultWas::OfType resultType,
13114 StringRef const& message, AssertionReaction& reaction) {
13115 m_reporter->assertionStarting(info);
13116
13117 m_lastAssertionInfo = info;
13118
13119 AssertionResultData data(resultType, LazyExpression(false));
13120 data.message = static_cast<std::string>(message);
13121 AssertionResult assertionResult{m_lastAssertionInfo, data};
13122 assertionEnded(assertionResult);
13123 if (!assertionResult.isOk())
13124 populateReaction(reaction);
13125}
13126void RunContext::handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
13127 AssertionReaction& reaction) {
13128 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13129}
13130
13131void RunContext::handleUnexpectedInflightException(AssertionInfo const& info,
13132 std::string const& message,
13133 AssertionReaction& reaction) {
13134 m_lastAssertionInfo = info;
13135
13136 AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13137 data.message = message;
13138 AssertionResult assertionResult{info, data};
13139 assertionEnded(assertionResult);
13140 populateReaction(reaction);
13141}
13142
13143void RunContext::populateReaction(AssertionReaction& reaction) {
13144 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13145 reaction.shouldThrow =
13146 aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13147}
13148
13149void RunContext::handleIncomplete(AssertionInfo const& info) {
13150 m_lastAssertionInfo = info;
13151
13152 AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13153 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13154 AssertionResult assertionResult{info, data};
13155 assertionEnded(assertionResult);
13156}
13157void RunContext::handleNonExpr(AssertionInfo const& info, ResultWas::OfType resultType,
13158 AssertionReaction& reaction) {
13159 m_lastAssertionInfo = info;
13160
13161 AssertionResultData data(resultType, LazyExpression(false));
13162 AssertionResult assertionResult{info, data};
13163 assertionEnded(assertionResult);
13164
13165 if (!assertionResult.isOk())
13166 populateReaction(reaction);
13167}
13168
13169IResultCapture& getResultCapture() {
13170 if (auto* capture = getCurrentContext().getResultCapture())
13171 return *capture;
13172 else
13173 CATCH_INTERNAL_ERROR("No result capture instance");
13174}
13175
13176void seedRng(IConfig const& config) {
13177 if (config.rngSeed() != 0) {
13178 std::srand(config.rngSeed());
13179 rng().seed(config.rngSeed());
13180 }
13181}
13182
13183unsigned int rngSeed() {
13184 return getCurrentContext().getConfig()->rngSeed();
13185}
13186
13187} // namespace Catch
13188// end catch_run_context.cpp
13189// start catch_section.cpp
13190
13191namespace Catch {
13192
13193Section::Section(SectionInfo const& info)
13194 : m_info(info), m_sectionIncluded(getResultCapture().sectionStarted(m_info, m_assertions)) {
13195 m_timer.start();
13196}
13197
13198Section::~Section() {
13199 if (m_sectionIncluded) {
13200 SectionEndInfo endInfo{m_info, m_assertions, m_timer.getElapsedSeconds()};
13201 if (uncaught_exceptions())
13202 getResultCapture().sectionEndedEarly(endInfo);
13203 else
13204 getResultCapture().sectionEnded(endInfo);
13205 }
13206}
13207
13208// This indicates whether the section should be executed or not
13209Section::operator bool() const {
13210 return m_sectionIncluded;
13211}
13212
13213} // end namespace Catch
13214// end catch_section.cpp
13215// start catch_section_info.cpp
13216
13217namespace Catch {
13218
13219SectionInfo::SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name)
13220 : name(_name), lineInfo(_lineInfo) {}
13221
13222} // end namespace Catch
13223// end catch_section_info.cpp
13224// start catch_session.cpp
13225
13226// start catch_session.h
13227
13228#include <memory>
13229
13230namespace Catch {
13231
13232class Session : NonCopyable {
13233 public:
13234 Session();
13235 ~Session() override;
13236
13237 void showHelp() const;
13238 void libIdentify();
13239
13240 int applyCommandLine(int argc, char const* const* argv);
13241#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13242 int applyCommandLine(int argc, wchar_t const* const* argv);
13243#endif
13244
13245 void useConfigData(ConfigData const& configData);
13246
13247 template <typename CharT> int run(int argc, CharT const* const argv[]) {
13248 if (m_startupExceptions)
13249 return 1;
13250 int returnCode = applyCommandLine(argc, argv);
13251 if (returnCode == 0)
13252 returnCode = run();
13253 return returnCode;
13254 }
13255
13256 int run();
13257
13258 clara::Parser const& cli() const;
13259 void cli(clara::Parser const& newParser);
13260 ConfigData& configData();
13261 Config& config();
13262
13263 private:
13264 int runInternal();
13265
13266 clara::Parser m_cli;
13267 ConfigData m_configData;
13268 std::shared_ptr<Config> m_config;
13269 bool m_startupExceptions = false;
13270};
13271
13272} // end namespace Catch
13273
13274// end catch_session.h
13275// start catch_version.h
13276
13277#include <iosfwd>
13278
13279namespace Catch {
13280
13281// Versioning information
13282struct Version {
13283 Version(Version const&) = delete;
13284 Version& operator=(Version const&) = delete;
13285 Version(unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber,
13286 char const* const _branchName, unsigned int _buildNumber);
13287
13288 unsigned int const majorVersion;
13289 unsigned int const minorVersion;
13290 unsigned int const patchNumber;
13291
13292 // buildNumber is only used if branchName is not null
13293 char const* const branchName;
13294 unsigned int const buildNumber;
13295
13296 friend std::ostream& operator<<(std::ostream& os, Version const& version);
13297};
13298
13299Version const& libraryVersion();
13300} // namespace Catch
13301
13302// end catch_version.h
13303#include <cstdlib>
13304#include <iomanip>
13305#include <iterator>
13306#include <set>
13307
13308namespace Catch {
13309
13310namespace {
13311const int MaxExitCode = 255;
13312
13313IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
13314 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13315 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13316
13317 return reporter;
13318}
13319
13320IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13321 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13322 return createReporter(config->getReporterName(), config);
13323 }
13324
13325 // On older platforms, returning std::unique_ptr<ListeningReporter>
13326 // when the return type is std::unique_ptr<IStreamingReporter>
13327 // doesn't compile without a std::move call. However, this causes
13328 // a warning on newer platforms. Thus, we have to work around
13329 // it a bit and downcast the pointer manually.
13330 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13331 auto& multi = static_cast<ListeningReporter&>(*ret);
13332 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13333 for (auto const& listener : listeners) {
13334 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13335 }
13336 multi.addReporter(createReporter(config->getReporterName(), config));
13337 return ret;
13338}
13339
13340class TestGroup {
13341 public:
13342 explicit TestGroup(std::shared_ptr<Config> const& config)
13343 : m_config{config}, m_context{config, makeReporter(config)} {
13344 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13345 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13346 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13347
13348 if (m_matches.empty() && invalidArgs.empty()) {
13349 for (auto const& test : allTestCases)
13350 if (!test.isHidden())
13351 m_tests.emplace(&test);
13352 } else {
13353 for (auto const& match : m_matches)
13354 m_tests.insert(match.tests.begin(), match.tests.end());
13355 }
13356 }
13357
13358 Totals execute() {
13359 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13360 Totals totals;
13361 m_context.testGroupStarting(m_config->name(), 1, 1);
13362 for (auto const& testCase : m_tests) {
13363 if (!m_context.aborting())
13364 totals += m_context.runTest(*testCase);
13365 else
13366 m_context.reporter().skipTest(*testCase);
13367 }
13368
13369 for (auto const& match : m_matches) {
13370 if (match.tests.empty()) {
13371 m_context.reporter().noMatchingTestCases(match.name);
13372 totals.error = -1;
13373 }
13374 }
13375
13376 if (!invalidArgs.empty()) {
13377 for (auto const& invalidArg : invalidArgs)
13378 m_context.reporter().reportInvalidArguments(invalidArg);
13379 }
13380
13381 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13382 return totals;
13383 }
13384
13385 private:
13386 using Tests = std::set<TestCase const*>;
13387
13388 std::shared_ptr<Config> m_config;
13389 RunContext m_context;
13390 Tests m_tests;
13391 TestSpec::Matches m_matches;
13392};
13393
13394void applyFilenamesAsTags(Catch::IConfig const& config) {
13395 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13396 for (auto& testCase : tests) {
13397 auto tags = testCase.tags;
13398
13399 std::string filename = testCase.lineInfo.file;
13400 auto lastSlash = filename.find_last_of("\\/");
13401 if (lastSlash != std::string::npos) {
13402 filename.erase(0, lastSlash);
13403 filename[0] = '#';
13404 } else {
13405 filename.insert(0, "#");
13406 }
13407
13408 auto lastDot = filename.find_last_of('.');
13409 if (lastDot != std::string::npos) {
13410 filename.erase(lastDot);
13411 }
13412
13413 tags.push_back(std::move(filename));
13414 setTags(testCase, tags);
13415 }
13416}
13417
13418} // namespace
13419
13420Session::Session() {
13421 static bool alreadyInstantiated = false;
13422 if (alreadyInstantiated) {
13423 CATCH_TRY {
13424 CATCH_INTERNAL_ERROR("Only one instance of Catch::Session can ever be used");
13425 }
13426 CATCH_CATCH_ALL {
13427 getMutableRegistryHub().registerStartupException();
13428 }
13429 }
13430
13431 // There cannot be exceptions at startup in no-exception mode.
13432#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13433 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13434 if (!exceptions.empty()) {
13435 config();
13436 getCurrentMutableContext().setConfig(m_config);
13437
13438 m_startupExceptions = true;
13439 Colour colourGuard(Colour::Red);
13440 Catch::cerr() << "Errors occurred during startup!" << '\n';
13441 // iterate over all exceptions and notify user
13442 for (const auto& ex_ptr : exceptions) {
13443 try {
13444 std::rethrow_exception(ex_ptr);
13445 } catch (std::exception const& ex) {
13446 Catch::cerr() << Column(ex.what()).indent(2) << '\n';
13447 }
13448 }
13449 }
13450#endif
13451
13452 alreadyInstantiated = true;
13453 m_cli = makeCommandLineParser(m_configData);
13454}
13455Session::~Session() {
13456 Catch::cleanUp();
13457}
13458
13459void Session::showHelp() const {
13460 Catch::cout() << "\nCatch v" << libraryVersion() << "\n"
13461 << m_cli << std::endl
13462 << "For more detailed usage please see the project docs\n"
13463 << std::endl;
13464}
13465void Session::libIdentify() {
13466 Catch::cout() << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
13467 << std::left << std::setw(16) << "category: " << "testframework\n"
13468 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
13469 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13470}
13471
13472int Session::applyCommandLine(int argc, char const* const* argv) {
13473 if (m_startupExceptions)
13474 return 1;
13475
13476 auto result = m_cli.parse(clara::Args(argc, argv));
13477 if (!result) {
13478 config();
13479 getCurrentMutableContext().setConfig(m_config);
13480 Catch::cerr() << Colour(Colour::Red) << "\nError(s) in input:\n"
13481 << Column(result.errorMessage()).indent(2) << "\n\n";
13482 Catch::cerr() << "Run with -? for usage\n" << std::endl;
13483 return MaxExitCode;
13484 }
13485
13486 if (m_configData.showHelp)
13487 showHelp();
13488 if (m_configData.libIdentify)
13489 libIdentify();
13490 m_config.reset();
13491 return 0;
13492}
13493
13494#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13495int Session::applyCommandLine(int argc, wchar_t const* const* argv) {
13496
13497 char** utf8Argv = new char*[argc];
13498
13499 for (int i = 0; i < argc; ++i) {
13500 int bufSize = WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr);
13501
13502 utf8Argv[i] = new char[bufSize];
13503
13504 WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr);
13505 }
13506
13507 int returnCode = applyCommandLine(argc, utf8Argv);
13508
13509 for (int i = 0; i < argc; ++i)
13510 delete[] utf8Argv[i];
13511
13512 delete[] utf8Argv;
13513
13514 return returnCode;
13515}
13516#endif
13517
13518void Session::useConfigData(ConfigData const& configData) {
13519 m_configData = configData;
13520 m_config.reset();
13521}
13522
13523int Session::run() {
13524 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeStart) != 0) {
13525 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13526 static_cast<void>(std::getchar());
13527 }
13528 int exitCode = runInternal();
13529 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeExit) != 0) {
13530 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode
13531 << std::endl;
13532 static_cast<void>(std::getchar());
13533 }
13534 return exitCode;
13535}
13536
13537clara::Parser const& Session::cli() const {
13538 return m_cli;
13539}
13540void Session::cli(clara::Parser const& newParser) {
13541 m_cli = newParser;
13542}
13543ConfigData& Session::configData() {
13544 return m_configData;
13545}
13546Config& Session::config() {
13547 if (!m_config)
13548 m_config = std::make_shared<Config>(m_configData);
13549 return *m_config;
13550}
13551
13552int Session::runInternal() {
13553 if (m_startupExceptions)
13554 return 1;
13555
13556 if (m_configData.showHelp || m_configData.libIdentify) {
13557 return 0;
13558 }
13559
13560 CATCH_TRY {
13561 config(); // Force config to be constructed
13562
13563 seedRng(*m_config);
13564
13565 if (m_configData.filenamesAsTags)
13566 applyFilenamesAsTags(*m_config);
13567
13568 // Handle list request
13569 if (Option<std::size_t> listed = list(m_config))
13570 return static_cast<int>(*listed);
13571
13572 TestGroup tests{m_config};
13573 auto const totals = tests.execute();
13574
13575 if (m_config->warnAboutNoTests() && totals.error == -1)
13576 return 2;
13577
13578 // Note that on unices only the lower 8 bits are usually used, clamping
13579 // the return value to 255 prevents false negative when some multiple
13580 // of 256 tests has failed
13581 return (std::min)(MaxExitCode,
13582 (std::max)(totals.error, static_cast<int>(totals.assertions.failed)));
13583 }
13584#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13585 catch (std::exception& ex) {
13586 Catch::cerr() << ex.what() << std::endl;
13587 return MaxExitCode;
13588 }
13589#endif
13590}
13591
13592} // end namespace Catch
13593// end catch_session.cpp
13594// start catch_singletons.cpp
13595
13596#include <vector>
13597
13598namespace Catch {
13599
13600namespace {
13601static auto getSingletons() -> std::vector<ISingleton*>*& {
13602 static std::vector<ISingleton*>* g_singletons = nullptr;
13603 if (!g_singletons)
13604 g_singletons = new std::vector<ISingleton*>();
13605 return g_singletons;
13606}
13607} // namespace
13608
13609ISingleton::~ISingleton() {}
13610
13611void addSingleton(ISingleton* singleton) {
13612 getSingletons()->push_back(singleton);
13613}
13614void cleanupSingletons() {
13615 auto& singletons = getSingletons();
13616 for (auto singleton : *singletons)
13617 delete singleton;
13618 delete singletons;
13619 singletons = nullptr;
13620}
13621
13622} // namespace Catch
13623// end catch_singletons.cpp
13624// start catch_startup_exception_registry.cpp
13625
13626#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13627namespace Catch {
13628void StartupExceptionRegistry::add(std::exception_ptr const& exception) noexcept {
13629 CATCH_TRY {
13630 m_exceptions.push_back(exception);
13631 }
13632 CATCH_CATCH_ALL {
13633 // If we run out of memory during start-up there's really not a lot more we
13634 // can do about it
13635 std::terminate();
13636 }
13637}
13638
13639std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
13640 return m_exceptions;
13641}
13642
13643} // end namespace Catch
13644#endif
13645// end catch_startup_exception_registry.cpp
13646// start catch_stream.cpp
13647
13648#include <cstdio>
13649#include <fstream>
13650#include <iostream>
13651#include <memory>
13652#include <sstream>
13653#include <vector>
13654
13655namespace Catch {
13656
13657Catch::IStream::~IStream() = default;
13658
13659namespace Detail {
13660namespace {
13661template <typename WriterF, std::size_t bufferSize = 256>
13662class StreamBufImpl : public std::streambuf {
13663 char data[bufferSize];
13664 WriterF m_writer;
13665
13666 public:
13667 StreamBufImpl() { setp(data, data + sizeof(data)); }
13668
13669 ~StreamBufImpl() noexcept { StreamBufImpl::sync(); }
13670
13671 private:
13672 int overflow(int c) override {
13673 sync();
13674
13675 if (c != EOF) {
13676 if (pbase() == epptr())
13677 m_writer(std::string(1, static_cast<char>(c)));
13678 else
13679 sputc(static_cast<char>(c));
13680 }
13681 return 0;
13682 }
13683
13684 int sync() override {
13685 if (pbase() != pptr()) {
13686 m_writer(std::string(pbase(), static_cast<std::string::size_type>(pptr() - pbase())));
13687 setp(pbase(), epptr());
13688 }
13689 return 0;
13690 }
13691};
13692
13694
13695struct OutputDebugWriter {
13696
13697 void operator()(std::string const& str) { writeToDebugConsole(str); }
13698};
13699
13701
13702class FileStream : public IStream {
13703 mutable std::ofstream m_ofs;
13704
13705 public:
13706 FileStream(StringRef filename) {
13707 m_ofs.open(filename.c_str());
13708 CATCH_ENFORCE(!m_ofs.fail(), "Unable to open file: '" << filename << "'");
13709 }
13710 ~FileStream() override = default;
13711
13712 public: // IStream
13713 std::ostream& stream() const override { return m_ofs; }
13714};
13715
13717
13718class CoutStream : public IStream {
13719 mutable std::ostream m_os;
13720
13721 public:
13722 // Store the streambuf from cout up-front because
13723 // cout may get redirected when running tests
13724 CoutStream() : m_os(Catch::cout().rdbuf()) {}
13725 ~CoutStream() override = default;
13726
13727 public: // IStream
13728 std::ostream& stream() const override { return m_os; }
13729};
13730
13732
13733class DebugOutStream : public IStream {
13734 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13735 mutable std::ostream m_os;
13736
13737 public:
13738 DebugOutStream()
13739 : m_streamBuf(new StreamBufImpl<OutputDebugWriter>()), m_os(m_streamBuf.get()) {}
13740
13741 ~DebugOutStream() override = default;
13742
13743 public: // IStream
13744 std::ostream& stream() const override { return m_os; }
13745};
13746
13747} // namespace
13748} // namespace Detail
13749
13751
13752auto makeStream(StringRef const& filename) -> IStream const* {
13753 if (filename.empty())
13754 return new Detail::CoutStream();
13755 else if (filename[0] == '%') {
13756 if (filename == "%debug")
13757 return new Detail::DebugOutStream();
13758 else
13759 CATCH_ERROR("Unrecognised stream: '" << filename << "'");
13760 } else
13761 return new Detail::FileStream(filename);
13762}
13763
13764// This class encapsulates the idea of a pool of ostringstreams that can be
13765// reused.
13766struct StringStreams {
13767 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13768 std::vector<std::size_t> m_unused;
13769 std::ostringstream m_referenceStream; // Used for copy state/ flags from
13770
13771 auto add() -> std::size_t {
13772 if (m_unused.empty()) {
13773 m_streams.push_back(std::unique_ptr<std::ostringstream>(new std::ostringstream));
13774 return m_streams.size() - 1;
13775 } else {
13776 auto index = m_unused.back();
13777 m_unused.pop_back();
13778 return index;
13779 }
13780 }
13781
13782 void release(std::size_t index) {
13783 m_streams[index]->copyfmt(m_referenceStream); // Restore initial flags and other state
13784 m_unused.push_back(index);
13785 }
13786};
13787
13788ReusableStringStream::ReusableStringStream()
13789 : m_index(Singleton<StringStreams>::getMutable().add()),
13790 m_oss(Singleton<StringStreams>::getMutable().m_streams[m_index].get()) {}
13791
13792ReusableStringStream::~ReusableStringStream() {
13793 static_cast<std::ostringstream*>(m_oss)->str("");
13794 m_oss->clear();
13795 Singleton<StringStreams>::getMutable().release(m_index);
13796}
13797
13798auto ReusableStringStream::str() const -> std::string {
13799 return static_cast<std::ostringstream*>(m_oss)->str();
13800}
13801
13803
13804#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these
13805 // functions
13806std::ostream& cout() {
13807 return std::cout;
13808}
13809std::ostream& cerr() {
13810 return std::cerr;
13811}
13812std::ostream& clog() {
13813 return std::clog;
13814}
13815#endif
13816} // namespace Catch
13817// end catch_stream.cpp
13818// start catch_string_manip.cpp
13819
13820#include <algorithm>
13821#include <cctype>
13822#include <cstring>
13823#include <ostream>
13824#include <vector>
13825
13826namespace Catch {
13827
13828namespace {
13829char toLowerCh(char c) {
13830 return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
13831}
13832} // namespace
13833
13834bool startsWith(std::string const& s, std::string const& prefix) {
13835 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13836}
13837bool startsWith(std::string const& s, char prefix) {
13838 return !s.empty() && s[0] == prefix;
13839}
13840bool endsWith(std::string const& s, std::string const& suffix) {
13841 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13842}
13843bool endsWith(std::string const& s, char suffix) {
13844 return !s.empty() && s[s.size() - 1] == suffix;
13845}
13846bool contains(std::string const& s, std::string const& infix) {
13847 return s.find(infix) != std::string::npos;
13848}
13849void toLowerInPlace(std::string& s) {
13850 std::transform(s.begin(), s.end(), s.begin(), toLowerCh);
13851}
13852std::string toLower(std::string const& s) {
13853 std::string lc = s;
13854 toLowerInPlace(lc);
13855 return lc;
13856}
13857std::string trim(std::string const& str) {
13858 static char const* whitespaceChars = "\n\r\t ";
13859 std::string::size_type start = str.find_first_not_of(whitespaceChars);
13860 std::string::size_type end = str.find_last_not_of(whitespaceChars);
13861
13862 return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
13863}
13864
13865StringRef trim(StringRef ref) {
13866 const auto is_ws = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; };
13867 size_t real_begin = 0;
13868 while (real_begin < ref.size() && is_ws(ref[real_begin])) {
13869 ++real_begin;
13870 }
13871 size_t real_end = ref.size();
13872 while (real_end > real_begin && is_ws(ref[real_end - 1])) {
13873 --real_end;
13874 }
13875
13876 return ref.substr(real_begin, real_end - real_begin);
13877}
13878
13879bool replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis) {
13880 bool replaced = false;
13881 std::size_t i = str.find(replaceThis);
13882 while (i != std::string::npos) {
13883 replaced = true;
13884 str = str.substr(0, i) + withThis + str.substr(i + replaceThis.size());
13885 if (i < str.size() - withThis.size())
13886 i = str.find(replaceThis, i + withThis.size());
13887 else
13888 i = std::string::npos;
13889 }
13890 return replaced;
13891}
13892
13893std::vector<StringRef> splitStringRef(StringRef str, char delimiter) {
13894 std::vector<StringRef> subStrings;
13895 std::size_t start = 0;
13896 for (std::size_t pos = 0; pos < str.size(); ++pos) {
13897 if (str[pos] == delimiter) {
13898 if (pos - start > 1)
13899 subStrings.push_back(str.substr(start, pos - start));
13900 start = pos + 1;
13901 }
13902 }
13903 if (start < str.size())
13904 subStrings.push_back(str.substr(start, str.size() - start));
13905 return subStrings;
13906}
13907
13908pluralise::pluralise(std::size_t count, std::string const& label)
13909 : m_count(count), m_label(label) {}
13910
13911std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser) {
13912 os << pluraliser.m_count << ' ' << pluraliser.m_label;
13913 if (pluraliser.m_count != 1)
13914 os << 's';
13915 return os;
13916}
13917
13918} // namespace Catch
13919// end catch_string_manip.cpp
13920// start catch_stringref.cpp
13921
13922#include <algorithm>
13923#include <cstdint>
13924#include <cstring>
13925#include <ostream>
13926
13927namespace Catch {
13928StringRef::StringRef(char const* rawChars) noexcept
13929 : StringRef(rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars))) {}
13930
13931auto StringRef::c_str() const -> char const* {
13932 CATCH_ENFORCE(isNullTerminated(),
13933 "Called StringRef::c_str() on a non-null-terminated instance");
13934 return m_start;
13935}
13936auto StringRef::data() const noexcept -> char const* {
13937 return m_start;
13938}
13939
13940auto StringRef::substr(size_type start, size_type size) const noexcept -> StringRef {
13941 if (start < m_size) {
13942 return StringRef(m_start + start, (std::min)(m_size - start, size));
13943 } else {
13944 return StringRef();
13945 }
13946}
13947auto StringRef::operator==(StringRef const& other) const noexcept -> bool {
13948 return m_size == other.m_size && (std::memcmp(m_start, other.m_start, m_size) == 0);
13949}
13950
13951auto operator<<(std::ostream& os, StringRef const& str) -> std::ostream& {
13952 return os.write(str.data(), str.size());
13953}
13954
13955auto operator+=(std::string& lhs, StringRef const& rhs) -> std::string& {
13956 lhs.append(rhs.data(), rhs.size());
13957 return lhs;
13958}
13959
13960} // namespace Catch
13961// end catch_stringref.cpp
13962// start catch_tag_alias.cpp
13963
13964namespace Catch {
13965TagAlias::TagAlias(std::string const& _tag, SourceLineInfo _lineInfo)
13966 : tag(_tag), lineInfo(_lineInfo) {}
13967} // namespace Catch
13968// end catch_tag_alias.cpp
13969// start catch_tag_alias_autoregistrar.cpp
13970
13971namespace Catch {
13972
13973RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag,
13974 SourceLineInfo const& lineInfo) {
13975 CATCH_TRY {
13976 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13977 }
13978 CATCH_CATCH_ALL {
13979 // Do not throw when constructing global objects, instead register the
13980 // exception to be processed later
13981 getMutableRegistryHub().registerStartupException();
13982 }
13983}
13984
13985} // namespace Catch
13986// end catch_tag_alias_autoregistrar.cpp
13987// start catch_tag_alias_registry.cpp
13988
13989#include <sstream>
13990
13991namespace Catch {
13992
13993TagAliasRegistry::~TagAliasRegistry() {}
13994
13995TagAlias const* TagAliasRegistry::find(std::string const& alias) const {
13996 auto it = m_registry.find(alias);
13997 if (it != m_registry.end())
13998 return &(it->second);
13999 else
14000 return nullptr;
14001}
14002
14003std::string TagAliasRegistry::expandAliases(std::string const& unexpandedTestSpec) const {
14004 std::string expandedTestSpec = unexpandedTestSpec;
14005 for (auto const& registryKvp : m_registry) {
14006 std::size_t pos = expandedTestSpec.find(registryKvp.first);
14007 if (pos != std::string::npos) {
14008 expandedTestSpec = expandedTestSpec.substr(0, pos) + registryKvp.second.tag +
14009 expandedTestSpec.substr(pos + registryKvp.first.size());
14010 }
14011 }
14012 return expandedTestSpec;
14013}
14014
14015void TagAliasRegistry::add(std::string const& alias, std::string const& tag,
14016 SourceLineInfo const& lineInfo) {
14017 CATCH_ENFORCE(startsWith(alias, "[@") && endsWith(alias, ']'),
14018 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n"
14019 << lineInfo);
14020
14021 CATCH_ENFORCE(m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14022 "error: tag alias, '" << alias << "' already registered.\n"
14023 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
14024 << "\tRedefined at: " << lineInfo);
14025}
14026
14027ITagAliasRegistry::~ITagAliasRegistry() {}
14028
14029ITagAliasRegistry const& ITagAliasRegistry::get() {
14030 return getRegistryHub().getTagAliasRegistry();
14031}
14032
14033} // end namespace Catch
14034// end catch_tag_alias_registry.cpp
14035// start catch_test_case_info.cpp
14036
14037#include <algorithm>
14038#include <cctype>
14039#include <exception>
14040#include <sstream>
14041
14042namespace Catch {
14043
14044namespace {
14045TestCaseInfo::SpecialProperties parseSpecialTag(std::string const& tag) {
14046 if (startsWith(tag, '.') || tag == "!hide")
14047 return TestCaseInfo::IsHidden;
14048 else if (tag == "!throws")
14049 return TestCaseInfo::Throws;
14050 else if (tag == "!shouldfail")
14051 return TestCaseInfo::ShouldFail;
14052 else if (tag == "!mayfail")
14053 return TestCaseInfo::MayFail;
14054 else if (tag == "!nonportable")
14055 return TestCaseInfo::NonPortable;
14056 else if (tag == "!benchmark")
14057 return static_cast<TestCaseInfo::SpecialProperties>(TestCaseInfo::Benchmark |
14058 TestCaseInfo::IsHidden);
14059 else
14060 return TestCaseInfo::None;
14061}
14062bool isReservedTag(std::string const& tag) {
14063 return parseSpecialTag(tag) == TestCaseInfo::None && tag.size() > 0 &&
14064 !std::isalnum(static_cast<unsigned char>(tag[0]));
14065}
14066void enforceNotReservedTag(std::string const& tag, SourceLineInfo const& _lineInfo) {
14067 CATCH_ENFORCE(!isReservedTag(tag), "Tag name: [" << tag << "] is not allowed.\n"
14068 << "Tag names starting with non alphanumeric "
14069 "characters are reserved\n"
14070 << _lineInfo);
14071}
14072} // namespace
14073
14074TestCase makeTestCase(ITestInvoker* _testCase, std::string const& _className,
14075 NameAndTags const& nameAndTags, SourceLineInfo const& _lineInfo) {
14076 bool isHidden = false;
14077
14078 // Parse out tags
14079 std::vector<std::string> tags;
14080 std::string desc, tag;
14081 bool inTag = false;
14082 for (char c : nameAndTags.tags) {
14083 if (!inTag) {
14084 if (c == '[')
14085 inTag = true;
14086 else
14087 desc += c;
14088 } else {
14089 if (c == ']') {
14090 TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag);
14091 if ((prop & TestCaseInfo::IsHidden) != 0)
14092 isHidden = true;
14093 else if (prop == TestCaseInfo::None)
14094 enforceNotReservedTag(tag, _lineInfo);
14095
14096 // Merged hide tags like `[.approvals]` should be added as
14097 // `[.][approvals]`. The `[.]` is added at later point, so
14098 // we only strip the prefix
14099 if (startsWith(tag, '.') && tag.size() > 1) {
14100 tag.erase(0, 1);
14101 }
14102 tags.push_back(tag);
14103 tag.clear();
14104 inTag = false;
14105 } else
14106 tag += c;
14107 }
14108 }
14109 if (isHidden) {
14110 // Add all "hidden" tags to make them behave identically
14111 tags.insert(tags.end(), {".", "!hide"});
14112 }
14113
14114 TestCaseInfo info(static_cast<std::string>(nameAndTags.name), _className, desc, tags,
14115 _lineInfo);
14116 return TestCase(_testCase, std::move(info));
14117}
14118
14119void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags) {
14120 std::sort(begin(tags), end(tags));
14121 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14122 testCaseInfo.lcaseTags.clear();
14123
14124 for (auto const& tag : tags) {
14125 std::string lcaseTag = toLower(tag);
14126 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>(
14127 testCaseInfo.properties | parseSpecialTag(lcaseTag));
14128 testCaseInfo.lcaseTags.push_back(lcaseTag);
14129 }
14130 testCaseInfo.tags = std::move(tags);
14131}
14132
14133TestCaseInfo::TestCaseInfo(std::string const& _name, std::string const& _className,
14134 std::string const& _description, std::vector<std::string> const& _tags,
14135 SourceLineInfo const& _lineInfo)
14136 : name(_name), className(_className), description(_description), lineInfo(_lineInfo),
14137 properties(None) {
14138 setTags(*this, _tags);
14139}
14140
14141bool TestCaseInfo::isHidden() const {
14142 return (properties & IsHidden) != 0;
14143}
14144bool TestCaseInfo::throws() const {
14145 return (properties & Throws) != 0;
14146}
14147bool TestCaseInfo::okToFail() const {
14148 return (properties & (ShouldFail | MayFail)) != 0;
14149}
14150bool TestCaseInfo::expectedToFail() const {
14151 return (properties & (ShouldFail)) != 0;
14152}
14153
14154std::string TestCaseInfo::tagsAsString() const {
14155 std::string ret;
14156 // '[' and ']' per tag
14157 std::size_t full_size = 2 * tags.size();
14158 for (const auto& tag : tags) {
14159 full_size += tag.size();
14160 }
14161 ret.reserve(full_size);
14162 for (const auto& tag : tags) {
14163 ret.push_back('[');
14164 ret.append(tag);
14165 ret.push_back(']');
14166 }
14167
14168 return ret;
14169}
14170
14171TestCase::TestCase(ITestInvoker* testCase, TestCaseInfo&& info)
14172 : TestCaseInfo(std::move(info)), test(testCase) {}
14173
14174TestCase TestCase::withName(std::string const& _newName) const {
14175 TestCase other(*this);
14176 other.name = _newName;
14177 return other;
14178}
14179
14180void TestCase::invoke() const {
14181 test->invoke();
14182}
14183
14184bool TestCase::operator==(TestCase const& other) const {
14185 return test.get() == other.test.get() && name == other.name && className == other.className;
14186}
14187
14188bool TestCase::operator<(TestCase const& other) const {
14189 return name < other.name;
14190}
14191
14192TestCaseInfo const& TestCase::getTestCaseInfo() const {
14193 return *this;
14194}
14195
14196} // end namespace Catch
14197// end catch_test_case_info.cpp
14198// start catch_test_case_registry_impl.cpp
14199
14200#include <algorithm>
14201#include <sstream>
14202
14203namespace Catch {
14204
14205namespace {
14206struct TestHasher {
14207 using hash_t = uint64_t;
14208
14209 explicit TestHasher(hash_t hashSuffix) : m_hashSuffix{hashSuffix} {}
14210
14211 uint32_t operator()(TestCase const& t) const {
14212 // FNV-1a hash with multiplication fold.
14213 const hash_t prime = 1099511628211u;
14214 hash_t hash = 14695981039346656037u;
14215 for (const char c : t.name) {
14216 hash ^= c;
14217 hash *= prime;
14218 }
14219 hash ^= m_hashSuffix;
14220 hash *= prime;
14221 const uint32_t low{static_cast<uint32_t>(hash)};
14222 const uint32_t high{static_cast<uint32_t>(hash >> 32)};
14223 return low * high;
14224 }
14225
14226 private:
14227 hash_t m_hashSuffix;
14228};
14229} // end unnamed namespace
14230
14231std::vector<TestCase> sortTests(IConfig const& config,
14232 std::vector<TestCase> const& unsortedTestCases) {
14233 switch (config.runOrder()) {
14234 case RunTests::InDeclarationOrder:
14235 // already in declaration order
14236 break;
14237
14238 case RunTests::InLexicographicalOrder: {
14239 std::vector<TestCase> sorted = unsortedTestCases;
14240 std::sort(sorted.begin(), sorted.end());
14241 return sorted;
14242 }
14243
14244 case RunTests::InRandomOrder: {
14245 seedRng(config);
14246 TestHasher h{config.rngSeed()};
14247
14248 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14249 std::vector<hashedTest> indexed_tests;
14250 indexed_tests.reserve(unsortedTestCases.size());
14251
14252 for (auto const& testCase : unsortedTestCases) {
14253 indexed_tests.emplace_back(h(testCase), &testCase);
14254 }
14255
14256 std::sort(indexed_tests.begin(), indexed_tests.end(),
14257 [](hashedTest const& lhs, hashedTest const& rhs) {
14258 if (lhs.first == rhs.first) {
14259 return lhs.second->name < rhs.second->name;
14260 }
14261 return lhs.first < rhs.first;
14262 });
14263
14264 std::vector<TestCase> sorted;
14265 sorted.reserve(indexed_tests.size());
14266
14267 for (auto const& hashed : indexed_tests) {
14268 sorted.emplace_back(*hashed.second);
14269 }
14270
14271 return sorted;
14272 }
14273 }
14274 return unsortedTestCases;
14275}
14276
14277bool isThrowSafe(TestCase const& testCase, IConfig const& config) {
14278 return !testCase.throws() || config.allowThrows();
14279}
14280
14281bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config) {
14282 return testSpec.matches(testCase) && isThrowSafe(testCase, config);
14283}
14284
14285void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions) {
14286 std::set<TestCase> seenFunctions;
14287 for (auto const& function : functions) {
14288 auto prev = seenFunctions.insert(function);
14289 CATCH_ENFORCE(prev.second, "error: TEST_CASE( \""
14290 << function.name << "\" ) already defined.\n"
14291 << "\tFirst seen at "
14292 << prev.first->getTestCaseInfo().lineInfo << "\n"
14293 << "\tRedefined at " << function.getTestCaseInfo().lineInfo);
14294 }
14295}
14296
14297std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases, TestSpec const& testSpec,
14298 IConfig const& config) {
14299 std::vector<TestCase> filtered;
14300 filtered.reserve(testCases.size());
14301 for (auto const& testCase : testCases) {
14302 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14303 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14304 filtered.push_back(testCase);
14305 }
14306 }
14307 return filtered;
14308}
14309std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config) {
14310 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config);
14311}
14312
14313void TestRegistry::registerTest(TestCase const& testCase) {
14314 std::string name = testCase.getTestCaseInfo().name;
14315 if (name.empty()) {
14316 ReusableStringStream rss;
14317 rss << "Anonymous test case " << ++m_unnamedCount;
14318 return registerTest(testCase.withName(rss.str()));
14319 }
14320 m_functions.push_back(testCase);
14321}
14322
14323std::vector<TestCase> const& TestRegistry::getAllTests() const {
14324 return m_functions;
14325}
14326std::vector<TestCase> const& TestRegistry::getAllTestsSorted(IConfig const& config) const {
14327 if (m_sortedFunctions.empty())
14328 enforceNoDuplicateTestCases(m_functions);
14329
14330 if (m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty()) {
14331 m_sortedFunctions = sortTests(config, m_functions);
14332 m_currentSortOrder = config.runOrder();
14333 }
14334 return m_sortedFunctions;
14335}
14336
14338TestInvokerAsFunction::TestInvokerAsFunction(void (*testAsFunction)()) noexcept
14339 : m_testAsFunction(testAsFunction) {}
14340
14341void TestInvokerAsFunction::invoke() const {
14342 m_testAsFunction();
14343}
14344
14345std::string extractClassName(StringRef const& classOrQualifiedMethodName) {
14346 std::string className(classOrQualifiedMethodName);
14347 if (startsWith(className, '&')) {
14348 std::size_t lastColons = className.rfind("::");
14349 std::size_t penultimateColons = className.rfind("::", lastColons - 1);
14350 if (penultimateColons == std::string::npos)
14351 penultimateColons = 1;
14352 className = className.substr(penultimateColons, lastColons - penultimateColons);
14353 }
14354 return className;
14355}
14356
14357} // end namespace Catch
14358// end catch_test_case_registry_impl.cpp
14359// start catch_test_case_tracker.cpp
14360
14361#include <algorithm>
14362#include <cassert>
14363#include <memory>
14364#include <sstream>
14365#include <stdexcept>
14366
14367#if defined(__clang__)
14368#pragma clang diagnostic push
14369#pragma clang diagnostic ignored "-Wexit-time-destructors"
14370#endif
14371
14372namespace Catch {
14373namespace TestCaseTracking {
14374
14375NameAndLocation::NameAndLocation(std::string const& _name, SourceLineInfo const& _location)
14376 : name(_name), location(_location) {}
14377
14378ITracker::~ITracker() = default;
14379
14380ITracker& TrackerContext::startRun() {
14381 m_rootTracker = std::make_shared<SectionTracker>(
14382 NameAndLocation("{root}", CATCH_INTERNAL_LINEINFO), *this, nullptr);
14383 m_currentTracker = nullptr;
14384 m_runState = Executing;
14385 return *m_rootTracker;
14386}
14387
14388void TrackerContext::endRun() {
14389 m_rootTracker.reset();
14390 m_currentTracker = nullptr;
14391 m_runState = NotStarted;
14392}
14393
14394void TrackerContext::startCycle() {
14395 m_currentTracker = m_rootTracker.get();
14396 m_runState = Executing;
14397}
14398void TrackerContext::completeCycle() {
14399 m_runState = CompletedCycle;
14400}
14401
14402bool TrackerContext::completedCycle() const {
14403 return m_runState == CompletedCycle;
14404}
14405ITracker& TrackerContext::currentTracker() {
14406 return *m_currentTracker;
14407}
14408void TrackerContext::setCurrentTracker(ITracker* tracker) {
14409 m_currentTracker = tracker;
14410}
14411
14412TrackerBase::TrackerBase(NameAndLocation const& nameAndLocation, TrackerContext& ctx,
14413 ITracker* parent)
14414 : ITracker(nameAndLocation), m_ctx(ctx), m_parent(parent) {}
14415
14416bool TrackerBase::isComplete() const {
14417 return m_runState == CompletedSuccessfully || m_runState == Failed;
14418}
14419bool TrackerBase::isSuccessfullyCompleted() const {
14420 return m_runState == CompletedSuccessfully;
14421}
14422bool TrackerBase::isOpen() const {
14423 return m_runState != NotStarted && !isComplete();
14424}
14425bool TrackerBase::hasChildren() const {
14426 return !m_children.empty();
14427}
14428
14429void TrackerBase::addChild(ITrackerPtr const& child) {
14430 m_children.push_back(child);
14431}
14432
14433ITrackerPtr TrackerBase::findChild(NameAndLocation const& nameAndLocation) {
14434 auto it = std::find_if(
14435 m_children.begin(), m_children.end(), [&nameAndLocation](ITrackerPtr const& tracker) {
14436 return tracker->nameAndLocation().location == nameAndLocation.location &&
14437 tracker->nameAndLocation().name == nameAndLocation.name;
14438 });
14439 return (it != m_children.end()) ? *it : nullptr;
14440}
14441ITracker& TrackerBase::parent() {
14442 assert(m_parent); // Should always be non-null except for root
14443 return *m_parent;
14444}
14445
14446void TrackerBase::openChild() {
14447 if (m_runState != ExecutingChildren) {
14448 m_runState = ExecutingChildren;
14449 if (m_parent)
14450 m_parent->openChild();
14451 }
14452}
14453
14454bool TrackerBase::isSectionTracker() const {
14455 return false;
14456}
14457bool TrackerBase::isGeneratorTracker() const {
14458 return false;
14459}
14460
14461void TrackerBase::open() {
14462 m_runState = Executing;
14463 moveToThis();
14464 if (m_parent)
14465 m_parent->openChild();
14466}
14467
14468void TrackerBase::close() {
14469
14470 // Close any still open children (e.g. generators)
14471 while (&m_ctx.currentTracker() != this)
14472 m_ctx.currentTracker().close();
14473
14474 switch (m_runState) {
14475 case NeedsAnotherRun:
14476 break;
14477
14478 case Executing:
14479 m_runState = CompletedSuccessfully;
14480 break;
14481 case ExecutingChildren:
14482 if (std::all_of(m_children.begin(), m_children.end(),
14483 [](ITrackerPtr const& t) { return t->isComplete(); }))
14484 m_runState = CompletedSuccessfully;
14485 break;
14486
14487 case NotStarted:
14488 case CompletedSuccessfully:
14489 case Failed:
14490 CATCH_INTERNAL_ERROR("Illogical state: " << m_runState);
14491
14492 default:
14493 CATCH_INTERNAL_ERROR("Unknown state: " << m_runState);
14494 }
14495 moveToParent();
14496 m_ctx.completeCycle();
14497}
14498void TrackerBase::fail() {
14499 m_runState = Failed;
14500 if (m_parent)
14501 m_parent->markAsNeedingAnotherRun();
14502 moveToParent();
14503 m_ctx.completeCycle();
14504}
14505void TrackerBase::markAsNeedingAnotherRun() {
14506 m_runState = NeedsAnotherRun;
14507}
14508
14509void TrackerBase::moveToParent() {
14510 assert(m_parent);
14511 m_ctx.setCurrentTracker(m_parent);
14512}
14513void TrackerBase::moveToThis() {
14514 m_ctx.setCurrentTracker(this);
14515}
14516
14517SectionTracker::SectionTracker(NameAndLocation const& nameAndLocation, TrackerContext& ctx,
14518 ITracker* parent)
14519 : TrackerBase(nameAndLocation, ctx, parent), m_trimmed_name(trim(nameAndLocation.name)) {
14520 if (parent) {
14521 while (!parent->isSectionTracker())
14522 parent = &parent->parent();
14523
14524 SectionTracker& parentSection = static_cast<SectionTracker&>(*parent);
14525 addNextFilters(parentSection.m_filters);
14526 }
14527}
14528
14529bool SectionTracker::isComplete() const {
14530 bool complete = true;
14531
14532 if (m_filters.empty() || m_filters[0] == "" ||
14533 std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14534 complete = TrackerBase::isComplete();
14535 }
14536 return complete;
14537}
14538
14539bool SectionTracker::isSectionTracker() const {
14540 return true;
14541}
14542
14543SectionTracker& SectionTracker::acquire(TrackerContext& ctx,
14544 NameAndLocation const& nameAndLocation) {
14545 std::shared_ptr<SectionTracker> section;
14546
14547 ITracker& currentTracker = ctx.currentTracker();
14548 if (ITrackerPtr childTracker = currentTracker.findChild(nameAndLocation)) {
14549 assert(childTracker);
14550 assert(childTracker->isSectionTracker());
14551 section = std::static_pointer_cast<SectionTracker>(childTracker);
14552 } else {
14553 section = std::make_shared<SectionTracker>(nameAndLocation, ctx, &currentTracker);
14554 currentTracker.addChild(section);
14555 }
14556 if (!ctx.completedCycle())
14557 section->tryOpen();
14558 return *section;
14559}
14560
14561void SectionTracker::tryOpen() {
14562 if (!isComplete())
14563 open();
14564}
14565
14566void SectionTracker::addInitialFilters(std::vector<std::string> const& filters) {
14567 if (!filters.empty()) {
14568 m_filters.reserve(m_filters.size() + filters.size() + 2);
14569 m_filters.emplace_back(""); // Root - should never be consulted
14570 m_filters.emplace_back(""); // Test Case - not a section filter
14571 m_filters.insert(m_filters.end(), filters.begin(), filters.end());
14572 }
14573}
14574void SectionTracker::addNextFilters(std::vector<std::string> const& filters) {
14575 if (filters.size() > 1)
14576 m_filters.insert(m_filters.end(), filters.begin() + 1, filters.end());
14577}
14578
14579std::vector<std::string> const& SectionTracker::getFilters() const {
14580 return m_filters;
14581}
14582
14583std::string const& SectionTracker::trimmedName() const {
14584 return m_trimmed_name;
14585}
14586
14587} // namespace TestCaseTracking
14588
14589using TestCaseTracking::ITracker;
14590using TestCaseTracking::SectionTracker;
14591using TestCaseTracking::TrackerContext;
14592
14593} // namespace Catch
14594
14595#if defined(__clang__)
14596#pragma clang diagnostic pop
14597#endif
14598// end catch_test_case_tracker.cpp
14599// start catch_test_registry.cpp
14600
14601namespace Catch {
14602
14603auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker* {
14604 return new (std::nothrow) TestInvokerAsFunction(testAsFunction);
14605}
14606
14607NameAndTags::NameAndTags(StringRef const& name_, StringRef const& tags_) noexcept
14608 : name(name_), tags(tags_) {}
14609
14610AutoReg::AutoReg(ITestInvoker* invoker, SourceLineInfo const& lineInfo,
14611 StringRef const& classOrMethod, NameAndTags const& nameAndTags) noexcept {
14612 CATCH_TRY {
14613 getMutableRegistryHub().registerTest(
14614 makeTestCase(invoker, extractClassName(classOrMethod), nameAndTags, lineInfo));
14615 }
14616 CATCH_CATCH_ALL {
14617 // Do not throw when constructing global objects, instead register the
14618 // exception to be processed later
14619 getMutableRegistryHub().registerStartupException();
14620 }
14621}
14622
14623AutoReg::~AutoReg() = default;
14624} // namespace Catch
14625// end catch_test_registry.cpp
14626// start catch_test_spec.cpp
14627
14628#include <algorithm>
14629#include <memory>
14630#include <string>
14631#include <vector>
14632
14633namespace Catch {
14634
14635TestSpec::Pattern::Pattern(std::string const& name) : m_name(name) {}
14636
14637TestSpec::Pattern::~Pattern() = default;
14638
14639std::string const& TestSpec::Pattern::name() const {
14640 return m_name;
14641}
14642
14643TestSpec::NamePattern::NamePattern(std::string const& name, std::string const& filterString)
14644 : Pattern(filterString), m_wildcardPattern(toLower(name), CaseSensitive::No) {}
14645
14646bool TestSpec::NamePattern::matches(TestCaseInfo const& testCase) const {
14647 return m_wildcardPattern.matches(testCase.name);
14648}
14649
14650TestSpec::TagPattern::TagPattern(std::string const& tag, std::string const& filterString)
14651 : Pattern(filterString), m_tag(toLower(tag)) {}
14652
14653bool TestSpec::TagPattern::matches(TestCaseInfo const& testCase) const {
14654 return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) !=
14655 end(testCase.lcaseTags);
14656}
14657
14658TestSpec::ExcludedPattern::ExcludedPattern(PatternPtr const& underlyingPattern)
14659 : Pattern(underlyingPattern->name()), m_underlyingPattern(underlyingPattern) {}
14660
14661bool TestSpec::ExcludedPattern::matches(TestCaseInfo const& testCase) const {
14662 return !m_underlyingPattern->matches(testCase);
14663}
14664
14665bool TestSpec::Filter::matches(TestCaseInfo const& testCase) const {
14666 return std::all_of(m_patterns.begin(), m_patterns.end(),
14667 [&](PatternPtr const& p) { return p->matches(testCase); });
14668}
14669
14670std::string TestSpec::Filter::name() const {
14671 std::string name;
14672 for (auto const& p : m_patterns)
14673 name += p->name();
14674 return name;
14675}
14676
14677bool TestSpec::hasFilters() const {
14678 return !m_filters.empty();
14679}
14680
14681bool TestSpec::matches(TestCaseInfo const& testCase) const {
14682 return std::any_of(m_filters.begin(), m_filters.end(),
14683 [&](Filter const& f) { return f.matches(testCase); });
14684}
14685
14686TestSpec::Matches TestSpec::matchesByFilter(std::vector<TestCase> const& testCases,
14687 IConfig const& config) const {
14688 Matches matches(m_filters.size());
14689 std::transform(m_filters.begin(), m_filters.end(), matches.begin(), [&](Filter const& filter) {
14690 std::vector<TestCase const*> currentMatches;
14691 for (auto const& test : testCases)
14692 if (isThrowSafe(test, config) && filter.matches(test))
14693 currentMatches.emplace_back(&test);
14694 return FilterMatch{filter.name(), currentMatches};
14695 });
14696 return matches;
14697}
14698
14699const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const {
14700 return (m_invalidArgs);
14701}
14702
14703} // namespace Catch
14704// end catch_test_spec.cpp
14705// start catch_test_spec_parser.cpp
14706
14707namespace Catch {
14708
14709TestSpecParser::TestSpecParser(ITagAliasRegistry const& tagAliases) : m_tagAliases(&tagAliases) {}
14710
14711TestSpecParser& TestSpecParser::parse(std::string const& arg) {
14712 m_mode = None;
14713 m_exclusion = false;
14714 m_arg = m_tagAliases->expandAliases(arg);
14715 m_escapeChars.clear();
14716 m_substring.reserve(m_arg.size());
14717 m_patternName.reserve(m_arg.size());
14718 m_realPatternPos = 0;
14719
14720 for (m_pos = 0; m_pos < m_arg.size(); ++m_pos)
14721 // if visitChar fails
14722 if (!visitChar(m_arg[m_pos])) {
14723 m_testSpec.m_invalidArgs.push_back(arg);
14724 break;
14725 }
14726 endMode();
14727 return *this;
14728}
14729TestSpec TestSpecParser::testSpec() {
14730 addFilter();
14731 return m_testSpec;
14732}
14733bool TestSpecParser::visitChar(char c) {
14734 if ((m_mode != EscapedName) && (c == '\\')) {
14735 escape();
14736 addCharToPattern(c);
14737 return true;
14738 } else if ((m_mode != EscapedName) && (c == ',')) {
14739 return separate();
14740 }
14741
14742 switch (m_mode) {
14743 case None:
14744 if (processNoneChar(c))
14745 return true;
14746 break;
14747 case Name:
14748 processNameChar(c);
14749 break;
14750 case EscapedName:
14751 endMode();
14752 addCharToPattern(c);
14753 return true;
14754 default:
14755 case Tag:
14756 case QuotedName:
14757 if (processOtherChar(c))
14758 return true;
14759 break;
14760 }
14761
14762 m_substring += c;
14763 if (!isControlChar(c)) {
14764 m_patternName += c;
14765 m_realPatternPos++;
14766 }
14767 return true;
14768}
14769// Two of the processing methods return true to signal the caller to return
14770// without adding the given character to the current pattern strings
14771bool TestSpecParser::processNoneChar(char c) {
14772 switch (c) {
14773 case ' ':
14774 return true;
14775 case '~':
14776 m_exclusion = true;
14777 return false;
14778 case '[':
14779 startNewMode(Tag);
14780 return false;
14781 case '"':
14782 startNewMode(QuotedName);
14783 return false;
14784 default:
14785 startNewMode(Name);
14786 return false;
14787 }
14788}
14789void TestSpecParser::processNameChar(char c) {
14790 if (c == '[') {
14791 if (m_substring == "exclude:")
14792 m_exclusion = true;
14793 else
14794 endMode();
14795 startNewMode(Tag);
14796 }
14797}
14798bool TestSpecParser::processOtherChar(char c) {
14799 if (!isControlChar(c))
14800 return false;
14801 m_substring += c;
14802 endMode();
14803 return true;
14804}
14805void TestSpecParser::startNewMode(Mode mode) {
14806 m_mode = mode;
14807}
14808void TestSpecParser::endMode() {
14809 switch (m_mode) {
14810 case Name:
14811 case QuotedName:
14812 return addNamePattern();
14813 case Tag:
14814 return addTagPattern();
14815 case EscapedName:
14816 revertBackToLastMode();
14817 return;
14818 case None:
14819 default:
14820 return startNewMode(None);
14821 }
14822}
14823void TestSpecParser::escape() {
14824 saveLastMode();
14825 m_mode = EscapedName;
14826 m_escapeChars.push_back(m_realPatternPos);
14827}
14828bool TestSpecParser::isControlChar(char c) const {
14829 switch (m_mode) {
14830 default:
14831 return false;
14832 case None:
14833 return c == '~';
14834 case Name:
14835 return c == '[';
14836 case EscapedName:
14837 return true;
14838 case QuotedName:
14839 return c == '"';
14840 case Tag:
14841 return c == '[' || c == ']';
14842 }
14843}
14844
14845void TestSpecParser::addFilter() {
14846 if (!m_currentFilter.m_patterns.empty()) {
14847 m_testSpec.m_filters.push_back(m_currentFilter);
14848 m_currentFilter = TestSpec::Filter();
14849 }
14850}
14851
14852void TestSpecParser::saveLastMode() {
14853 lastMode = m_mode;
14854}
14855
14856void TestSpecParser::revertBackToLastMode() {
14857 m_mode = lastMode;
14858}
14859
14860bool TestSpecParser::separate() {
14861 if ((m_mode == QuotedName) || (m_mode == Tag)) {
14862 // invalid argument, signal failure to previous scope.
14863 m_mode = None;
14864 m_pos = m_arg.size();
14865 m_substring.clear();
14866 m_patternName.clear();
14867 m_realPatternPos = 0;
14868 return false;
14869 }
14870 endMode();
14871 addFilter();
14872 return true; // success
14873}
14874
14875std::string TestSpecParser::preprocessPattern() {
14876 std::string token = m_patternName;
14877 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14878 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14879 m_escapeChars.clear();
14880 if (startsWith(token, "exclude:")) {
14881 m_exclusion = true;
14882 token = token.substr(8);
14883 }
14884
14885 m_patternName.clear();
14886 m_realPatternPos = 0;
14887
14888 return token;
14889}
14890
14891void TestSpecParser::addNamePattern() {
14892 auto token = preprocessPattern();
14893
14894 if (!token.empty()) {
14895 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14896 if (m_exclusion)
14897 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14898 m_currentFilter.m_patterns.push_back(pattern);
14899 }
14900 m_substring.clear();
14901 m_exclusion = false;
14902 m_mode = None;
14903}
14904
14905void TestSpecParser::addTagPattern() {
14906 auto token = preprocessPattern();
14907
14908 if (!token.empty()) {
14909 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
14910 // we have to create a separate hide tag and shorten the real one
14911 if (token.size() > 1 && token[0] == '.') {
14912 token.erase(token.begin());
14913 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
14914 if (m_exclusion) {
14915 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14916 }
14917 m_currentFilter.m_patterns.push_back(pattern);
14918 }
14919
14920 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14921
14922 if (m_exclusion) {
14923 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14924 }
14925 m_currentFilter.m_patterns.push_back(pattern);
14926 }
14927 m_substring.clear();
14928 m_exclusion = false;
14929 m_mode = None;
14930}
14931
14932TestSpec parseTestSpec(std::string const& arg) {
14933 return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec();
14934}
14935
14936} // namespace Catch
14937// end catch_test_spec_parser.cpp
14938// start catch_timer.cpp
14939
14940#include <chrono>
14941
14942static const uint64_t nanosecondsInSecond = 1000000000;
14943
14944namespace Catch {
14945
14946auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14947 return std::chrono::duration_cast<std::chrono::nanoseconds>(
14948 std::chrono::high_resolution_clock::now().time_since_epoch())
14949 .count();
14950}
14951
14952namespace {
14953auto estimateClockResolution() -> uint64_t {
14954 uint64_t sum = 0;
14955 static const uint64_t iterations = 1000000;
14956
14957 auto startTime = getCurrentNanosecondsSinceEpoch();
14958
14959 for (std::size_t i = 0; i < iterations; ++i) {
14960
14961 uint64_t ticks;
14962 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14963 do {
14964 ticks = getCurrentNanosecondsSinceEpoch();
14965 } while (ticks == baseTicks);
14966
14967 auto delta = ticks - baseTicks;
14968 sum += delta;
14969
14970 // If we have been calibrating for over 3 seconds -- the clock
14971 // is terrible and we should move on.
14972 // TBD: How to signal that the measured resolution is probably wrong?
14973 if (ticks > startTime + 3 * nanosecondsInSecond) {
14974 return sum / (i + 1u);
14975 }
14976 }
14977
14978 // We're just taking the mean, here. To do better we could take the std. dev
14979 // and exclude outliers
14980 // - and potentially do more iterations if there's a high variance.
14981 return sum / iterations;
14982}
14983} // namespace
14984auto getEstimatedClockResolution() -> uint64_t {
14985 static auto s_resolution = estimateClockResolution();
14986 return s_resolution;
14987}
14988
14989void Timer::start() {
14990 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14991}
14992auto Timer::getElapsedNanoseconds() const -> uint64_t {
14993 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14994}
14995auto Timer::getElapsedMicroseconds() const -> uint64_t {
14996 return getElapsedNanoseconds() / 1000;
14997}
14998auto Timer::getElapsedMilliseconds() const -> unsigned int {
14999 return static_cast<unsigned int>(getElapsedMicroseconds() / 1000);
15000}
15001auto Timer::getElapsedSeconds() const -> double {
15002 return getElapsedMicroseconds() / 1000000.0;
15003}
15004
15005} // namespace Catch
15006// end catch_timer.cpp
15007// start catch_tostring.cpp
15008
15009#if defined(__clang__)
15010#pragma clang diagnostic push
15011#pragma clang diagnostic ignored "-Wexit-time-destructors"
15012#pragma clang diagnostic ignored "-Wglobal-constructors"
15013#endif
15014
15015// Enable specific decls locally
15016#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15017#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15018#endif
15019
15020#include <cmath>
15021#include <iomanip>
15022
15023namespace Catch {
15024
15025namespace Detail {
15026
15027const std::string unprintableString = "{?}";
15028
15029namespace {
15030const int hexThreshold = 255;
15031
15032struct Endianness {
15033 enum Arch { Big, Little };
15034
15035 static Arch which() {
15036 int one = 1;
15037 // If the lowest byte we read is non-zero, we can assume
15038 // that little endian format is used.
15039 auto value = *reinterpret_cast<char*>(&one);
15040 return value ? Little : Big;
15041 }
15042};
15043} // namespace
15044
15045std::string rawMemoryToString(const void* object, std::size_t size) {
15046 // Reverse order for little endian architectures
15047 int i = 0, end = static_cast<int>(size), inc = 1;
15048 if (Endianness::which() == Endianness::Little) {
15049 i = end - 1;
15050 end = inc = -1;
15051 }
15052
15053 unsigned char const* bytes = static_cast<unsigned char const*>(object);
15054 ReusableStringStream rss;
15055 rss << "0x" << std::setfill('0') << std::hex;
15056 for (; i != end; i += inc)
15057 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15058 return rss.str();
15059}
15060} // namespace Detail
15061
15062template <typename T> std::string fpToString(T value, int precision) {
15063 if (Catch::isnan(value)) {
15064 return "nan";
15065 }
15066
15068 rss << std::setprecision(precision) << std::fixed << value;
15069 std::string d = rss.str();
15070 std::size_t i = d.find_last_not_of('0');
15071 if (i != std::string::npos && i != d.size() - 1) {
15072 if (d[i] == '.')
15073 i++;
15074 d = d.substr(0, i + 1);
15075 }
15076 return d;
15077}
15078
15080//
15081// Out-of-line defs for full specialization of StringMaker
15082//
15084
15085std::string StringMaker<std::string>::convert(const std::string& str) {
15086 if (!getCurrentContext().getConfig()->showInvisibles()) {
15087 return '"' + str + '"';
15088 }
15089
15090 std::string s("\"");
15091 for (char c : str) {
15092 switch (c) {
15093 case '\n':
15094 s.append("\\n");
15095 break;
15096 case '\t':
15097 s.append("\\t");
15098 break;
15099 default:
15100 s.push_back(c);
15101 break;
15102 }
15103 }
15104 s.append("\"");
15105 return s;
15106}
15107
15108#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15109std::string StringMaker<std::string_view>::convert(std::string_view str) {
15110 return ::Catch::Detail::stringify(std::string{str});
15111}
15112#endif
15113
15114std::string StringMaker<char const*>::convert(char const* str) {
15115 if (str) {
15116 return ::Catch::Detail::stringify(std::string{str});
15117 } else {
15118 return {"{null string}"};
15119 }
15120}
15121std::string StringMaker<char*>::convert(char* str) {
15122 if (str) {
15123 return ::Catch::Detail::stringify(std::string{str});
15124 } else {
15125 return {"{null string}"};
15126 }
15127}
15128
15129#ifdef CATCH_CONFIG_WCHAR
15130std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15131 std::string s;
15132 s.reserve(wstr.size());
15133 for (auto c : wstr) {
15134 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15135 }
15136 return ::Catch::Detail::stringify(s);
15137}
15138
15139#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15140std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15141 return StringMaker<std::wstring>::convert(std::wstring(str));
15142}
15143#endif
15144
15145std::string StringMaker<wchar_t const*>::convert(wchar_t const* str) {
15146 if (str) {
15147 return ::Catch::Detail::stringify(std::wstring{str});
15148 } else {
15149 return {"{null string}"};
15150 }
15151}
15152std::string StringMaker<wchar_t*>::convert(wchar_t* str) {
15153 if (str) {
15154 return ::Catch::Detail::stringify(std::wstring{str});
15155 } else {
15156 return {"{null string}"};
15157 }
15158}
15159#endif
15160
15161#if defined(CATCH_CONFIG_CPP17_BYTE)
15162#include <cstddef>
15163std::string StringMaker<std::byte>::convert(std::byte value) {
15164 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15165}
15166#endif // defined(CATCH_CONFIG_CPP17_BYTE)
15167
15168std::string StringMaker<int>::convert(int value) {
15169 return ::Catch::Detail::stringify(static_cast<long long>(value));
15170}
15171std::string StringMaker<long>::convert(long value) {
15172 return ::Catch::Detail::stringify(static_cast<long long>(value));
15173}
15174std::string StringMaker<long long>::convert(long long value) {
15176 rss << value;
15177 if (value > Detail::hexThreshold) {
15178 rss << " (0x" << std::hex << value << ')';
15179 }
15180 return rss.str();
15181}
15182
15183std::string StringMaker<unsigned int>::convert(unsigned int value) {
15184 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15185}
15186std::string StringMaker<unsigned long>::convert(unsigned long value) {
15187 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15188}
15189std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15191 rss << value;
15192 if (value > Detail::hexThreshold) {
15193 rss << " (0x" << std::hex << value << ')';
15194 }
15195 return rss.str();
15196}
15197
15198std::string StringMaker<bool>::convert(bool b) {
15199 return b ? "true" : "false";
15200}
15201
15202std::string StringMaker<signed char>::convert(signed char value) {
15203 if (value == '\r') {
15204 return "'\\r'";
15205 } else if (value == '\f') {
15206 return "'\\f'";
15207 } else if (value == '\n') {
15208 return "'\\n'";
15209 } else if (value == '\t') {
15210 return "'\\t'";
15211 } else if ('\0' <= value && value < ' ') {
15212 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15213 } else {
15214 char chstr[] = "' '";
15215 chstr[1] = value;
15216 return chstr;
15217 }
15218}
15219std::string StringMaker<char>::convert(char c) {
15220 return ::Catch::Detail::stringify(static_cast<signed char>(c));
15221}
15222std::string StringMaker<unsigned char>::convert(unsigned char c) {
15223 return ::Catch::Detail::stringify(static_cast<char>(c));
15224}
15225
15226std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15227 return "nullptr";
15228}
15229
15231
15232std::string StringMaker<float>::convert(float value) {
15233 return fpToString(value, precision) + 'f';
15234}
15235
15237
15238std::string StringMaker<double>::convert(double value) {
15239 return fpToString(value, precision);
15240}
15241
15242std::string ratio_string<std::atto>::symbol() {
15243 return "a";
15244}
15245std::string ratio_string<std::femto>::symbol() {
15246 return "f";
15247}
15248std::string ratio_string<std::pico>::symbol() {
15249 return "p";
15250}
15251std::string ratio_string<std::nano>::symbol() {
15252 return "n";
15253}
15254std::string ratio_string<std::micro>::symbol() {
15255 return "u";
15256}
15257std::string ratio_string<std::milli>::symbol() {
15258 return "m";
15259}
15260
15261} // end namespace Catch
15262
15263#if defined(__clang__)
15264#pragma clang diagnostic pop
15265#endif
15266
15267// end catch_tostring.cpp
15268// start catch_totals.cpp
15269
15270namespace Catch {
15271
15272Counts Counts::operator-(Counts const& other) const {
15273 Counts diff;
15274 diff.passed = passed - other.passed;
15275 diff.failed = failed - other.failed;
15276 diff.failedButOk = failedButOk - other.failedButOk;
15277 return diff;
15278}
15279
15280Counts& Counts::operator+=(Counts const& other) {
15281 passed += other.passed;
15282 failed += other.failed;
15283 failedButOk += other.failedButOk;
15284 return *this;
15285}
15286
15287std::size_t Counts::total() const {
15288 return passed + failed + failedButOk;
15289}
15290bool Counts::allPassed() const {
15291 return failed == 0 && failedButOk == 0;
15292}
15293bool Counts::allOk() const {
15294 return failed == 0;
15295}
15296
15297Totals Totals::operator-(Totals const& other) const {
15298 Totals diff;
15299 diff.assertions = assertions - other.assertions;
15300 diff.testCases = testCases - other.testCases;
15301 return diff;
15302}
15303
15304Totals& Totals::operator+=(Totals const& other) {
15305 assertions += other.assertions;
15306 testCases += other.testCases;
15307 return *this;
15308}
15309
15310Totals Totals::delta(Totals const& prevTotals) const {
15311 Totals diff = *this - prevTotals;
15312 if (diff.assertions.failed > 0)
15313 ++diff.testCases.failed;
15314 else if (diff.assertions.failedButOk > 0)
15315 ++diff.testCases.failedButOk;
15316 else
15317 ++diff.testCases.passed;
15318 return diff;
15319}
15320
15321} // namespace Catch
15322// end catch_totals.cpp
15323// start catch_uncaught_exceptions.cpp
15324
15325// start catch_config_uncaught_exceptions.hpp
15326
15327// Copyright Catch2 Authors
15328// Distributed under the Boost Software License, Version 1.0.
15329// (See accompanying file LICENSE_1_0.txt or copy at
15330// https://www.boost.org/LICENSE_1_0.txt)
15331
15332// SPDX-License-Identifier: BSL-1.0
15333
15334#ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15335#define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15336
15337#if defined(_MSC_VER)
15338#if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15339#define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15340#endif
15341#endif
15342
15343#include <exception>
15344
15345#if defined(__cpp_lib_uncaught_exceptions) && \
15346 !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15347
15348#define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15349#endif // __cpp_lib_uncaught_exceptions
15350
15351#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && \
15352 !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && \
15353 !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15354
15355#define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15356#endif
15357
15358#endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15359// end catch_config_uncaught_exceptions.hpp
15360#include <exception>
15361
15362namespace Catch {
15363bool uncaught_exceptions() {
15364#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15365 return false;
15366#elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15367 return std::uncaught_exceptions() > 0;
15368#else
15369 return std::uncaught_exception();
15370#endif
15371}
15372} // end namespace Catch
15373// end catch_uncaught_exceptions.cpp
15374// start catch_version.cpp
15375
15376#include <ostream>
15377
15378namespace Catch {
15379
15380Version::Version(unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber,
15381 char const* const _branchName, unsigned int _buildNumber)
15382 : majorVersion(_majorVersion), minorVersion(_minorVersion), patchNumber(_patchNumber),
15383 branchName(_branchName), buildNumber(_buildNumber) {}
15384
15385std::ostream& operator<<(std::ostream& os, Version const& version) {
15386 os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber;
15387 // branchName is never null -> 0th char is \0 if it is empty
15388 if (version.branchName[0]) {
15389 os << '-' << version.branchName << '.' << version.buildNumber;
15390 }
15391 return os;
15392}
15393
15394Version const& libraryVersion() {
15395 static Version version(2, 13, 9, "", 0);
15396 return version;
15397}
15398
15399} // namespace Catch
15400// end catch_version.cpp
15401// start catch_wildcard_pattern.cpp
15402
15403namespace Catch {
15404
15405WildcardPattern::WildcardPattern(std::string const& pattern, CaseSensitive::Choice caseSensitivity)
15406 : m_caseSensitivity(caseSensitivity), m_pattern(normaliseString(pattern)) {
15407 if (startsWith(m_pattern, '*')) {
15408 m_pattern = m_pattern.substr(1);
15409 m_wildcard = WildcardAtStart;
15410 }
15411 if (endsWith(m_pattern, '*')) {
15412 m_pattern = m_pattern.substr(0, m_pattern.size() - 1);
15413 m_wildcard = static_cast<WildcardPosition>(m_wildcard | WildcardAtEnd);
15414 }
15415}
15416
15417bool WildcardPattern::matches(std::string const& str) const {
15418 switch (m_wildcard) {
15419 case NoWildcard:
15420 return m_pattern == normaliseString(str);
15421 case WildcardAtStart:
15422 return endsWith(normaliseString(str), m_pattern);
15423 case WildcardAtEnd:
15424 return startsWith(normaliseString(str), m_pattern);
15425 case WildcardAtBothEnds:
15426 return contains(normaliseString(str), m_pattern);
15427 default:
15428 CATCH_INTERNAL_ERROR("Unknown enum");
15429 }
15430}
15431
15432std::string WildcardPattern::normaliseString(std::string const& str) const {
15433 return trim(m_caseSensitivity == CaseSensitive::No ? toLower(str) : str);
15434}
15435} // namespace Catch
15436// end catch_wildcard_pattern.cpp
15437// start catch_xmlwriter.cpp
15438
15439#include <iomanip>
15440#include <type_traits>
15441
15442namespace Catch {
15443
15444namespace {
15445
15446size_t trailingBytes(unsigned char c) {
15447 if ((c & 0xE0) == 0xC0) {
15448 return 2;
15449 }
15450 if ((c & 0xF0) == 0xE0) {
15451 return 3;
15452 }
15453 if ((c & 0xF8) == 0xF0) {
15454 return 4;
15455 }
15456 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15457}
15458
15459uint32_t headerValue(unsigned char c) {
15460 if ((c & 0xE0) == 0xC0) {
15461 return c & 0x1F;
15462 }
15463 if ((c & 0xF0) == 0xE0) {
15464 return c & 0x0F;
15465 }
15466 if ((c & 0xF8) == 0xF0) {
15467 return c & 0x07;
15468 }
15469 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15470}
15471
15472void hexEscapeChar(std::ostream& os, unsigned char c) {
15473 std::ios_base::fmtflags f(os.flags());
15474 os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15475 << static_cast<int>(c);
15476 os.flags(f);
15477}
15478
15479bool shouldNewline(XmlFormatting fmt) {
15480 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
15481}
15482
15483bool shouldIndent(XmlFormatting fmt) {
15484 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
15485}
15486
15487} // anonymous namespace
15488
15489XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs) {
15490 return static_cast<XmlFormatting>(static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15491 static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
15492}
15493
15494XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs) {
15495 return static_cast<XmlFormatting>(static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15496 static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
15497}
15498
15499XmlEncode::XmlEncode(std::string const& str, ForWhat forWhat) : m_str(str), m_forWhat(forWhat) {}
15500
15501void XmlEncode::encodeTo(std::ostream& os) const {
15502 // Apostrophe escaping not necessary if we always use " to write attributes
15503 // (see: http://www.w3.org/TR/xml/#syntax)
15504
15505 for (std::size_t idx = 0; idx < m_str.size(); ++idx) {
15506 unsigned char c = m_str[idx];
15507 switch (c) {
15508 case '<':
15509 os << "&lt;";
15510 break;
15511 case '&':
15512 os << "&amp;";
15513 break;
15514
15515 case '>':
15516 // See: http://www.w3.org/TR/xml/#syntax
15517 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15518 os << "&gt;";
15519 else
15520 os << c;
15521 break;
15522
15523 case '\"':
15524 if (m_forWhat == ForAttributes)
15525 os << "&quot;";
15526 else
15527 os << c;
15528 break;
15529
15530 default:
15531 // Check for control characters and invalid utf-8
15532
15533 // Escape control characters in standard ascii
15534 // see
15535 // http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15536 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15537 hexEscapeChar(os, c);
15538 break;
15539 }
15540
15541 // Plain ASCII: Write it to stream
15542 if (c < 0x7F) {
15543 os << c;
15544 break;
15545 }
15546
15547 // UTF-8 territory
15548 // Check if the encoding is valid and if it is not, hex escape bytes.
15549 // Important: We do not check the exact decoded values for validity, only
15550 // the encoding format First check that this bytes is a valid lead byte:
15551 // This means that it is not encoded as 1111 1XXX
15552 // Or as 10XX XXXX
15553 if (c < 0xC0 || c >= 0xF8) {
15554 hexEscapeChar(os, c);
15555 break;
15556 }
15557
15558 auto encBytes = trailingBytes(c);
15559 // Are there enough bytes left to avoid accessing out-of-bounds memory?
15560 if (idx + encBytes - 1 >= m_str.size()) {
15561 hexEscapeChar(os, c);
15562 break;
15563 }
15564 // The header is valid, check data
15565 // The next encBytes bytes must together be a valid utf-8
15566 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
15567 bool valid = true;
15568 uint32_t value = headerValue(c);
15569 for (std::size_t n = 1; n < encBytes; ++n) {
15570 unsigned char nc = m_str[idx + n];
15571 valid &= ((nc & 0xC0) == 0x80);
15572 value = (value << 6) | (nc & 0x3F);
15573 }
15574
15575 if (
15576 // Wrong bit pattern of following bytes
15577 (!valid) ||
15578 // Overlong encodings
15579 (value < 0x80) || (0x80 <= value && value < 0x800 && encBytes > 2) ||
15580 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15581 // Encoded value out of range
15582 (value >= 0x110000)) {
15583 hexEscapeChar(os, c);
15584 break;
15585 }
15586
15587 // If we got here, this is in fact a valid(ish) utf-8 sequence
15588 for (std::size_t n = 0; n < encBytes; ++n) {
15589 os << m_str[idx + n];
15590 }
15591 idx += encBytes - 1;
15592 break;
15593 }
15594 }
15595}
15596
15597std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode) {
15598 xmlEncode.encodeTo(os);
15599 return os;
15600}
15601
15602XmlWriter::ScopedElement::ScopedElement(XmlWriter* writer, XmlFormatting fmt)
15603 : m_writer(writer), m_fmt(fmt) {}
15604
15605XmlWriter::ScopedElement::ScopedElement(ScopedElement&& other) noexcept
15606 : m_writer(other.m_writer), m_fmt(other.m_fmt) {
15607 other.m_writer = nullptr;
15608 other.m_fmt = XmlFormatting::None;
15609}
15610XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=(ScopedElement&& other) noexcept {
15611 if (m_writer) {
15612 m_writer->endElement();
15613 }
15614 m_writer = other.m_writer;
15615 other.m_writer = nullptr;
15616 m_fmt = other.m_fmt;
15617 other.m_fmt = XmlFormatting::None;
15618 return *this;
15619}
15620
15621XmlWriter::ScopedElement::~ScopedElement() {
15622 if (m_writer) {
15623 m_writer->endElement(m_fmt);
15624 }
15625}
15626
15627XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText(std::string const& text,
15628 XmlFormatting fmt) {
15629 m_writer->writeText(text, fmt);
15630 return *this;
15631}
15632
15633XmlWriter::XmlWriter(std::ostream& os) : m_os(os) {
15634 writeDeclaration();
15635}
15636
15637XmlWriter::~XmlWriter() {
15638 while (!m_tags.empty()) {
15639 endElement();
15640 }
15641 newlineIfNecessary();
15642}
15643
15644XmlWriter& XmlWriter::startElement(std::string const& name, XmlFormatting fmt) {
15645 ensureTagClosed();
15646 newlineIfNecessary();
15647 if (shouldIndent(fmt)) {
15648 m_os << m_indent;
15649 m_indent += " ";
15650 }
15651 m_os << '<' << name;
15652 m_tags.push_back(name);
15653 m_tagIsOpen = true;
15654 applyFormatting(fmt);
15655 return *this;
15656}
15657
15658XmlWriter::ScopedElement XmlWriter::scopedElement(std::string const& name, XmlFormatting fmt) {
15659 ScopedElement scoped(this, fmt);
15660 startElement(name, fmt);
15661 return scoped;
15662}
15663
15664XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15665 m_indent = m_indent.substr(0, m_indent.size() - 2);
15666
15667 if (m_tagIsOpen) {
15668 m_os << "/>";
15669 m_tagIsOpen = false;
15670 } else {
15671 newlineIfNecessary();
15672 if (shouldIndent(fmt)) {
15673 m_os << m_indent;
15674 }
15675 m_os << "</" << m_tags.back() << ">";
15676 }
15677 m_os << std::flush;
15678 applyFormatting(fmt);
15679 m_tags.pop_back();
15680 return *this;
15681}
15682
15683XmlWriter& XmlWriter::writeAttribute(std::string const& name, std::string const& attribute) {
15684 if (!name.empty() && !attribute.empty())
15685 m_os << ' ' << name << "=\"" << XmlEncode(attribute, XmlEncode::ForAttributes) << '"';
15686 return *this;
15687}
15688
15689XmlWriter& XmlWriter::writeAttribute(std::string const& name, bool attribute) {
15690 m_os << ' ' << name << "=\"" << (attribute ? "true" : "false") << '"';
15691 return *this;
15692}
15693
15694XmlWriter& XmlWriter::writeText(std::string const& text, XmlFormatting fmt) {
15695 if (!text.empty()) {
15696 bool tagWasOpen = m_tagIsOpen;
15697 ensureTagClosed();
15698 if (tagWasOpen && shouldIndent(fmt)) {
15699 m_os << m_indent;
15700 }
15701 m_os << XmlEncode(text);
15702 applyFormatting(fmt);
15703 }
15704 return *this;
15705}
15706
15707XmlWriter& XmlWriter::writeComment(std::string const& text, XmlFormatting fmt) {
15708 ensureTagClosed();
15709 if (shouldIndent(fmt)) {
15710 m_os << m_indent;
15711 }
15712 m_os << "<!--" << text << "-->";
15713 applyFormatting(fmt);
15714 return *this;
15715}
15716
15717void XmlWriter::writeStylesheetRef(std::string const& url) {
15718 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
15719}
15720
15721XmlWriter& XmlWriter::writeBlankLine() {
15722 ensureTagClosed();
15723 m_os << '\n';
15724 return *this;
15725}
15726
15727void XmlWriter::ensureTagClosed() {
15728 if (m_tagIsOpen) {
15729 m_os << '>' << std::flush;
15730 newlineIfNecessary();
15731 m_tagIsOpen = false;
15732 }
15733}
15734
15735void XmlWriter::applyFormatting(XmlFormatting fmt) {
15736 m_needsNewline = shouldNewline(fmt);
15737}
15738
15739void XmlWriter::writeDeclaration() {
15740 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15741}
15742
15743void XmlWriter::newlineIfNecessary() {
15744 if (m_needsNewline) {
15745 m_os << std::endl;
15746 m_needsNewline = false;
15747 }
15748}
15749} // namespace Catch
15750// end catch_xmlwriter.cpp
15751// start catch_reporter_bases.cpp
15752
15753#include <cassert>
15754#include <cfloat>
15755#include <cstdio>
15756#include <cstring>
15757#include <memory>
15758
15759namespace Catch {
15760void prepareExpandedExpression(AssertionResult& result) {
15761 result.getExpandedExpression();
15762}
15763
15764// Because formatting using c++ streams is stateful, drop down to C is required
15765// Alternatively we could use stringstream, but its performance is... not good.
15766std::string getFormattedDuration(double duration) {
15767 // Max exponent + 1 is required to represent the whole part
15768 // + 1 for decimal point
15769 // + 3 for the 3 decimal places
15770 // + 1 for null terminator
15771 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15772 char buffer[maxDoubleSize];
15773
15774 // Save previous errno, to prevent sprintf from overwriting it
15775 ErrnoGuard guard;
15776#ifdef _MSC_VER
15777 sprintf_s(buffer, "%.3f", duration);
15778#else
15779 std::sprintf(buffer, "%.3f", duration);
15780#endif
15781 return std::string(buffer);
15782}
15783
15784bool shouldShowDuration(IConfig const& config, double duration) {
15785 if (config.showDurations() == ShowDurations::Always) {
15786 return true;
15787 }
15788 if (config.showDurations() == ShowDurations::Never) {
15789 return false;
15790 }
15791 const double min = config.minDuration();
15792 return min >= 0 && duration >= min;
15793}
15794
15795std::string serializeFilters(std::vector<std::string> const& container) {
15797 bool first = true;
15798 for (auto&& filter : container) {
15799 if (!first)
15800 oss << ' ';
15801 else
15802 first = false;
15803
15804 oss << filter;
15805 }
15806 return oss.str();
15807}
15808
15809TestEventListenerBase::TestEventListenerBase(ReporterConfig const& _config)
15810 : StreamingReporterBase(_config) {}
15811
15812std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15813 return {Verbosity::Quiet, Verbosity::Normal, Verbosity::High};
15814}
15815
15816void TestEventListenerBase::assertionStarting(AssertionInfo const&) {}
15817
15818bool TestEventListenerBase::assertionEnded(AssertionStats const&) {
15819 return false;
15820}
15821
15822} // end namespace Catch
15823// end catch_reporter_bases.cpp
15824// start catch_reporter_compact.cpp
15825
15826namespace {
15827
15828#ifdef CATCH_PLATFORM_MAC
15829const char* failedString() {
15830 return "FAILED";
15831}
15832const char* passedString() {
15833 return "PASSED";
15834}
15835#else
15836const char* failedString() {
15837 return "failed";
15838}
15839const char* passedString() {
15840 return "passed";
15841}
15842#endif
15843
15844// Colour::LightGrey
15845Catch::Colour::Code dimColour() {
15846 return Catch::Colour::FileName;
15847}
15848
15849std::string bothOrAll(std::size_t count) {
15850 return count == 1 ? std::string() : count == 2 ? "both " : "all ";
15851}
15852
15853} // namespace
15854
15855namespace Catch {
15856namespace {
15857// Colour, message variants:
15858// - white: No tests ran.
15859// - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15860// - white: Passed [both/all] N test cases (no assertions).
15861// - red: Failed N tests cases, failed M assertions.
15862// - green: Passed [both/all] N tests cases with M assertions.
15863void printTotals(std::ostream& out, const Totals& totals) {
15864 if (totals.testCases.total() == 0) {
15865 out << "No tests ran.";
15866 } else if (totals.testCases.failed == totals.testCases.total()) {
15867 Colour colour(Colour::ResultError);
15868 const std::string qualify_assertions_failed =
15869 totals.assertions.failed == totals.assertions.total()
15870 ? bothOrAll(totals.assertions.failed)
15871 : std::string();
15872 out << "Failed " << bothOrAll(totals.testCases.failed)
15873 << pluralise(totals.testCases.failed, "test case")
15874 << ", "
15875 "failed "
15876 << qualify_assertions_failed << pluralise(totals.assertions.failed, "assertion") << '.';
15877 } else if (totals.assertions.total() == 0) {
15878 out << "Passed " << bothOrAll(totals.testCases.total())
15879 << pluralise(totals.testCases.total(), "test case") << " (no assertions).";
15880 } else if (totals.assertions.failed) {
15881 Colour colour(Colour::ResultError);
15882 out << "Failed " << pluralise(totals.testCases.failed, "test case")
15883 << ", "
15884 "failed "
15885 << pluralise(totals.assertions.failed, "assertion") << '.';
15886 } else {
15887 Colour colour(Colour::ResultSuccess);
15888 out << "Passed " << bothOrAll(totals.testCases.passed)
15889 << pluralise(totals.testCases.passed, "test case") << " with "
15890 << pluralise(totals.assertions.passed, "assertion") << '.';
15891 }
15892}
15893
15894// Implementation of CompactReporter formatting
15895class AssertionPrinter {
15896 public:
15897 AssertionPrinter& operator=(AssertionPrinter const&) = delete;
15898 AssertionPrinter(AssertionPrinter const&) = delete;
15899 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15900 : stream(_stream), result(_stats.assertionResult), messages(_stats.infoMessages),
15901 itMessage(_stats.infoMessages.begin()), printInfoMessages(_printInfoMessages) {}
15902
15903 void print() {
15904 printSourceInfo();
15905
15906 itMessage = messages.begin();
15907
15908 switch (result.getResultType()) {
15909 case ResultWas::Ok:
15910 printResultType(Colour::ResultSuccess, passedString());
15911 printOriginalExpression();
15912 printReconstructedExpression();
15913 if (!result.hasExpression())
15914 printRemainingMessages(Colour::None);
15915 else
15916 printRemainingMessages();
15917 break;
15918 case ResultWas::ExpressionFailed:
15919 if (result.isOk())
15920 printResultType(Colour::ResultSuccess,
15921 failedString() + std::string(" - but was ok"));
15922 else
15923 printResultType(Colour::Error, failedString());
15924 printOriginalExpression();
15925 printReconstructedExpression();
15926 printRemainingMessages();
15927 break;
15928 case ResultWas::ThrewException:
15929 printResultType(Colour::Error, failedString());
15930 printIssue("unexpected exception with message:");
15931 printMessage();
15932 printExpressionWas();
15933 printRemainingMessages();
15934 break;
15935 case ResultWas::FatalErrorCondition:
15936 printResultType(Colour::Error, failedString());
15937 printIssue("fatal error condition with message:");
15938 printMessage();
15939 printExpressionWas();
15940 printRemainingMessages();
15941 break;
15942 case ResultWas::DidntThrowException:
15943 printResultType(Colour::Error, failedString());
15944 printIssue("expected exception, got none");
15945 printExpressionWas();
15946 printRemainingMessages();
15947 break;
15948 case ResultWas::Info:
15949 printResultType(Colour::None, "info");
15950 printMessage();
15951 printRemainingMessages();
15952 break;
15953 case ResultWas::Warning:
15954 printResultType(Colour::None, "warning");
15955 printMessage();
15956 printRemainingMessages();
15957 break;
15958 case ResultWas::ExplicitFailure:
15959 printResultType(Colour::Error, failedString());
15960 printIssue("explicitly");
15961 printRemainingMessages(Colour::None);
15962 break;
15963 // These cases are here to prevent compiler warnings
15964 case ResultWas::Unknown:
15965 case ResultWas::FailureBit:
15966 case ResultWas::Exception:
15967 printResultType(Colour::Error, "** internal error **");
15968 break;
15969 }
15970 }
15971
15972 private:
15973 void printSourceInfo() const {
15974 Colour colourGuard(Colour::FileName);
15975 stream << result.getSourceInfo() << ':';
15976 }
15977
15978 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15979 if (!passOrFail.empty()) {
15980 {
15981 Colour colourGuard(colour);
15982 stream << ' ' << passOrFail;
15983 }
15984 stream << ':';
15985 }
15986 }
15987
15988 void printIssue(std::string const& issue) const { stream << ' ' << issue; }
15989
15990 void printExpressionWas() {
15991 if (result.hasExpression()) {
15992 stream << ';';
15993 {
15994 Colour colour(dimColour());
15995 stream << " expression was:";
15996 }
15997 printOriginalExpression();
15998 }
15999 }
16000
16001 void printOriginalExpression() const {
16002 if (result.hasExpression()) {
16003 stream << ' ' << result.getExpression();
16004 }
16005 }
16006
16007 void printReconstructedExpression() const {
16008 if (result.hasExpandedExpression()) {
16009 {
16010 Colour colour(dimColour());
16011 stream << " for: ";
16012 }
16013 stream << result.getExpandedExpression();
16014 }
16015 }
16016
16017 void printMessage() {
16018 if (itMessage != messages.end()) {
16019 stream << " '" << itMessage->message << '\'';
16020 ++itMessage;
16021 }
16022 }
16023
16024 void printRemainingMessages(Colour::Code colour = dimColour()) {
16025 if (itMessage == messages.end())
16026 return;
16027
16028 const auto itEnd = messages.cend();
16029 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16030
16031 {
16032 Colour colourGuard(colour);
16033 stream << " with " << pluralise(N, "message") << ':';
16034 }
16035
16036 while (itMessage != itEnd) {
16037 // If this assertion is a warning ignore any INFO messages
16038 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16039 printMessage();
16040 if (itMessage != itEnd) {
16041 Colour colourGuard(dimColour());
16042 stream << " and";
16043 }
16044 continue;
16045 }
16046 ++itMessage;
16047 }
16048 }
16049
16050 private:
16051 std::ostream& stream;
16052 AssertionResult const& result;
16053 std::vector<MessageInfo> messages;
16054 std::vector<MessageInfo>::const_iterator itMessage;
16055 bool printInfoMessages;
16056};
16057
16058} // namespace
16059
16060std::string CompactReporter::getDescription() {
16061 return "Reports test results on a single line, suitable for IDEs";
16062}
16063
16064void CompactReporter::noMatchingTestCases(std::string const& spec) {
16065 stream << "No test cases matched '" << spec << '\'' << std::endl;
16066}
16067
16068void CompactReporter::assertionStarting(AssertionInfo const&) {}
16069
16070bool CompactReporter::assertionEnded(AssertionStats const& _assertionStats) {
16071 AssertionResult const& result = _assertionStats.assertionResult;
16072
16073 bool printInfoMessages = true;
16074
16075 // Drop out if result was successful and we're not printing those
16076 if (!m_config->includeSuccessfulResults() && result.isOk()) {
16077 if (result.getResultType() != ResultWas::Warning)
16078 return false;
16079 printInfoMessages = false;
16080 }
16081
16082 AssertionPrinter printer(stream, _assertionStats, printInfoMessages);
16083 printer.print();
16084
16085 stream << std::endl;
16086 return true;
16087}
16088
16089void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16090 double dur = _sectionStats.durationInSeconds;
16091 if (shouldShowDuration(*m_config, dur)) {
16092 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name
16093 << std::endl;
16094 }
16095}
16096
16097void CompactReporter::testRunEnded(TestRunStats const& _testRunStats) {
16098 printTotals(stream, _testRunStats.totals);
16099 stream << '\n' << std::endl;
16100 StreamingReporterBase::testRunEnded(_testRunStats);
16101}
16102
16103CompactReporter::~CompactReporter() {}
16104
16105CATCH_REGISTER_REPORTER("compact", CompactReporter)
16106
16107} // end namespace Catch
16108// end catch_reporter_compact.cpp
16109// start catch_reporter_console.cpp
16110
16111#include <cfloat>
16112#include <cstdio>
16113
16114#if defined(_MSC_VER)
16115#pragma warning(push)
16116#pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in switch
16117 // Note that 4062 (not all labels are handled and default is missing) is
16118 // enabled
16119#endif
16120
16121#if defined(__clang__)
16122#pragma clang diagnostic push
16123// For simplicity, benchmarking-only helpers are always enabled
16124#pragma clang diagnostic ignored "-Wunused-function"
16125#endif
16126
16127namespace Catch {
16128
16129namespace {
16130
16131// Formatter impl for ConsoleReporter
16132class ConsoleAssertionPrinter {
16133 public:
16134 ConsoleAssertionPrinter& operator=(ConsoleAssertionPrinter const&) = delete;
16135 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
16136 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats,
16137 bool _printInfoMessages)
16138 : stream(_stream), stats(_stats), result(_stats.assertionResult), colour(Colour::None),
16139 message(result.getMessage()), messages(_stats.infoMessages),
16140 printInfoMessages(_printInfoMessages) {
16141 switch (result.getResultType()) {
16142 case ResultWas::Ok:
16143 colour = Colour::Success;
16144 passOrFail = "PASSED";
16145 // if( result.hasMessage() )
16146 if (_stats.infoMessages.size() == 1)
16147 messageLabel = "with message";
16148 if (_stats.infoMessages.size() > 1)
16149 messageLabel = "with messages";
16150 break;
16151 case ResultWas::ExpressionFailed:
16152 if (result.isOk()) {
16153 colour = Colour::Success;
16154 passOrFail = "FAILED - but was ok";
16155 } else {
16156 colour = Colour::Error;
16157 passOrFail = "FAILED";
16158 }
16159 if (_stats.infoMessages.size() == 1)
16160 messageLabel = "with message";
16161 if (_stats.infoMessages.size() > 1)
16162 messageLabel = "with messages";
16163 break;
16164 case ResultWas::ThrewException:
16165 colour = Colour::Error;
16166 passOrFail = "FAILED";
16167 messageLabel = "due to unexpected exception with ";
16168 if (_stats.infoMessages.size() == 1)
16169 messageLabel += "message";
16170 if (_stats.infoMessages.size() > 1)
16171 messageLabel += "messages";
16172 break;
16173 case ResultWas::FatalErrorCondition:
16174 colour = Colour::Error;
16175 passOrFail = "FAILED";
16176 messageLabel = "due to a fatal error condition";
16177 break;
16178 case ResultWas::DidntThrowException:
16179 colour = Colour::Error;
16180 passOrFail = "FAILED";
16181 messageLabel = "because no exception was thrown where one was expected";
16182 break;
16183 case ResultWas::Info:
16184 messageLabel = "info";
16185 break;
16186 case ResultWas::Warning:
16187 messageLabel = "warning";
16188 break;
16189 case ResultWas::ExplicitFailure:
16190 passOrFail = "FAILED";
16191 colour = Colour::Error;
16192 if (_stats.infoMessages.size() == 1)
16193 messageLabel = "explicitly with message";
16194 if (_stats.infoMessages.size() > 1)
16195 messageLabel = "explicitly with messages";
16196 break;
16197 // These cases are here to prevent compiler warnings
16198 case ResultWas::Unknown:
16199 case ResultWas::FailureBit:
16200 case ResultWas::Exception:
16201 passOrFail = "** internal error **";
16202 colour = Colour::Error;
16203 break;
16204 }
16205 }
16206
16207 void print() const {
16208 printSourceInfo();
16209 if (stats.totals.assertions.total() > 0) {
16210 printResultType();
16211 printOriginalExpression();
16212 printReconstructedExpression();
16213 } else {
16214 stream << '\n';
16215 }
16216 printMessage();
16217 }
16218
16219 private:
16220 void printResultType() const {
16221 if (!passOrFail.empty()) {
16222 Colour colourGuard(colour);
16223 stream << passOrFail << ":\n";
16224 }
16225 }
16226 void printOriginalExpression() const {
16227 if (result.hasExpression()) {
16228 Colour colourGuard(Colour::OriginalExpression);
16229 stream << " ";
16230 stream << result.getExpressionInMacro();
16231 stream << '\n';
16232 }
16233 }
16234 void printReconstructedExpression() const {
16235 if (result.hasExpandedExpression()) {
16236 stream << "with expansion:\n";
16237 Colour colourGuard(Colour::ReconstructedExpression);
16238 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16239 }
16240 }
16241 void printMessage() const {
16242 if (!messageLabel.empty())
16243 stream << messageLabel << ':' << '\n';
16244 for (auto const& msg : messages) {
16245 // If this assertion is a warning ignore any INFO messages
16246 if (printInfoMessages || msg.type != ResultWas::Info)
16247 stream << Column(msg.message).indent(2) << '\n';
16248 }
16249 }
16250 void printSourceInfo() const {
16251 Colour colourGuard(Colour::FileName);
16252 stream << result.getSourceInfo() << ": ";
16253 }
16254
16255 std::ostream& stream;
16256 AssertionStats const& stats;
16257 AssertionResult const& result;
16258 Colour::Code colour;
16259 std::string passOrFail;
16260 std::string messageLabel;
16261 std::string message;
16262 std::vector<MessageInfo> messages;
16263 bool printInfoMessages;
16264};
16265
16266std::size_t makeRatio(std::size_t number, std::size_t total) {
16267 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16268 return (ratio == 0 && number > 0) ? 1 : ratio;
16269}
16270
16271std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16272 if (i > j && i > k)
16273 return i;
16274 else if (j > k)
16275 return j;
16276 else
16277 return k;
16278}
16279
16280struct ColumnInfo {
16281 enum Justification { Left, Right };
16282 std::string name;
16283 int width;
16284 Justification justification;
16285};
16286struct ColumnBreak {};
16287struct RowBreak {};
16288
16289class Duration {
16290 enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes };
16291 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16292 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16293 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16294 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16295
16296 double m_inNanoseconds;
16297 Unit m_units;
16298
16299 public:
16300 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
16301 : m_inNanoseconds(inNanoseconds), m_units(units) {
16302 if (m_units == Unit::Auto) {
16303 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16304 m_units = Unit::Nanoseconds;
16305 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16306 m_units = Unit::Microseconds;
16307 else if (m_inNanoseconds < s_nanosecondsInASecond)
16308 m_units = Unit::Milliseconds;
16309 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16310 m_units = Unit::Seconds;
16311 else
16312 m_units = Unit::Minutes;
16313 }
16314 }
16315
16316 auto value() const -> double {
16317 switch (m_units) {
16318 case Unit::Microseconds:
16319 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16320 case Unit::Milliseconds:
16321 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16322 case Unit::Seconds:
16323 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16324 case Unit::Minutes:
16325 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16326 default:
16327 return m_inNanoseconds;
16328 }
16329 }
16330 auto unitsAsString() const -> std::string {
16331 switch (m_units) {
16332 case Unit::Nanoseconds:
16333 return "ns";
16334 case Unit::Microseconds:
16335 return "us";
16336 case Unit::Milliseconds:
16337 return "ms";
16338 case Unit::Seconds:
16339 return "s";
16340 case Unit::Minutes:
16341 return "m";
16342 default:
16343 return "** internal error **";
16344 }
16345 }
16346 friend auto operator<<(std::ostream& os, Duration const& duration) -> std::ostream& {
16347 return os << duration.value() << ' ' << duration.unitsAsString();
16348 }
16349};
16350} // namespace
16351
16352class TablePrinter {
16353 std::ostream& m_os;
16354 std::vector<ColumnInfo> m_columnInfos;
16355 std::ostringstream m_oss;
16356 int m_currentColumn = -1;
16357 bool m_isOpen = false;
16358
16359 public:
16360 TablePrinter(std::ostream& os, std::vector<ColumnInfo> columnInfos)
16361 : m_os(os), m_columnInfos(std::move(columnInfos)) {}
16362
16363 auto columnInfos() const -> std::vector<ColumnInfo> const& { return m_columnInfos; }
16364
16365 void open() {
16366 if (!m_isOpen) {
16367 m_isOpen = true;
16368 *this << RowBreak();
16369
16370 Columns headerCols;
16371 Spacer spacer(2);
16372 for (auto const& info : m_columnInfos) {
16373 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16374 headerCols += spacer;
16375 }
16376 m_os << headerCols << '\n';
16377
16378 m_os << Catch::getLineOfChars<'-'>() << '\n';
16379 }
16380 }
16381 void close() {
16382 if (m_isOpen) {
16383 *this << RowBreak();
16384 m_os << std::endl;
16385 m_isOpen = false;
16386 }
16387 }
16388
16389 template <typename T> friend TablePrinter& operator<<(TablePrinter& tp, T const& value) {
16390 tp.m_oss << value;
16391 return tp;
16392 }
16393
16394 friend TablePrinter& operator<<(TablePrinter& tp, ColumnBreak) {
16395 auto colStr = tp.m_oss.str();
16396 const auto strSize = colStr.size();
16397 tp.m_oss.str("");
16398 tp.open();
16399 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16400 tp.m_currentColumn = -1;
16401 tp.m_os << '\n';
16402 }
16403 tp.m_currentColumn++;
16404
16405 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16406 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16407 ? std::string(colInfo.width - (strSize + 1), ' ')
16408 : std::string();
16409 if (colInfo.justification == ColumnInfo::Left)
16410 tp.m_os << colStr << padding << ' ';
16411 else
16412 tp.m_os << padding << colStr << ' ';
16413 return tp;
16414 }
16415
16416 friend TablePrinter& operator<<(TablePrinter& tp, RowBreak) {
16417 if (tp.m_currentColumn > 0) {
16418 tp.m_os << '\n';
16419 tp.m_currentColumn = -1;
16420 }
16421 return tp;
16422 }
16423};
16424
16425ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
16426 : StreamingReporterBase(config),
16427 m_tablePrinter(new TablePrinter(config.stream(), [&config]() -> std::vector<ColumnInfo> {
16428 if (config.fullConfig()->benchmarkNoAnalysis()) {
16429 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16430 {" samples", 14, ColumnInfo::Right},
16431 {" iterations", 14, ColumnInfo::Right},
16432 {" mean", 14, ColumnInfo::Right}};
16433 } else {
16434 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16435 {"samples mean std dev", 14, ColumnInfo::Right},
16436 {"iterations low mean low std dev", 14, ColumnInfo::Right},
16437 {"estimated high mean high std dev", 14, ColumnInfo::Right}};
16438 }
16439 }())) {}
16440ConsoleReporter::~ConsoleReporter() = default;
16441
16442std::string ConsoleReporter::getDescription() {
16443 return "Reports test results as plain lines of text";
16444}
16445
16446void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16447 stream << "No test cases matched '" << spec << '\'' << std::endl;
16448}
16449
16450void ConsoleReporter::reportInvalidArguments(std::string const& arg) {
16451 stream << "Invalid Filter: " << arg << std::endl;
16452}
16453
16454void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16455
16456bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16457 AssertionResult const& result = _assertionStats.assertionResult;
16458
16459 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16460
16461 // Drop out if result was successful but we're not printing them.
16462 if (!includeResults && result.getResultType() != ResultWas::Warning)
16463 return false;
16464
16465 lazyPrint();
16466
16467 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16468 printer.print();
16469 stream << std::endl;
16470 return true;
16471}
16472
16473void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16474 m_tablePrinter->close();
16475 m_headerPrinted = false;
16476 StreamingReporterBase::sectionStarting(_sectionInfo);
16477}
16478void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16479 m_tablePrinter->close();
16480 if (_sectionStats.missingAssertions) {
16481 lazyPrint();
16482 Colour colour(Colour::ResultError);
16483 if (m_sectionStack.size() > 1)
16484 stream << "\nNo assertions in section";
16485 else
16486 stream << "\nNo assertions in test case";
16487 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16488 }
16489 double dur = _sectionStats.durationInSeconds;
16490 if (shouldShowDuration(*m_config, dur)) {
16491 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name
16492 << std::endl;
16493 }
16494 if (m_headerPrinted) {
16495 m_headerPrinted = false;
16496 }
16497 StreamingReporterBase::sectionEnded(_sectionStats);
16498}
16499
16500#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16501void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16502 lazyPrintWithoutClosingBenchmarkTable();
16503
16504 auto nameCol =
16505 Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16506
16507 bool firstLine = true;
16508 for (auto line : nameCol) {
16509 if (!firstLine)
16510 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16511 else
16512 firstLine = false;
16513
16514 (*m_tablePrinter) << line << ColumnBreak();
16515 }
16516}
16517
16518void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16519 (*m_tablePrinter) << info.samples << ColumnBreak() << info.iterations << ColumnBreak();
16520 if (!m_config->benchmarkNoAnalysis())
16521 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16522}
16523void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16524 if (m_config->benchmarkNoAnalysis()) {
16525 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16526 } else {
16527 (*m_tablePrinter) << ColumnBreak() << Duration(stats.mean.point.count()) << ColumnBreak()
16528 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16529 << Duration(stats.mean.upper_bound.count()) << ColumnBreak()
16530 << ColumnBreak() << Duration(stats.standardDeviation.point.count())
16531 << ColumnBreak() << Duration(stats.standardDeviation.lower_bound.count())
16532 << ColumnBreak() << Duration(stats.standardDeviation.upper_bound.count())
16533 << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak()
16534 << ColumnBreak();
16535 }
16536}
16537
16538void ConsoleReporter::benchmarkFailed(std::string const& error) {
16539 Colour colour(Colour::Red);
16540 (*m_tablePrinter) << "Benchmark failed (" << error << ')' << ColumnBreak() << RowBreak();
16541}
16542#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16543
16544void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16545 m_tablePrinter->close();
16546 StreamingReporterBase::testCaseEnded(_testCaseStats);
16547 m_headerPrinted = false;
16548}
16549void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16550 if (currentGroupInfo.used) {
16551 printSummaryDivider();
16552 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16553 printTotals(_testGroupStats.totals);
16554 stream << '\n' << std::endl;
16555 }
16556 StreamingReporterBase::testGroupEnded(_testGroupStats);
16557}
16558void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16559 printTotalsDivider(_testRunStats.totals);
16560 printTotals(_testRunStats.totals);
16561 stream << std::endl;
16562 StreamingReporterBase::testRunEnded(_testRunStats);
16563}
16564void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16565 StreamingReporterBase::testRunStarting(_testInfo);
16566 printTestFilters();
16567}
16568
16569void ConsoleReporter::lazyPrint() {
16570
16571 m_tablePrinter->close();
16572 lazyPrintWithoutClosingBenchmarkTable();
16573}
16574
16575void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16576
16577 if (!currentTestRunInfo.used)
16578 lazyPrintRunInfo();
16579 if (!currentGroupInfo.used)
16580 lazyPrintGroupInfo();
16581
16582 if (!m_headerPrinted) {
16583 printTestCaseAndSectionHeader();
16584 m_headerPrinted = true;
16585 }
16586}
16587void ConsoleReporter::lazyPrintRunInfo() {
16588 stream << '\n' << getLineOfChars<'~'>() << '\n';
16589 Colour colour(Colour::SecondaryText);
16590 stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion()
16591 << " host application.\n"
16592 << "Run with -? for options\n\n";
16593
16594 if (m_config->rngSeed() != 0)
16595 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16596
16597 currentTestRunInfo.used = true;
16598}
16599void ConsoleReporter::lazyPrintGroupInfo() {
16600 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16601 printClosedHeader("Group: " + currentGroupInfo->name);
16602 currentGroupInfo.used = true;
16603 }
16604}
16605void ConsoleReporter::printTestCaseAndSectionHeader() {
16606 assert(!m_sectionStack.empty());
16607 printOpenHeader(currentTestCaseInfo->name);
16608
16609 if (m_sectionStack.size() > 1) {
16610 Colour colourGuard(Colour::Headers);
16611
16612 auto it = m_sectionStack.begin() + 1, // Skip first section (test case)
16613 itEnd = m_sectionStack.end();
16614 for (; it != itEnd; ++it)
16615 printHeaderString(it->name, 2);
16616 }
16617
16618 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16619
16620 stream << getLineOfChars<'-'>() << '\n';
16621 Colour colourGuard(Colour::FileName);
16622 stream << lineInfo << '\n';
16623 stream << getLineOfChars<'.'>() << '\n' << std::endl;
16624}
16625
16626void ConsoleReporter::printClosedHeader(std::string const& _name) {
16627 printOpenHeader(_name);
16628 stream << getLineOfChars<'.'>() << '\n';
16629}
16630void ConsoleReporter::printOpenHeader(std::string const& _name) {
16631 stream << getLineOfChars<'-'>() << '\n';
16632 {
16633 Colour colourGuard(Colour::Headers);
16634 printHeaderString(_name);
16635 }
16636}
16637
16638// if string has a : in first line will set indent to follow it on
16639// subsequent lines
16640void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16641 std::size_t i = _string.find(": ");
16642 if (i != std::string::npos)
16643 i += 2;
16644 else
16645 i = 0;
16646 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16647}
16648
16649struct SummaryColumn {
16650
16651 SummaryColumn(std::string _label, Colour::Code _colour)
16652 : label(std::move(_label)), colour(_colour) {}
16653 SummaryColumn addRow(std::size_t count) {
16654 ReusableStringStream rss;
16655 rss << count;
16656 std::string row = rss.str();
16657 for (auto& oldRow : rows) {
16658 while (oldRow.size() < row.size())
16659 oldRow = ' ' + oldRow;
16660 while (oldRow.size() > row.size())
16661 row = ' ' + row;
16662 }
16663 rows.push_back(row);
16664 return *this;
16665 }
16666
16667 std::string label;
16668 Colour::Code colour;
16669 std::vector<std::string> rows;
16670};
16671
16672void ConsoleReporter::printTotals(Totals const& totals) {
16673 if (totals.testCases.total() == 0) {
16674 stream << Colour(Colour::Warning) << "No tests ran\n";
16675 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16676 stream << Colour(Colour::ResultSuccess) << "All tests passed";
16677 stream << " (" << pluralise(totals.assertions.passed, "assertion") << " in "
16678 << pluralise(totals.testCases.passed, "test case") << ')' << '\n';
16679 } else {
16680
16681 std::vector<SummaryColumn> columns;
16682 columns.push_back(SummaryColumn("", Colour::None)
16683 .addRow(totals.testCases.total())
16684 .addRow(totals.assertions.total()));
16685 columns.push_back(SummaryColumn("passed", Colour::Success)
16686 .addRow(totals.testCases.passed)
16687 .addRow(totals.assertions.passed));
16688 columns.push_back(SummaryColumn("failed", Colour::ResultError)
16689 .addRow(totals.testCases.failed)
16690 .addRow(totals.assertions.failed));
16691 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
16692 .addRow(totals.testCases.failedButOk)
16693 .addRow(totals.assertions.failedButOk));
16694
16695 printSummaryRow("test cases", columns, 0);
16696 printSummaryRow("assertions", columns, 1);
16697 }
16698}
16699void ConsoleReporter::printSummaryRow(std::string const& label,
16700 std::vector<SummaryColumn> const& cols, std::size_t row) {
16701 for (auto col : cols) {
16702 std::string value = col.rows[row];
16703 if (col.label.empty()) {
16704 stream << label << ": ";
16705 if (value != "0")
16706 stream << value;
16707 else
16708 stream << Colour(Colour::Warning) << "- none -";
16709 } else if (value != "0") {
16710 stream << Colour(Colour::LightGrey) << " | ";
16711 stream << Colour(col.colour) << value << ' ' << col.label;
16712 }
16713 }
16714 stream << '\n';
16715}
16716
16717void ConsoleReporter::printTotalsDivider(Totals const& totals) {
16718 if (totals.testCases.total() > 0) {
16719 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16720 std::size_t failedButOkRatio =
16721 makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16722 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16723 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16724 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16725 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16726 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16727
16728 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
16729 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
16730 if (totals.testCases.allPassed())
16731 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
16732 else
16733 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
16734 } else {
16735 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
16736 }
16737 stream << '\n';
16738}
16739void ConsoleReporter::printSummaryDivider() {
16740 stream << getLineOfChars<'-'>() << '\n';
16741}
16742
16743void ConsoleReporter::printTestFilters() {
16744 if (m_config->testSpec().hasFilters()) {
16745 Colour guard(Colour::BrightYellow);
16746 stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
16747 }
16748}
16749
16750CATCH_REGISTER_REPORTER("console", ConsoleReporter)
16751
16752} // end namespace Catch
16753
16754#if defined(_MSC_VER)
16755#pragma warning(pop)
16756#endif
16757
16758#if defined(__clang__)
16759#pragma clang diagnostic pop
16760#endif
16761// end catch_reporter_console.cpp
16762// start catch_reporter_junit.cpp
16763
16764#include <algorithm>
16765#include <cassert>
16766#include <ctime>
16767#include <iomanip>
16768#include <sstream>
16769
16770namespace Catch {
16771
16772namespace {
16773std::string getCurrentTimestamp() {
16774 // Beware, this is not reentrant because of backward compatibility issues
16775 // Also, UTC only, again because of backward compatibility (%z is C++11)
16776 time_t rawtime;
16777 std::time(&rawtime);
16778 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
16779
16780#ifdef _MSC_VER
16781 std::tm timeInfo = {};
16782 gmtime_s(&timeInfo, &rawtime);
16783#else
16784 std::tm* timeInfo;
16785 timeInfo = std::gmtime(&rawtime);
16786#endif
16787
16788 char timeStamp[timeStampSize];
16789 const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
16790
16791#ifdef _MSC_VER
16792 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16793#else
16794 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16795#endif
16796 return std::string(timeStamp, timeStampSize - 1);
16797}
16798
16799std::string fileNameTag(const std::vector<std::string>& tags) {
16800 auto it = std::find_if(begin(tags), end(tags),
16801 [](std::string const& tag) { return tag.front() == '#'; });
16802 if (it != tags.end())
16803 return it->substr(1);
16804 return std::string();
16805}
16806
16807// Formats the duration in seconds to 3 decimal places.
16808// This is done because some genius defined Maven Surefire schema
16809// in a way that only accepts 3 decimal places, and tools like
16810// Jenkins use that schema for validation JUnit reporter output.
16811std::string formatDuration(double seconds) {
16813 rss << std::fixed << std::setprecision(3) << seconds;
16814 return rss.str();
16815}
16816
16817} // anonymous namespace
16818
16819JunitReporter::JunitReporter(ReporterConfig const& _config)
16820 : CumulativeReporterBase(_config), xml(_config.stream()) {
16821 m_reporterPrefs.shouldRedirectStdOut = true;
16822 m_reporterPrefs.shouldReportAllAssertions = true;
16823}
16824
16825JunitReporter::~JunitReporter() {}
16826
16827std::string JunitReporter::getDescription() {
16828 return "Reports test results in an XML format that looks like Ant's "
16829 "junitreport target";
16830}
16831
16832void JunitReporter::noMatchingTestCases(std::string const& /*spec*/) {}
16833
16834void JunitReporter::testRunStarting(TestRunInfo const& runInfo) {
16835 CumulativeReporterBase::testRunStarting(runInfo);
16836 xml.startElement("testsuites");
16837}
16838
16839void JunitReporter::testGroupStarting(GroupInfo const& groupInfo) {
16840 suiteTimer.start();
16841 stdOutForSuite.clear();
16842 stdErrForSuite.clear();
16843 unexpectedExceptions = 0;
16844 CumulativeReporterBase::testGroupStarting(groupInfo);
16845}
16846
16847void JunitReporter::testCaseStarting(TestCaseInfo const& testCaseInfo) {
16848 m_okToFail = testCaseInfo.okToFail();
16849}
16850
16851bool JunitReporter::assertionEnded(AssertionStats const& assertionStats) {
16852 if (assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail)
16853 unexpectedExceptions++;
16854 return CumulativeReporterBase::assertionEnded(assertionStats);
16855}
16856
16857void JunitReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
16858 stdOutForSuite += testCaseStats.stdOut;
16859 stdErrForSuite += testCaseStats.stdErr;
16860 CumulativeReporterBase::testCaseEnded(testCaseStats);
16861}
16862
16863void JunitReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
16864 double suiteTime = suiteTimer.getElapsedSeconds();
16865 CumulativeReporterBase::testGroupEnded(testGroupStats);
16866 writeGroup(*m_testGroups.back(), suiteTime);
16867}
16868
16869void JunitReporter::testRunEndedCumulative() {
16870 xml.endElement();
16871}
16872
16873void JunitReporter::writeGroup(TestGroupNode const& groupNode, double suiteTime) {
16874 XmlWriter::ScopedElement e = xml.scopedElement("testsuite");
16875
16876 TestGroupStats const& stats = groupNode.value;
16877 xml.writeAttribute("name", stats.groupInfo.name);
16878 xml.writeAttribute("errors", unexpectedExceptions);
16879 xml.writeAttribute("failures", stats.totals.assertions.failed - unexpectedExceptions);
16880 xml.writeAttribute("tests", stats.totals.assertions.total());
16881 xml.writeAttribute("hostname", "tbd"); // !TBD
16882 if (m_config->showDurations() == ShowDurations::Never)
16883 xml.writeAttribute("time", "");
16884 else
16885 xml.writeAttribute("time", formatDuration(suiteTime));
16886 xml.writeAttribute("timestamp", getCurrentTimestamp());
16887
16888 // Write properties if there are any
16889 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16890 auto properties = xml.scopedElement("properties");
16891 if (m_config->hasTestFilters()) {
16892 xml.scopedElement("property")
16893 .writeAttribute("name", "filters")
16894 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16895 }
16896 if (m_config->rngSeed() != 0) {
16897 xml.scopedElement("property")
16898 .writeAttribute("name", "random-seed")
16899 .writeAttribute("value", m_config->rngSeed());
16900 }
16901 }
16902
16903 // Write test cases
16904 for (auto const& child : groupNode.children)
16905 writeTestCase(*child);
16906
16907 xml.scopedElement("system-out").writeText(trim(stdOutForSuite), XmlFormatting::Newline);
16908 xml.scopedElement("system-err").writeText(trim(stdErrForSuite), XmlFormatting::Newline);
16909}
16910
16911void JunitReporter::writeTestCase(TestCaseNode const& testCaseNode) {
16912 TestCaseStats const& stats = testCaseNode.value;
16913
16914 // All test cases have exactly one section - which represents the
16915 // test case itself. That section may have 0-n nested sections
16916 assert(testCaseNode.children.size() == 1);
16917 SectionNode const& rootSection = *testCaseNode.children.front();
16918
16919 std::string className = stats.testInfo.className;
16920
16921 if (className.empty()) {
16922 className = fileNameTag(stats.testInfo.tags);
16923 if (className.empty())
16924 className = "global";
16925 }
16926
16927 if (!m_config->name().empty())
16928 className = m_config->name() + "." + className;
16929
16930 writeSection(className, "", rootSection, stats.testInfo.okToFail());
16931}
16932
16933void JunitReporter::writeSection(std::string const& className, std::string const& rootName,
16934 SectionNode const& sectionNode, bool testOkToFail) {
16935 std::string name = trim(sectionNode.stats.sectionInfo.name);
16936 if (!rootName.empty())
16937 name = rootName + '/' + name;
16938
16939 if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() ||
16940 !sectionNode.stdErr.empty()) {
16941 XmlWriter::ScopedElement e = xml.scopedElement("testcase");
16942 if (className.empty()) {
16943 xml.writeAttribute("classname", name);
16944 xml.writeAttribute("name", "root");
16945 } else {
16946 xml.writeAttribute("classname", className);
16947 xml.writeAttribute("name", name);
16948 }
16949 xml.writeAttribute("time", formatDuration(sectionNode.stats.durationInSeconds));
16950 // This is not ideal, but it should be enough to mimic gtest's
16951 // junit output.
16952 // Ideally the JUnit reporter would also handle `skipTest`
16953 // events and write those out appropriately.
16954 xml.writeAttribute("status", "run");
16955
16956 if (sectionNode.stats.assertions.failedButOk) {
16957 xml.scopedElement("skipped").writeAttribute("message",
16958 "TEST_CASE tagged with !mayfail");
16959 }
16960
16961 writeAssertions(sectionNode);
16962
16963 if (!sectionNode.stdOut.empty())
16964 xml.scopedElement("system-out")
16965 .writeText(trim(sectionNode.stdOut), XmlFormatting::Newline);
16966 if (!sectionNode.stdErr.empty())
16967 xml.scopedElement("system-err")
16968 .writeText(trim(sectionNode.stdErr), XmlFormatting::Newline);
16969 }
16970 for (auto const& childNode : sectionNode.childSections)
16971 if (className.empty())
16972 writeSection(name, "", *childNode, testOkToFail);
16973 else
16974 writeSection(className, name, *childNode, testOkToFail);
16975}
16976
16977void JunitReporter::writeAssertions(SectionNode const& sectionNode) {
16978 for (auto const& assertion : sectionNode.assertions)
16979 writeAssertion(assertion);
16980}
16981
16982void JunitReporter::writeAssertion(AssertionStats const& stats) {
16983 AssertionResult const& result = stats.assertionResult;
16984 if (!result.isOk()) {
16985 std::string elementName;
16986 switch (result.getResultType()) {
16987 case ResultWas::ThrewException:
16988 case ResultWas::FatalErrorCondition:
16989 elementName = "error";
16990 break;
16991 case ResultWas::ExplicitFailure:
16992 case ResultWas::ExpressionFailed:
16993 case ResultWas::DidntThrowException:
16994 elementName = "failure";
16995 break;
16996
16997 // We should never see these here:
16998 case ResultWas::Info:
16999 case ResultWas::Warning:
17000 case ResultWas::Ok:
17001 case ResultWas::Unknown:
17002 case ResultWas::FailureBit:
17003 case ResultWas::Exception:
17004 elementName = "internalError";
17005 break;
17006 }
17007
17008 XmlWriter::ScopedElement e = xml.scopedElement(elementName);
17009
17010 xml.writeAttribute("message", result.getExpression());
17011 xml.writeAttribute("type", result.getTestMacroName());
17012
17014 if (stats.totals.assertions.total() > 0) {
17015 rss << "FAILED" << ":\n";
17016 if (result.hasExpression()) {
17017 rss << " ";
17018 rss << result.getExpressionInMacro();
17019 rss << '\n';
17020 }
17021 if (result.hasExpandedExpression()) {
17022 rss << "with expansion:\n";
17023 rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17024 }
17025 } else {
17026 rss << '\n';
17027 }
17028
17029 if (!result.getMessage().empty())
17030 rss << result.getMessage() << '\n';
17031 for (auto const& msg : stats.infoMessages)
17032 if (msg.type == ResultWas::Info)
17033 rss << msg.message << '\n';
17034
17035 rss << "at " << result.getSourceInfo();
17036 xml.writeText(rss.str(), XmlFormatting::Newline);
17037 }
17038}
17039
17040CATCH_REGISTER_REPORTER("junit", JunitReporter)
17041
17042} // end namespace Catch
17043// end catch_reporter_junit.cpp
17044// start catch_reporter_listening.cpp
17045
17046#include <cassert>
17047
17048namespace Catch {
17049
17050ListeningReporter::ListeningReporter() {
17051 // We will assume that listeners will always want all assertions
17052 m_preferences.shouldReportAllAssertions = true;
17053}
17054
17055void ListeningReporter::addListener(IStreamingReporterPtr&& listener) {
17056 m_listeners.push_back(std::move(listener));
17057}
17058
17059void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17060 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17061 m_reporter = std::move(reporter);
17062 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17063}
17064
17065ReporterPreferences ListeningReporter::getPreferences() const {
17066 return m_preferences;
17067}
17068
17069std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17070 return std::set<Verbosity>{};
17071}
17072
17073void ListeningReporter::noMatchingTestCases(std::string const& spec) {
17074 for (auto const& listener : m_listeners) {
17075 listener->noMatchingTestCases(spec);
17076 }
17077 m_reporter->noMatchingTestCases(spec);
17078}
17079
17080void ListeningReporter::reportInvalidArguments(std::string const& arg) {
17081 for (auto const& listener : m_listeners) {
17082 listener->reportInvalidArguments(arg);
17083 }
17084 m_reporter->reportInvalidArguments(arg);
17085}
17086
17087#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17088void ListeningReporter::benchmarkPreparing(std::string const& name) {
17089 for (auto const& listener : m_listeners) {
17090 listener->benchmarkPreparing(name);
17091 }
17092 m_reporter->benchmarkPreparing(name);
17093}
17094void ListeningReporter::benchmarkStarting(BenchmarkInfo const& benchmarkInfo) {
17095 for (auto const& listener : m_listeners) {
17096 listener->benchmarkStarting(benchmarkInfo);
17097 }
17098 m_reporter->benchmarkStarting(benchmarkInfo);
17099}
17100void ListeningReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17101 for (auto const& listener : m_listeners) {
17102 listener->benchmarkEnded(benchmarkStats);
17103 }
17104 m_reporter->benchmarkEnded(benchmarkStats);
17105}
17106
17107void ListeningReporter::benchmarkFailed(std::string const& error) {
17108 for (auto const& listener : m_listeners) {
17109 listener->benchmarkFailed(error);
17110 }
17111 m_reporter->benchmarkFailed(error);
17112}
17113#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17114
17115void ListeningReporter::testRunStarting(TestRunInfo const& testRunInfo) {
17116 for (auto const& listener : m_listeners) {
17117 listener->testRunStarting(testRunInfo);
17118 }
17119 m_reporter->testRunStarting(testRunInfo);
17120}
17121
17122void ListeningReporter::testGroupStarting(GroupInfo const& groupInfo) {
17123 for (auto const& listener : m_listeners) {
17124 listener->testGroupStarting(groupInfo);
17125 }
17126 m_reporter->testGroupStarting(groupInfo);
17127}
17128
17129void ListeningReporter::testCaseStarting(TestCaseInfo const& testInfo) {
17130 for (auto const& listener : m_listeners) {
17131 listener->testCaseStarting(testInfo);
17132 }
17133 m_reporter->testCaseStarting(testInfo);
17134}
17135
17136void ListeningReporter::sectionStarting(SectionInfo const& sectionInfo) {
17137 for (auto const& listener : m_listeners) {
17138 listener->sectionStarting(sectionInfo);
17139 }
17140 m_reporter->sectionStarting(sectionInfo);
17141}
17142
17143void ListeningReporter::assertionStarting(AssertionInfo const& assertionInfo) {
17144 for (auto const& listener : m_listeners) {
17145 listener->assertionStarting(assertionInfo);
17146 }
17147 m_reporter->assertionStarting(assertionInfo);
17148}
17149
17150// The return value indicates if the messages buffer should be cleared:
17151bool ListeningReporter::assertionEnded(AssertionStats const& assertionStats) {
17152 for (auto const& listener : m_listeners) {
17153 static_cast<void>(listener->assertionEnded(assertionStats));
17154 }
17155 return m_reporter->assertionEnded(assertionStats);
17156}
17157
17158void ListeningReporter::sectionEnded(SectionStats const& sectionStats) {
17159 for (auto const& listener : m_listeners) {
17160 listener->sectionEnded(sectionStats);
17161 }
17162 m_reporter->sectionEnded(sectionStats);
17163}
17164
17165void ListeningReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17166 for (auto const& listener : m_listeners) {
17167 listener->testCaseEnded(testCaseStats);
17168 }
17169 m_reporter->testCaseEnded(testCaseStats);
17170}
17171
17172void ListeningReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17173 for (auto const& listener : m_listeners) {
17174 listener->testGroupEnded(testGroupStats);
17175 }
17176 m_reporter->testGroupEnded(testGroupStats);
17177}
17178
17179void ListeningReporter::testRunEnded(TestRunStats const& testRunStats) {
17180 for (auto const& listener : m_listeners) {
17181 listener->testRunEnded(testRunStats);
17182 }
17183 m_reporter->testRunEnded(testRunStats);
17184}
17185
17186void ListeningReporter::skipTest(TestCaseInfo const& testInfo) {
17187 for (auto const& listener : m_listeners) {
17188 listener->skipTest(testInfo);
17189 }
17190 m_reporter->skipTest(testInfo);
17191}
17192
17193bool ListeningReporter::isMulti() const {
17194 return true;
17195}
17196
17197} // end namespace Catch
17198// end catch_reporter_listening.cpp
17199// start catch_reporter_xml.cpp
17200
17201#if defined(_MSC_VER)
17202#pragma warning(push)
17203#pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in
17204 // switch Note that 4062 (not all labels are
17205 // handled and default is missing) is enabled
17206#endif
17207
17208namespace Catch {
17209XmlReporter::XmlReporter(ReporterConfig const& _config)
17210 : StreamingReporterBase(_config), m_xml(_config.stream()) {
17211 m_reporterPrefs.shouldRedirectStdOut = true;
17212 m_reporterPrefs.shouldReportAllAssertions = true;
17213}
17214
17215XmlReporter::~XmlReporter() = default;
17216
17217std::string XmlReporter::getDescription() {
17218 return "Reports test results as an XML document";
17219}
17220
17221std::string XmlReporter::getStylesheetRef() const {
17222 return std::string();
17223}
17224
17225void XmlReporter::writeSourceInfo(SourceLineInfo const& sourceInfo) {
17226 m_xml.writeAttribute("filename", sourceInfo.file).writeAttribute("line", sourceInfo.line);
17227}
17228
17229void XmlReporter::noMatchingTestCases(std::string const& s) {
17230 StreamingReporterBase::noMatchingTestCases(s);
17231}
17232
17233void XmlReporter::testRunStarting(TestRunInfo const& testInfo) {
17234 StreamingReporterBase::testRunStarting(testInfo);
17235 std::string stylesheetRef = getStylesheetRef();
17236 if (!stylesheetRef.empty())
17237 m_xml.writeStylesheetRef(stylesheetRef);
17238 m_xml.startElement("Catch");
17239 if (!m_config->name().empty())
17240 m_xml.writeAttribute("name", m_config->name());
17241 if (m_config->testSpec().hasFilters())
17242 m_xml.writeAttribute("filters", serializeFilters(m_config->getTestsOrTags()));
17243 if (m_config->rngSeed() != 0)
17244 m_xml.scopedElement("Randomness").writeAttribute("seed", m_config->rngSeed());
17245}
17246
17247void XmlReporter::testGroupStarting(GroupInfo const& groupInfo) {
17248 StreamingReporterBase::testGroupStarting(groupInfo);
17249 m_xml.startElement("Group").writeAttribute("name", groupInfo.name);
17250}
17251
17252void XmlReporter::testCaseStarting(TestCaseInfo const& testInfo) {
17253 StreamingReporterBase::testCaseStarting(testInfo);
17254 m_xml.startElement("TestCase")
17255 .writeAttribute("name", trim(testInfo.name))
17256 .writeAttribute("description", testInfo.description)
17257 .writeAttribute("tags", testInfo.tagsAsString());
17258
17259 writeSourceInfo(testInfo.lineInfo);
17260
17261 if (m_config->showDurations() == ShowDurations::Always)
17262 m_testCaseTimer.start();
17263 m_xml.ensureTagClosed();
17264}
17265
17266void XmlReporter::sectionStarting(SectionInfo const& sectionInfo) {
17267 StreamingReporterBase::sectionStarting(sectionInfo);
17268 if (m_sectionDepth++ > 0) {
17269 m_xml.startElement("Section").writeAttribute("name", trim(sectionInfo.name));
17270 writeSourceInfo(sectionInfo.lineInfo);
17271 m_xml.ensureTagClosed();
17272 }
17273}
17274
17275void XmlReporter::assertionStarting(AssertionInfo const&) {}
17276
17277bool XmlReporter::assertionEnded(AssertionStats const& assertionStats) {
17278
17279 AssertionResult const& result = assertionStats.assertionResult;
17280
17281 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17282
17283 if (includeResults || result.getResultType() == ResultWas::Warning) {
17284 // Print any info messages in <Info> tags.
17285 for (auto const& msg : assertionStats.infoMessages) {
17286 if (msg.type == ResultWas::Info && includeResults) {
17287 m_xml.scopedElement("Info").writeText(msg.message);
17288 } else if (msg.type == ResultWas::Warning) {
17289 m_xml.scopedElement("Warning").writeText(msg.message);
17290 }
17291 }
17292 }
17293
17294 // Drop out if result was successful but we're not printing them.
17295 if (!includeResults && result.getResultType() != ResultWas::Warning)
17296 return true;
17297
17298 // Print the expression if there is one.
17299 if (result.hasExpression()) {
17300 m_xml.startElement("Expression")
17301 .writeAttribute("success", result.succeeded())
17302 .writeAttribute("type", result.getTestMacroName());
17303
17304 writeSourceInfo(result.getSourceInfo());
17305
17306 m_xml.scopedElement("Original").writeText(result.getExpression());
17307 m_xml.scopedElement("Expanded").writeText(result.getExpandedExpression());
17308 }
17309
17310 // And... Print a result applicable to each result type.
17311 switch (result.getResultType()) {
17312 case ResultWas::ThrewException:
17313 m_xml.startElement("Exception");
17314 writeSourceInfo(result.getSourceInfo());
17315 m_xml.writeText(result.getMessage());
17316 m_xml.endElement();
17317 break;
17318 case ResultWas::FatalErrorCondition:
17319 m_xml.startElement("FatalErrorCondition");
17320 writeSourceInfo(result.getSourceInfo());
17321 m_xml.writeText(result.getMessage());
17322 m_xml.endElement();
17323 break;
17324 case ResultWas::Info:
17325 m_xml.scopedElement("Info").writeText(result.getMessage());
17326 break;
17327 case ResultWas::Warning:
17328 // Warning will already have been written
17329 break;
17330 case ResultWas::ExplicitFailure:
17331 m_xml.startElement("Failure");
17332 writeSourceInfo(result.getSourceInfo());
17333 m_xml.writeText(result.getMessage());
17334 m_xml.endElement();
17335 break;
17336 default:
17337 break;
17338 }
17339
17340 if (result.hasExpression())
17341 m_xml.endElement();
17342
17343 return true;
17344}
17345
17346void XmlReporter::sectionEnded(SectionStats const& sectionStats) {
17347 StreamingReporterBase::sectionEnded(sectionStats);
17348 if (--m_sectionDepth > 0) {
17349 XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults");
17350 e.writeAttribute("successes", sectionStats.assertions.passed);
17351 e.writeAttribute("failures", sectionStats.assertions.failed);
17352 e.writeAttribute("expectedFailures", sectionStats.assertions.failedButOk);
17353
17354 if (m_config->showDurations() == ShowDurations::Always)
17355 e.writeAttribute("durationInSeconds", sectionStats.durationInSeconds);
17356
17357 m_xml.endElement();
17358 }
17359}
17360
17361void XmlReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17362 StreamingReporterBase::testCaseEnded(testCaseStats);
17363 XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult");
17364 e.writeAttribute("success", testCaseStats.totals.assertions.allOk());
17365
17366 if (m_config->showDurations() == ShowDurations::Always)
17367 e.writeAttribute("durationInSeconds", m_testCaseTimer.getElapsedSeconds());
17368
17369 if (!testCaseStats.stdOut.empty())
17370 m_xml.scopedElement("StdOut").writeText(trim(testCaseStats.stdOut), XmlFormatting::Newline);
17371 if (!testCaseStats.stdErr.empty())
17372 m_xml.scopedElement("StdErr").writeText(trim(testCaseStats.stdErr), XmlFormatting::Newline);
17373
17374 m_xml.endElement();
17375}
17376
17377void XmlReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17378 StreamingReporterBase::testGroupEnded(testGroupStats);
17379 // TODO: Check testGroupStats.aborting and act accordingly.
17380 m_xml.scopedElement("OverallResults")
17381 .writeAttribute("successes", testGroupStats.totals.assertions.passed)
17382 .writeAttribute("failures", testGroupStats.totals.assertions.failed)
17383 .writeAttribute("expectedFailures", testGroupStats.totals.assertions.failedButOk);
17384 m_xml.scopedElement("OverallResultsCases")
17385 .writeAttribute("successes", testGroupStats.totals.testCases.passed)
17386 .writeAttribute("failures", testGroupStats.totals.testCases.failed)
17387 .writeAttribute("expectedFailures", testGroupStats.totals.testCases.failedButOk);
17388 m_xml.endElement();
17389}
17390
17391void XmlReporter::testRunEnded(TestRunStats const& testRunStats) {
17392 StreamingReporterBase::testRunEnded(testRunStats);
17393 m_xml.scopedElement("OverallResults")
17394 .writeAttribute("successes", testRunStats.totals.assertions.passed)
17395 .writeAttribute("failures", testRunStats.totals.assertions.failed)
17396 .writeAttribute("expectedFailures", testRunStats.totals.assertions.failedButOk);
17397 m_xml.scopedElement("OverallResultsCases")
17398 .writeAttribute("successes", testRunStats.totals.testCases.passed)
17399 .writeAttribute("failures", testRunStats.totals.testCases.failed)
17400 .writeAttribute("expectedFailures", testRunStats.totals.testCases.failedButOk);
17401 m_xml.endElement();
17402}
17403
17404#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17405void XmlReporter::benchmarkPreparing(std::string const& name) {
17406 m_xml.startElement("BenchmarkResults").writeAttribute("name", name);
17407}
17408
17409void XmlReporter::benchmarkStarting(BenchmarkInfo const& info) {
17410 m_xml.writeAttribute("samples", info.samples)
17411 .writeAttribute("resamples", info.resamples)
17412 .writeAttribute("iterations", info.iterations)
17413 .writeAttribute("clockResolution", info.clockResolution)
17414 .writeAttribute("estimatedDuration", info.estimatedDuration)
17415 .writeComment("All values in nano seconds");
17416}
17417
17418void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17419 m_xml.startElement("mean")
17420 .writeAttribute("value", benchmarkStats.mean.point.count())
17421 .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17422 .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17423 .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17424 m_xml.endElement();
17425 m_xml.startElement("standardDeviation")
17426 .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17427 .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17428 .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17429 .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17430 m_xml.endElement();
17431 m_xml.startElement("outliers")
17432 .writeAttribute("variance", benchmarkStats.outlierVariance)
17433 .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17434 .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17435 .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17436 .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17437 m_xml.endElement();
17438 m_xml.endElement();
17439}
17440
17441void XmlReporter::benchmarkFailed(std::string const& error) {
17442 m_xml.scopedElement("failed").writeAttribute("message", error);
17443 m_xml.endElement();
17444}
17445#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17446
17447CATCH_REGISTER_REPORTER("xml", XmlReporter)
17448
17449} // end namespace Catch
17450
17451#if defined(_MSC_VER)
17452#pragma warning(pop)
17453#endif
17454// end catch_reporter_xml.cpp
17455
17456namespace Catch {
17457LeakDetector leakDetector;
17458}
17459
17460#ifdef __clang__
17461#pragma clang diagnostic pop
17462#endif
17463
17464// end catch_impl.hpp
17465#endif
17466
17467#ifdef CATCH_CONFIG_MAIN
17468// start catch_default_main.hpp
17469
17470#ifndef __OBJC__
17471
17472#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && \
17473 !defined(DO_NOT_USE_WMAIN)
17474// Standard C/C++ Win32 Unicode wmain entry point
17475extern "C" int wmain(int argc, wchar_t* argv[], wchar_t*[]) {
17476#else
17477// Standard C/C++ main entry point
17478int main(int argc, char* argv[]) {
17479#endif
17480
17481 return Catch::Session().run(argc, argv);
17482}
17483
17484#else // __OBJC__
17485
17486// Objective-C entry point
17487int main(int argc, char* const argv[]) {
17488#if !CATCH_ARC_ENABLED
17489 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
17490#endif
17491
17492 Catch::registerTestMethods();
17493 int result = Catch::Session().run(argc, (char**)argv);
17494
17495#if !CATCH_ARC_ENABLED
17496 [pool drain];
17497#endif
17498
17499 return result;
17500}
17501
17502#endif // __OBJC__
17503
17504// end catch_default_main.hpp
17505#endif
17506
17507#if !defined(CATCH_CONFIG_IMPL_ONLY)
17508
17509#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17510#undef CLARA_CONFIG_MAIN
17511#endif
17512
17513#if !defined(CATCH_CONFIG_DISABLE)
17515// If this config identifier is defined then all CATCH macros are prefixed with
17516// CATCH_
17517#ifdef CATCH_CONFIG_PREFIX_ALL
17518
17519#define CATCH_REQUIRE(...) \
17520 INTERNAL_CATCH_TEST("CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
17521#define CATCH_REQUIRE_FALSE(...) \
17522 INTERNAL_CATCH_TEST("CATCH_REQUIRE_FALSE", \
17523 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
17524 __VA_ARGS__)
17525
17526#define CATCH_REQUIRE_THROWS(...) \
17527 INTERNAL_CATCH_THROWS("CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
17528#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) \
17529 INTERNAL_CATCH_THROWS_AS("CATCH_REQUIRE_THROWS_AS", exceptionType, \
17530 Catch::ResultDisposition::Normal, expr)
17531#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) \
17532 INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_REQUIRE_THROWS_WITH", \
17533 Catch::ResultDisposition::Normal, matcher, expr)
17534#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17535#define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
17536 INTERNAL_CATCH_THROWS_MATCHES("CATCH_REQUIRE_THROWS_MATCHES", exceptionType, \
17537 Catch::ResultDisposition::Normal, matcher, expr)
17538#endif // CATCH_CONFIG_DISABLE_MATCHERS
17539#define CATCH_REQUIRE_NOTHROW(...) \
17540 INTERNAL_CATCH_NO_THROW("CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
17541
17542#define CATCH_CHECK(...) \
17543 INTERNAL_CATCH_TEST("CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17544#define CATCH_CHECK_FALSE(...) \
17545 INTERNAL_CATCH_TEST("CATCH_CHECK_FALSE", \
17546 Catch::ResultDisposition::ContinueOnFailure | \
17547 Catch::ResultDisposition::FalseTest, \
17548 __VA_ARGS__)
17549#define CATCH_CHECKED_IF(...) \
17550 INTERNAL_CATCH_IF("CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17551#define CATCH_CHECKED_ELSE(...) \
17552 INTERNAL_CATCH_ELSE("CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, \
17553 __VA_ARGS__)
17554#define CATCH_CHECK_NOFAIL(...) \
17555 INTERNAL_CATCH_TEST("CATCH_CHECK_NOFAIL", \
17556 Catch::ResultDisposition::ContinueOnFailure | \
17557 Catch::ResultDisposition::SuppressFail, \
17558 __VA_ARGS__)
17559
17560#define CATCH_CHECK_THROWS(...) \
17561 INTERNAL_CATCH_THROWS("CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, \
17562 __VA_ARGS__)
17563#define CATCH_CHECK_THROWS_AS(expr, exceptionType) \
17564 INTERNAL_CATCH_THROWS_AS("CATCH_CHECK_THROWS_AS", exceptionType, \
17565 Catch::ResultDisposition::ContinueOnFailure, expr)
17566#define CATCH_CHECK_THROWS_WITH(expr, matcher) \
17567 INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_CHECK_THROWS_WITH", \
17568 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17569#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17570#define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
17571 INTERNAL_CATCH_THROWS_MATCHES("CATCH_CHECK_THROWS_MATCHES", exceptionType, \
17572 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17573#endif // CATCH_CONFIG_DISABLE_MATCHERS
17574#define CATCH_CHECK_NOTHROW(...) \
17575 INTERNAL_CATCH_NO_THROW("CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, \
17576 __VA_ARGS__)
17577
17578#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17579#define CATCH_CHECK_THAT(arg, matcher) \
17580 INTERNAL_CHECK_THAT("CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, \
17581 arg)
17582
17583#define CATCH_REQUIRE_THAT(arg, matcher) \
17584 INTERNAL_CHECK_THAT("CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
17585#endif // CATCH_CONFIG_DISABLE_MATCHERS
17586
17587#define CATCH_INFO(msg) INTERNAL_CATCH_INFO("CATCH_INFO", msg)
17588#define CATCH_UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("CATCH_UNSCOPED_INFO", msg)
17589#define CATCH_WARN(msg) \
17590 INTERNAL_CATCH_MSG("CATCH_WARN", Catch::ResultWas::Warning, \
17591 Catch::ResultDisposition::ContinueOnFailure, msg)
17592#define CATCH_CAPTURE(...) \
17593 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__)
17594
17595#define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
17596#define CATCH_TEST_CASE_METHOD(className, ...) \
17597 INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
17598#define CATCH_METHOD_AS_TEST_CASE(method, ...) \
17599 INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
17600#define CATCH_REGISTER_TEST_CASE(Function, ...) \
17601 INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
17602#define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
17603#define CATCH_DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
17604#define CATCH_FAIL(...) \
17605 INTERNAL_CATCH_MSG("CATCH_FAIL", Catch::ResultWas::ExplicitFailure, \
17606 Catch::ResultDisposition::Normal, __VA_ARGS__)
17607#define CATCH_FAIL_CHECK(...) \
17608 INTERNAL_CATCH_MSG("CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \
17609 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17610#define CATCH_SUCCEED(...) \
17611 INTERNAL_CATCH_MSG("CATCH_SUCCEED", Catch::ResultWas::Ok, \
17612 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17613
17614#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17615
17616#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17617#define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17618#define CATCH_TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
17619#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17620 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17621#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17622 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17623#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
17624#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17625 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
17626#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17627 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
17628#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17629 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17630#else
17631#define CATCH_TEMPLATE_TEST_CASE(...) \
17632 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
17633#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17634 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
17635#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17636 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
17637#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17638 INTERNAL_CATCH_EXPAND_VARGS( \
17639 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17640#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \
17641 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
17642#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17643 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
17644#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17645 INTERNAL_CATCH_EXPAND_VARGS( \
17646 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
17647#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17648 INTERNAL_CATCH_EXPAND_VARGS( \
17649 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17650#endif
17651
17652#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17653#define CATCH_STATIC_REQUIRE(...) \
17654 static_assert(__VA_ARGS__, #__VA_ARGS__); \
17655 CATCH_SUCCEED(#__VA_ARGS__)
17656#define CATCH_STATIC_REQUIRE_FALSE(...) \
17657 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
17658 CATCH_SUCCEED(#__VA_ARGS__)
17659#else
17660#define CATCH_STATIC_REQUIRE(...) CATCH_REQUIRE(__VA_ARGS__)
17661#define CATCH_STATIC_REQUIRE_FALSE(...) CATCH_REQUIRE_FALSE(__VA_ARGS__)
17662#endif
17663
17664// "BDD-style" convenience wrappers
17665#define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__)
17666#define CATCH_SCENARIO_METHOD(className, ...) \
17667 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
17668#define CATCH_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
17669#define CATCH_AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
17670#define CATCH_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
17671#define CATCH_AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
17672#define CATCH_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
17673#define CATCH_AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
17674
17675#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17676#define CATCH_BENCHMARK(...) \
17677 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), \
17678 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
17679 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
17680#define CATCH_BENCHMARK_ADVANCED(name) \
17681 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17682#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17683
17684// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not
17685// required
17686#else
17687
17688#define REQUIRE(...) INTERNAL_CATCH_TEST("REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
17689#define REQUIRE_FALSE(...) \
17690 INTERNAL_CATCH_TEST("REQUIRE_FALSE", \
17691 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
17692 __VA_ARGS__)
17693
17694#define REQUIRE_THROWS(...) \
17695 INTERNAL_CATCH_THROWS("REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
17696#define REQUIRE_THROWS_AS(expr, exceptionType) \
17697 INTERNAL_CATCH_THROWS_AS("REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, \
17698 expr)
17699#define REQUIRE_THROWS_WITH(expr, matcher) \
17700 INTERNAL_CATCH_THROWS_STR_MATCHES("REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, \
17701 matcher, expr)
17702#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17703#define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
17704 INTERNAL_CATCH_THROWS_MATCHES("REQUIRE_THROWS_MATCHES", exceptionType, \
17705 Catch::ResultDisposition::Normal, matcher, expr)
17706#endif // CATCH_CONFIG_DISABLE_MATCHERS
17707#define REQUIRE_NOTHROW(...) \
17708 INTERNAL_CATCH_NO_THROW("REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
17709
17710#define CHECK(...) \
17711 INTERNAL_CATCH_TEST("CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17712#define CHECK_FALSE(...) \
17713 INTERNAL_CATCH_TEST("CHECK_FALSE", \
17714 Catch::ResultDisposition::ContinueOnFailure | \
17715 Catch::ResultDisposition::FalseTest, \
17716 __VA_ARGS__)
17717#define CHECKED_IF(...) \
17718 INTERNAL_CATCH_IF("CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17719#define CHECKED_ELSE(...) \
17720 INTERNAL_CATCH_ELSE("CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17721#define CHECK_NOFAIL(...) \
17722 INTERNAL_CATCH_TEST("CHECK_NOFAIL", \
17723 Catch::ResultDisposition::ContinueOnFailure | \
17724 Catch::ResultDisposition::SuppressFail, \
17725 __VA_ARGS__)
17726
17727#define CHECK_THROWS(...) \
17728 INTERNAL_CATCH_THROWS("CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17729#define CHECK_THROWS_AS(expr, exceptionType) \
17730 INTERNAL_CATCH_THROWS_AS("CHECK_THROWS_AS", exceptionType, \
17731 Catch::ResultDisposition::ContinueOnFailure, expr)
17732#define CHECK_THROWS_WITH(expr, matcher) \
17733 INTERNAL_CATCH_THROWS_STR_MATCHES("CHECK_THROWS_WITH", \
17734 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17735#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17736#define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
17737 INTERNAL_CATCH_THROWS_MATCHES("CHECK_THROWS_MATCHES", exceptionType, \
17738 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17739#endif // CATCH_CONFIG_DISABLE_MATCHERS
17740#define CHECK_NOTHROW(...) \
17741 INTERNAL_CATCH_NO_THROW("CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, \
17742 __VA_ARGS__)
17743
17744#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17745#define CHECK_THAT(arg, matcher) \
17746 INTERNAL_CHECK_THAT("CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
17747
17748#define REQUIRE_THAT(arg, matcher) \
17749 INTERNAL_CHECK_THAT("REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
17750#endif // CATCH_CONFIG_DISABLE_MATCHERS
17751
17752#define INFO(msg) INTERNAL_CATCH_INFO("INFO", msg)
17753#define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("UNSCOPED_INFO", msg)
17754#define WARN(msg) \
17755 INTERNAL_CATCH_MSG("WARN", Catch::ResultWas::Warning, \
17756 Catch::ResultDisposition::ContinueOnFailure, msg)
17757#define CAPTURE(...) \
17758 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__)
17759
17760#define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
17761#define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
17762#define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
17763#define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
17764#define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
17765#define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
17766#define FAIL(...) \
17767 INTERNAL_CATCH_MSG("FAIL", Catch::ResultWas::ExplicitFailure, \
17768 Catch::ResultDisposition::Normal, __VA_ARGS__)
17769#define FAIL_CHECK(...) \
17770 INTERNAL_CATCH_MSG("FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \
17771 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17772#define SUCCEED(...) \
17773 INTERNAL_CATCH_MSG("SUCCEED", Catch::ResultWas::Ok, \
17774 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17775#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17776
17777#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17778#define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17779#define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
17780#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
17781 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17782#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17783 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17784#define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
17785#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17786 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
17787#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17788 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
17789#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17790 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17791#define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17792#define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
17793 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__)
17794#else
17795#define TEMPLATE_TEST_CASE(...) \
17796 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
17797#define TEMPLATE_TEST_CASE_SIG(...) \
17798 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
17799#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
17800 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
17801#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17802 INTERNAL_CATCH_EXPAND_VARGS( \
17803 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17804#define TEMPLATE_PRODUCT_TEST_CASE(...) \
17805 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
17806#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17807 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
17808#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17809 INTERNAL_CATCH_EXPAND_VARGS( \
17810 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
17811#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17812 INTERNAL_CATCH_EXPAND_VARGS( \
17813 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17814#define TEMPLATE_LIST_TEST_CASE(...) \
17815 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__))
17816#define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
17817 INTERNAL_CATCH_EXPAND_VARGS( \
17818 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__))
17819#endif
17820
17821#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17822#define STATIC_REQUIRE(...) \
17823 static_assert(__VA_ARGS__, #__VA_ARGS__); \
17824 SUCCEED(#__VA_ARGS__)
17825#define STATIC_REQUIRE_FALSE(...) \
17826 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
17827 SUCCEED("!(" #__VA_ARGS__ ")")
17828#else
17829#define STATIC_REQUIRE(...) REQUIRE(__VA_ARGS__)
17830#define STATIC_REQUIRE_FALSE(...) REQUIRE_FALSE(__VA_ARGS__)
17831#endif
17832
17833#endif
17834
17835#define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature)
17836
17837// "BDD-style" convenience wrappers
17838#define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__)
17839#define SCENARIO_METHOD(className, ...) \
17840 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
17841
17842#define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
17843#define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
17844#define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
17845#define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
17846#define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
17847#define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
17848
17849#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17850#define BENCHMARK(...) \
17851 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), \
17852 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
17853 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
17854#define BENCHMARK_ADVANCED(name) \
17855 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17856#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17857
17859
17860#else // CATCH_CONFIG_DISABLE
17861
17863// If this config identifier is defined then all CATCH macros are prefixed with
17864// CATCH_
17865#ifdef CATCH_CONFIG_PREFIX_ALL
17866
17867#define CATCH_REQUIRE(...) (void)(0)
17868#define CATCH_REQUIRE_FALSE(...) (void)(0)
17869
17870#define CATCH_REQUIRE_THROWS(...) (void)(0)
17871#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
17872#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
17873#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17874#define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17875#endif // CATCH_CONFIG_DISABLE_MATCHERS
17876#define CATCH_REQUIRE_NOTHROW(...) (void)(0)
17877
17878#define CATCH_CHECK(...) (void)(0)
17879#define CATCH_CHECK_FALSE(...) (void)(0)
17880#define CATCH_CHECKED_IF(...) if (__VA_ARGS__)
17881#define CATCH_CHECKED_ELSE(...) if (!(__VA_ARGS__))
17882#define CATCH_CHECK_NOFAIL(...) (void)(0)
17883
17884#define CATCH_CHECK_THROWS(...) (void)(0)
17885#define CATCH_CHECK_THROWS_AS(expr, exceptionType) (void)(0)
17886#define CATCH_CHECK_THROWS_WITH(expr, matcher) (void)(0)
17887#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17888#define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17889#endif // CATCH_CONFIG_DISABLE_MATCHERS
17890#define CATCH_CHECK_NOTHROW(...) (void)(0)
17891
17892#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17893#define CATCH_CHECK_THAT(arg, matcher) (void)(0)
17894
17895#define CATCH_REQUIRE_THAT(arg, matcher) (void)(0)
17896#endif // CATCH_CONFIG_DISABLE_MATCHERS
17897
17898#define CATCH_INFO(msg) (void)(0)
17899#define CATCH_UNSCOPED_INFO(msg) (void)(0)
17900#define CATCH_WARN(msg) (void)(0)
17901#define CATCH_CAPTURE(msg) (void)(0)
17902
17903#define CATCH_TEST_CASE(...) \
17904 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17905#define CATCH_TEST_CASE_METHOD(className, ...) \
17906 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17907#define CATCH_METHOD_AS_TEST_CASE(method, ...)
17908#define CATCH_REGISTER_TEST_CASE(Function, ...) (void)(0)
17909#define CATCH_SECTION(...)
17910#define CATCH_DYNAMIC_SECTION(...)
17911#define CATCH_FAIL(...) (void)(0)
17912#define CATCH_FAIL_CHECK(...) (void)(0)
17913#define CATCH_SUCCEED(...) (void)(0)
17914
17915#define CATCH_ANON_TEST_CASE() \
17916 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17917
17918#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17919#define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17920#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17921 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17922#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17923 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17924#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17925 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
17926#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17927#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17928#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17929 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17930#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17931 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17932#else
17933#define CATCH_TEMPLATE_TEST_CASE(...) \
17934 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
17935#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17936 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
17937#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17938 INTERNAL_CATCH_EXPAND_VARGS( \
17939 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
17940#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17941 INTERNAL_CATCH_EXPAND_VARGS( \
17942 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
17943#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17944#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17945#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17946 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17947#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17948 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17949#endif
17950
17951// "BDD-style" convenience wrappers
17952#define CATCH_SCENARIO(...) \
17953 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17954#define CATCH_SCENARIO_METHOD(className, ...) \
17955 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), \
17956 className)
17957#define CATCH_GIVEN(desc)
17958#define CATCH_AND_GIVEN(desc)
17959#define CATCH_WHEN(desc)
17960#define CATCH_AND_WHEN(desc)
17961#define CATCH_THEN(desc)
17962#define CATCH_AND_THEN(desc)
17963
17964#define CATCH_STATIC_REQUIRE(...) (void)(0)
17965#define CATCH_STATIC_REQUIRE_FALSE(...) (void)(0)
17966
17967// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not
17968// required
17969#else
17970
17971#define REQUIRE(...) (void)(0)
17972#define REQUIRE_FALSE(...) (void)(0)
17973
17974#define REQUIRE_THROWS(...) (void)(0)
17975#define REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
17976#define REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
17977#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17978#define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17979#endif // CATCH_CONFIG_DISABLE_MATCHERS
17980#define REQUIRE_NOTHROW(...) (void)(0)
17981
17982#define CHECK(...) (void)(0)
17983#define CHECK_FALSE(...) (void)(0)
17984#define CHECKED_IF(...) if (__VA_ARGS__)
17985#define CHECKED_ELSE(...) if (!(__VA_ARGS__))
17986#define CHECK_NOFAIL(...) (void)(0)
17987
17988#define CHECK_THROWS(...) (void)(0)
17989#define CHECK_THROWS_AS(expr, exceptionType) (void)(0)
17990#define CHECK_THROWS_WITH(expr, matcher) (void)(0)
17991#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17992#define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17993#endif // CATCH_CONFIG_DISABLE_MATCHERS
17994#define CHECK_NOTHROW(...) (void)(0)
17995
17996#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17997#define CHECK_THAT(arg, matcher) (void)(0)
17998
17999#define REQUIRE_THAT(arg, matcher) (void)(0)
18000#endif // CATCH_CONFIG_DISABLE_MATCHERS
18001
18002#define INFO(msg) (void)(0)
18003#define UNSCOPED_INFO(msg) (void)(0)
18004#define WARN(msg) (void)(0)
18005#define CAPTURE(...) (void)(0)
18006
18007#define TEST_CASE(...) \
18008 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18009#define TEST_CASE_METHOD(className, ...) \
18010 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18011#define METHOD_AS_TEST_CASE(method, ...)
18012#define REGISTER_TEST_CASE(Function, ...) (void)(0)
18013#define SECTION(...)
18014#define DYNAMIC_SECTION(...)
18015#define FAIL(...) (void)(0)
18016#define FAIL_CHECK(...) (void)(0)
18017#define SUCCEED(...) (void)(0)
18018#define ANON_TEST_CASE() \
18019 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18020
18021#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18022#define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18023#define TEMPLATE_TEST_CASE_SIG(...) \
18024 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18025#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18026 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18027#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18028 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18029#define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18030#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18031#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18032 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18033#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18034 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18035#else
18036#define TEMPLATE_TEST_CASE(...) \
18037 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18038#define TEMPLATE_TEST_CASE_SIG(...) \
18039 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18040#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18041 INTERNAL_CATCH_EXPAND_VARGS( \
18042 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18043#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18044 INTERNAL_CATCH_EXPAND_VARGS( \
18045 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18046#define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18047#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18048#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18049 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18050#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18051 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18052#endif
18053
18054#define STATIC_REQUIRE(...) (void)(0)
18055#define STATIC_REQUIRE_FALSE(...) (void)(0)
18056
18057#endif
18058
18059#define CATCH_TRANSLATE_EXCEPTION(signature) \
18060 INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( \
18061 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
18062
18063// "BDD-style" convenience wrappers
18064#define SCENARIO(...) \
18065 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18066#define SCENARIO_METHOD(className, ...) \
18067 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), \
18068 className)
18069
18070#define GIVEN(desc)
18071#define AND_GIVEN(desc)
18072#define WHEN(desc)
18073#define AND_WHEN(desc)
18074#define THEN(desc)
18075#define AND_THEN(desc)
18076
18078
18079#endif
18080
18081#endif // ! CATCH_CONFIG_IMPL_ONLY
18082
18083// start catch_reenable_warnings.h
18084
18085#ifdef __clang__
18086#ifdef __ICC // icpc defines the __clang__ macro
18087#pragma warning(pop)
18088#else
18089#pragma clang diagnostic pop
18090#endif
18091#elif defined __GNUC__
18092#pragma GCC diagnostic pop
18093#endif
18094
18095// end catch_reenable_warnings.h
18096// end catch.hpp
18097#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
Definition catch.hpp:2800
Definition catch.hpp:2497
Definition catch.hpp:3349
Definition catch.hpp:1923
Definition catch.hpp:2607
Definition catch.hpp:4203
Definition catch.hpp:4416
Definition catch.hpp:4259
Definition catch.hpp:4276
Definition catch.hpp:4909
Definition catch.hpp:4512
Definition catch.hpp:4871
Definition catch.hpp:4458
Definition catch.hpp:4385
Definition catch.hpp:2777
Definition catch.hpp:4046
Definition catch.hpp:520
Definition catch.hpp:4652
Definition catch.hpp:1798
Definition catch.hpp:2887
Definition catch.hpp:4781
Definition catch.hpp:635
Definition catch.hpp:5001
Definition catch.hpp:1164
Definition catch.hpp:3159
Definition catch.hpp:2560
@ error
throw a parse_error exception in case of a tag
Definition json.hpp:8727
@ object
object (unordered set of name/value pairs)
Definition json.hpp:3069
@ string
string value
Definition json.hpp:3071
std::size_t hash(const BasicJsonType &j)
hash a JSON value
Definition json.hpp:5883
StringType escape(StringType s)
string escaping as described in RFC 6901 (Sect. 4)
Definition json.hpp:3175
Definition catch.hpp:1755
Definition catch.hpp:2795
Definition catch.hpp:516
Definition catch.hpp:3098
Definition catch.hpp:2679
Definition catch.hpp:1824
Definition catch.hpp:4221
Definition catch.hpp:4319
Definition catch.hpp:4735
Definition catch.hpp:4606
Definition catch.hpp:3280
Definition catch.hpp:3286
Definition catch.hpp:4142
Definition catch.hpp:4614
Definition catch.hpp:1834
Definition catch.hpp:3245
Definition catch.hpp:3234
Definition catch.hpp:2719
Definition catch.hpp:5031
Definition catch.hpp:1791
Definition catch.hpp:608
Definition catch.hpp:600
Definition catch.hpp:2478
Definition catch.hpp:3569
Definition catch.hpp:3601
Definition catch.hpp:3562
Definition catch.hpp:3545
Definition catch.hpp:2875
Definition catch.hpp:2848
Definition catch.hpp:2865
Definition catch.hpp:1182
Definition catch.hpp:1732
Definition catch.hpp:1706
Definition catch.hpp:4718
Definition catch.hpp:3141
Definition catch.hpp:3129
Definition catch.hpp:4715
Definition catch.hpp:531
Definition catch.hpp:560
Definition catch.hpp:1969
Definition catch.hpp:4968
Definition catch.hpp:2772
Definition catch.hpp:3111
Definition catch.hpp:4721
Definition catch.hpp:4724
Definition catch.hpp:4711
Definition catch.hpp:1128
Definition catch.hpp:2291
Definition catch.hpp:2287
Definition catch.hpp:1131
Definition catch.hpp:1137
Definition catch.hpp:2298
Definition catch.hpp:3500
Definition catch.hpp:1130
Definition catch.hpp:511