3 * Generated: 2021-07-28 20:29:27.753164
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it
6 * directly Copyright (c) 2021 Two Blue Cubes Ltd. All rights reserved.
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)
11 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
15 #define CATCH_VERSION_MAJOR 2
16 #define CATCH_VERSION_MINOR 13
17 #define CATCH_VERSION_PATCH 7
20 #pragma clang system_header
21 #elif defined __GNUC__
22 #pragma GCC system_header
25 // start catch_suppress_warnings.h
28 #ifdef __ICC // icpc defines the __clang__ macro
30 #pragma warning(disable : 161 1682)
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"
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
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-variable"
45 #pragma GCC diagnostic ignored "-Wpadded"
47 // end catch_suppress_warnings.h
48 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
50 #define CATCH_CONFIG_ALL_PARTS
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
60 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
61 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
65 #if !defined(CATCH_CONFIG_IMPL_ONLY)
66 // start catch_platform.h
69 // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
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
78 #elif defined(linux) || defined(__linux) || defined(__linux__)
79 #define CATCH_PLATFORM_LINUX
81 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || \
83 #define CATCH_PLATFORM_WINDOWS
86 // end catch_platform.h
89 #ifndef CLARA_CONFIG_MAIN
90 #define CLARA_CONFIG_MAIN_NOT_DEFINED
91 #define CLARA_CONFIG_MAIN
95 // start catch_user_interfaces.h
98 unsigned int rngSeed();
101 // end catch_user_interfaces.h
102 // start catch_tag_alias_autoregistrar.h
104 // start catch_common.h
106 // start catch_compiler_capabilities.h
108 // Detect a number of compiler features - by compiler
109 // The following features are defined:
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?
116 // Note to maintainers: if new toggles are added please document them
117 // in configuration.md, too
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.
127 #if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
128 #define CATCH_CPP14_OR_GREATER
131 #if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
132 #define CATCH_CPP17_OR_GREATER
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__) && \
141 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic push")
142 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic pop")
144 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
148 #if defined(__clang__)
150 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("clang diagnostic push")
151 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("clang diagnostic pop")
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.
158 // For example, this code will likely segfault under IBM XL:
160 // REQUIRE(std::string("12") + "34" == "1234")
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, \
170 #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
171 _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
172 _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"")
174 #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
175 _Pragma("clang diagnostic ignored \"-Wparentheses\"")
177 #define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
178 _Pragma("clang diagnostic ignored \"-Wunused-variable\"")
180 #define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
181 _Pragma("clang diagnostic ignored " \
182 "\"-Wgnu-zero-variadic-macro-arguments\"")
184 #define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
185 _Pragma("clang diagnostic ignored \"-Wunused-template\"")
189 ////////////////////////////////////////////////////////////////////////////////
190 // Assume that non-Windows platforms support posix signals by default
191 #if !defined(CATCH_PLATFORM_WINDOWS)
192 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
195 ////////////////////////////////////////////////////////////////////////////////
196 // We know some environments not to support full POSIX signals
197 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
198 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
202 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
203 #define CATCH_CONFIG_COLOUR_NONE
206 ////////////////////////////////////////////////////////////////////////////////
207 // Android somehow still does not support std::to_string
208 #if defined(__ANDROID__)
209 #define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
210 #define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
213 ////////////////////////////////////////////////////////////////////////////////
214 // Not all Windows environments support SEH properly
215 #if defined(__MINGW32__)
216 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
219 ////////////////////////////////////////////////////////////////////////////////
221 #if defined(__ORBIS__)
222 #define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
225 ////////////////////////////////////////////////////////////////////////////////
229 // Required for some versions of Cygwin to declare gettimeofday
231 // http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
233 // some versions of cygwin (most) do not support std::to_string. Use the libstd
235 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html
237 #if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) && \
238 !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
240 #define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
245 ////////////////////////////////////////////////////////////////////////////////
247 #if defined(_MSC_VER)
249 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma(warning(push))
250 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma(warning(pop))
252 // Universal Windows platform does not support SEH
253 // Or console colours (or console at all...)
254 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
255 #define CATCH_CONFIG_COLOUR_NONE
257 #define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
260 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
261 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
262 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
263 #if !defined(__clang__) // Handle Clang masquerading for msvc
264 #if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
265 #define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
266 #endif // MSVC_TRADITIONAL
271 #if defined(_REENTRANT) || defined(_MSC_VER)
272 // Enable async processing, as -pthread is specified or no additional linking is
274 #define CATCH_INTERNAL_CONFIG_USE_ASYNC
277 ////////////////////////////////////////////////////////////////////////////////
278 // Check if we are compiled with -fno-exceptions or equivalent
279 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
280 #define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
283 ////////////////////////////////////////////////////////////////////////////////
286 #define CATCH_INTERNAL_CONFIG_NO_WCHAR
289 ////////////////////////////////////////////////////////////////////////////////
290 // Embarcadero C++Build
291 #if defined(__BORLANDC__)
292 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
295 ////////////////////////////////////////////////////////////////////////////////
297 // Use of __COUNTER__ is suppressed during code analysis in
298 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
300 // Otherwise all supported compilers support COUNTER macro,
301 // but user still might want to turn it off
302 #if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L)
303 #define CATCH_INTERNAL_CONFIG_COUNTER
306 ////////////////////////////////////////////////////////////////////////////////
308 // RTX is a special version of Windows that is real time.
309 // This means that it is detected as Windows, but does not provide
310 // the same set of capabilities as real Windows does.
311 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
312 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
313 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
314 #define CATCH_CONFIG_COLOUR_NONE
317 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
318 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
321 // Various stdlib support checks that require __has_include
322 #if defined(__has_include)
323 // Check if string_view is available and usable
324 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
325 #define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
328 // Check if optional is available and usable
329 #if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
330 #define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
331 #endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
333 // Check if byte is available and usable
334 #if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
336 #if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
337 #define CATCH_INTERNAL_CONFIG_CPP17_BYTE
339 #endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
341 // Check if variant is available and usable
342 #if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
343 #if defined(__clang__) && (__clang_major__ < 8)
344 // work around clang bug with libstdc++
345 // https://bugs.llvm.org/show_bug.cgi?id=31852 fix should be in clang 8,
346 // workaround in libstdc++ 8.2
348 #if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
349 #define CATCH_CONFIG_NO_CPP17_VARIANT
351 #define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
352 #endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE
355 #define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
356 #endif // defined(__clang__) && (__clang_major__ < 8)
357 #endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
358 #endif // defined(__has_include)
360 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && \
361 !defined(CATCH_CONFIG_COUNTER)
362 #define CATCH_CONFIG_COUNTER
364 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && \
365 !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
366 #define CATCH_CONFIG_WINDOWS_SEH
368 // This is set by default, because we assume that unix compilers are
369 // posix-signal-compatible by default.
370 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && \
371 !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && \
372 !defined(CATCH_CONFIG_POSIX_SIGNALS)
373 #define CATCH_CONFIG_POSIX_SIGNALS
375 // This is set by default, because we assume that compilers with no wchar_t
376 // support are just rare exceptions.
377 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && \
378 !defined(CATCH_CONFIG_WCHAR)
379 #define CATCH_CONFIG_WCHAR
382 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && \
383 !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
384 #define CATCH_CONFIG_CPP11_TO_STRING
387 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && \
388 !defined(CATCH_CONFIG_CPP17_OPTIONAL)
389 #define CATCH_CONFIG_CPP17_OPTIONAL
392 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && \
393 !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
394 #define CATCH_CONFIG_CPP17_STRING_VIEW
397 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && \
398 !defined(CATCH_CONFIG_CPP17_VARIANT)
399 #define CATCH_CONFIG_CPP17_VARIANT
402 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && \
403 !defined(CATCH_CONFIG_CPP17_BYTE)
404 #define CATCH_CONFIG_CPP17_BYTE
407 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
408 #define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
411 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && \
412 !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && \
413 !defined(CATCH_CONFIG_NEW_CAPTURE)
414 #define CATCH_CONFIG_NEW_CAPTURE
417 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
418 #define CATCH_CONFIG_DISABLE_EXCEPTIONS
421 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && \
422 !defined(CATCH_CONFIG_POLYFILL_ISNAN)
423 #define CATCH_CONFIG_POLYFILL_ISNAN
426 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && \
427 !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
428 #define CATCH_CONFIG_USE_ASYNC
431 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && \
432 !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
433 #define CATCH_CONFIG_ANDROID_LOGWRITE
436 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && \
437 !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
438 #define CATCH_CONFIG_GLOBAL_NEXTAFTER
441 // Even if we do not think the compiler has that warning, we still have
442 // to provide a macro that can be used by the code.
443 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
444 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
446 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
447 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
449 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
450 #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
452 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
453 #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
455 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
456 #define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
458 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
459 #define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
462 // The goal of this macro is to avoid evaluation of the arguments, but
463 // still have the compiler warn on problems inside...
464 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
465 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
468 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
469 #undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
470 #elif defined(__clang__) && (__clang_major__ < 5)
471 #undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
474 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
475 #define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
478 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
479 #define CATCH_TRY if ((true))
480 #define CATCH_CATCH_ALL if ((false))
481 #define CATCH_CATCH_ANON(type) if ((false))
483 #define CATCH_TRY try
484 #define CATCH_CATCH_ALL catch (...)
485 #define CATCH_CATCH_ANON(type) catch (type)
488 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && \
489 !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && \
490 !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
491 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
494 // end catch_compiler_capabilities.h
495 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line
496 #define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line)
497 #ifdef CATCH_CONFIG_COUNTER
498 #define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__)
500 #define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__)
507 // We need a dummy global operator<< so we can bring it into Catch namespace
509 struct Catch_global_namespace_dummy {};
510 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
514 struct CaseSensitive {
515 enum Choice { Yes, No };
519 NonCopyable(NonCopyable const&) = delete;
520 NonCopyable(NonCopyable&&) = delete;
521 NonCopyable& operator=(NonCopyable const&) = delete;
522 NonCopyable& operator=(NonCopyable&&) = delete;
526 virtual ~NonCopyable();
529 struct SourceLineInfo {
531 SourceLineInfo() = delete;
532 SourceLineInfo(char const* _file, std::size_t _line) noexcept : file(_file), line(_line) {}
534 SourceLineInfo(SourceLineInfo const& other) = default;
535 SourceLineInfo& operator=(SourceLineInfo const&) = default;
536 SourceLineInfo(SourceLineInfo&&) noexcept = default;
537 SourceLineInfo& operator=(SourceLineInfo&&) noexcept = default;
539 bool empty() const noexcept { return file[0] == '\0'; }
540 bool operator==(SourceLineInfo const& other) const noexcept;
541 bool operator<(SourceLineInfo const& other) const noexcept;
547 std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info);
549 // Bring in operator<< from global namespace into Catch namespace
550 // This is necessary because the overload of operator<< above makes
551 // lookup stop at namespace Catch
554 // Use this in variadic streaming macros to allow
557 // >> stuff +StreamEndStop
558 struct StreamEndStop {
559 std::string operator+() const;
561 template <typename T> T const& operator+(T const& value, StreamEndStop) { return value; }
564 #define CATCH_INTERNAL_LINEINFO \
565 ::Catch::SourceLineInfo(__FILE__, static_cast<std::size_t>(__LINE__))
567 // end catch_common.h
570 struct RegistrarForTagAliases {
571 RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo);
574 } // end namespace Catch
576 #define CATCH_REGISTER_TAG_ALIAS(alias, spec) \
577 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
578 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
580 Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME(AutoRegisterTagAlias)( \
581 alias, spec, CATCH_INTERNAL_LINEINFO); \
583 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
585 // end catch_tag_alias_autoregistrar.h
586 // start catch_test_registry.h
588 // start catch_interfaces_testcase.h
596 struct ITestInvoker {
597 virtual void invoke() const = 0;
598 virtual ~ITestInvoker();
604 struct ITestCaseRegistry {
605 virtual ~ITestCaseRegistry();
606 virtual std::vector<TestCase> const& getAllTests() const = 0;
607 virtual std::vector<TestCase> const& getAllTestsSorted(IConfig const& config) const = 0;
610 bool isThrowSafe(TestCase const& testCase, IConfig const& config);
611 bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config);
612 std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases,
613 TestSpec const& testSpec,
614 IConfig const& config);
615 std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config);
619 // end catch_interfaces_testcase.h
620 // start catch_stringref.h
629 /// A non-owning string class (similar to the forthcoming std::string_view)
630 /// Note that, because a StringRef may be a substring of another string,
631 /// it may not be null terminated.
634 using size_type = std::size_t;
635 using const_iterator = const char*;
638 static constexpr char const* const s_empty = "";
640 char const* m_start = s_empty;
641 size_type m_size = 0;
643 public: // construction
644 constexpr StringRef() noexcept = default;
646 StringRef(char const* rawChars) noexcept;
648 constexpr StringRef(char const* rawChars, size_type size) noexcept :
649 m_start(rawChars), m_size(size) {}
651 StringRef(std::string const& stdString) noexcept :
652 m_start(stdString.c_str()), m_size(stdString.size()) {}
654 explicit operator std::string() const { return std::string(m_start, m_size); }
657 auto operator==(StringRef const& other) const noexcept -> bool;
658 auto operator!=(StringRef const& other) const noexcept -> bool { return !(*this == other); }
660 auto operator[](size_type index) const noexcept -> char {
661 assert(index < m_size);
662 return m_start[index];
665 public: // named queries
666 constexpr auto empty() const noexcept -> bool { return m_size == 0; }
667 constexpr auto size() const noexcept -> size_type { return m_size; }
669 // Returns the current start pointer. If the StringRef is not
670 // null-terminated, throws std::domain_exception
671 auto c_str() const -> char const*;
673 public: // substrings and searches
674 // Returns a substring of [start, start + length).
675 // If start + length > size(), then the substring is [start, size()).
676 // If start > size(), then the substring is empty.
677 auto substr(size_type start, size_type length) const noexcept -> StringRef;
679 // Returns the current start pointer. May not be null-terminated.
680 auto data() const noexcept -> char const*;
682 constexpr auto isNullTerminated() const noexcept -> bool { return m_start[m_size] == '\0'; }
685 constexpr const_iterator begin() const { return m_start; }
686 constexpr const_iterator end() const { return m_start + m_size; }
689 auto operator+=(std::string& lhs, StringRef const& sr) -> std::string&;
690 auto operator<<(std::ostream& os, StringRef const& sr) -> std::ostream&;
692 constexpr auto operator"" _sr(char const* rawChars, std::size_t size) noexcept -> StringRef {
693 return StringRef(rawChars, size);
697 constexpr auto operator"" _catch_sr(char const* rawChars, std::size_t size) noexcept
698 -> Catch::StringRef {
699 return Catch::StringRef(rawChars, size);
702 // end catch_stringref.h
703 // start catch_preprocessor.hpp
705 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
706 #define CATCH_RECURSION_LEVEL1(...) \
707 CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
708 #define CATCH_RECURSION_LEVEL2(...) \
709 CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
710 #define CATCH_RECURSION_LEVEL3(...) \
711 CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
712 #define CATCH_RECURSION_LEVEL4(...) \
713 CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
714 #define CATCH_RECURSION_LEVEL5(...) \
715 CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
717 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
718 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
719 // MSVC needs more evaluations
720 #define CATCH_RECURSION_LEVEL6(...) \
721 CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
722 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
724 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
727 #define CATCH_REC_END(...)
728 #define CATCH_REC_OUT
730 #define CATCH_EMPTY()
731 #define CATCH_DEFER(id) id CATCH_EMPTY()
733 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
734 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
735 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
736 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
737 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER(CATCH_REC_NEXT0)(test, next, 0)
738 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
740 #define CATCH_REC_LIST0(f, x, peek, ...) \
741 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
742 #define CATCH_REC_LIST1(f, x, peek, ...) \
743 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0))(f, peek, __VA_ARGS__)
744 #define CATCH_REC_LIST2(f, x, peek, ...) \
745 f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
747 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) \
749 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
750 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) \
752 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD))(f, userdata, peek, __VA_ARGS__)
753 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) \
755 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
757 // Applies the function macro `f` to each of the remaining parameters, inserts
758 // commas between the results, and passes userdata as the first parameter to
759 // each invocation, e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a),
761 #define CATCH_REC_LIST_UD(f, userdata, ...) \
762 CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
764 #define CATCH_REC_LIST(f, ...) \
765 CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
767 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
768 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO##__VA_ARGS__
769 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
770 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
771 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
772 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
773 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
774 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
775 INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
777 // MSVC is adding extra space and needs another indirection to expand
778 // INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
779 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
780 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
781 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
782 (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
785 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
786 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
788 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
790 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
791 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
792 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
793 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
794 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
796 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
797 INTERNAL_CATCH_EXPAND_VARGS( \
798 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
799 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
800 INTERNAL_CATCH_EXPAND_VARGS( \
801 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
804 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...) \
805 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST, __VA_ARGS__)
807 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
808 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) \
809 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
810 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) \
811 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
812 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) \
813 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
814 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) \
815 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
816 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) \
817 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
818 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) \
819 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
820 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) \
821 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
822 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) \
823 INTERNAL_CATCH_REMOVE_PARENS(_0), \
824 INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
825 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \
826 INTERNAL_CATCH_REMOVE_PARENS(_0), \
827 INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
828 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \
829 INTERNAL_CATCH_REMOVE_PARENS(_0), \
830 INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
832 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
834 #define INTERNAL_CATCH_TYPE_GEN \
835 template <typename...> struct TypeList {}; \
836 template <typename... Ts> constexpr auto get_wrapper() noexcept->TypeList<Ts...> { \
839 template <template <typename...> class...> struct TemplateTypeList {}; \
840 template <template <typename...> class... Cs> \
841 constexpr auto get_wrapper() noexcept->TemplateTypeList<Cs...> { \
844 template <typename...> struct append; \
845 template <typename...> struct rewrap; \
846 template <template <typename...> class, typename...> struct create; \
847 template <template <typename...> class, typename> struct convert; \
849 template <typename T> struct append<T> { using type = T; }; \
850 template <template <typename...> class L1, \
852 template <typename...> \
856 struct append<L1<E1...>, L2<E2...>, Rest...> { \
857 using type = typename append<L1<E1..., E2...>, Rest...>::type; \
859 template <template <typename...> class L1, typename... E1, typename... Rest> \
860 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { \
861 using type = L1<E1...>; \
864 template <template <typename...> class Container, \
865 template <typename...> \
868 struct rewrap<TemplateTypeList<Container>, List<elems...>> { \
869 using type = TypeList<Container<elems...>>; \
871 template <template <typename...> class Container, \
872 template <typename...> \
875 typename... Elements> \
876 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { \
877 using type = typename append< \
878 TypeList<Container<Elems...>>, \
879 typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; \
882 template <template <typename...> class Final, \
883 template <typename...> \
884 class... Containers, \
886 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { \
887 using type = typename append< \
889 typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; \
891 template <template <typename...> class Final, \
892 template <typename...> \
895 struct convert<Final, List<Ts...>> { \
896 using type = typename append<Final<>, TypeList<Ts>...>::type; \
899 #define INTERNAL_CATCH_NTTP_1(signature, ...) \
900 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp {}; \
901 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
902 constexpr auto get_wrapper() noexcept->Nttp<__VA_ARGS__> { \
905 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> \
906 struct NttpTemplateTypeList {}; \
907 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Cs> \
908 constexpr auto get_wrapper() noexcept->NttpTemplateTypeList<Cs...> { \
912 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
913 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
915 INTERNAL_CATCH_REMOVE_PARENS(signature)> \
916 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { \
917 using type = TypeList<Container<__VA_ARGS__>>; \
919 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
920 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
922 INTERNAL_CATCH_REMOVE_PARENS(signature), \
923 typename... Elements> \
924 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { \
925 using type = typename append< \
926 TypeList<Container<__VA_ARGS__>>, \
927 typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; \
929 template <template <typename...> class Final, \
930 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
931 class... Containers, \
933 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { \
934 using type = typename append< \
936 typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; \
939 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
940 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature) \
941 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
942 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...) \
943 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
945 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
946 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature) \
947 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
948 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...) \
949 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
951 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature) \
952 template <typename Type> void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags) { \
953 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Type>), \
954 CATCH_INTERNAL_LINEINFO, \
955 Catch::StringRef(), \
959 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...) \
960 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
961 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags) { \
962 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), \
963 CATCH_INTERNAL_LINEINFO, \
964 Catch::StringRef(), \
968 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...) \
969 template <typename Type> \
970 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
971 Catch::AutoReg(Catch::makeTestInvoker(&TestName<Type>::test), \
972 CATCH_INTERNAL_LINEINFO, \
977 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...) \
978 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
979 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
980 Catch::AutoReg(Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), \
981 CATCH_INTERNAL_LINEINFO, \
986 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
987 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature) \
988 template <typename TestType> \
989 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
993 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...) \
994 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
995 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
999 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
1000 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature) \
1001 template <typename TestType> \
1002 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
1003 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...) \
1004 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
1005 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
1007 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1008 #define INTERNAL_CATCH_NTTP_0
1009 #define INTERNAL_CATCH_NTTP_GEN(...) \
1010 INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \
1011 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1012 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1013 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1014 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1015 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1016 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1017 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1018 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1019 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1020 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1021 INTERNAL_CATCH_NTTP_0)
1022 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
1023 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1025 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1026 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1027 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1028 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1029 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1030 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1031 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1032 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1033 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1034 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1035 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0) \
1036 (TestName, __VA_ARGS__)
1037 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1038 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1040 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1041 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1042 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1043 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1044 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1045 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1046 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1047 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1048 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1049 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1050 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0) \
1051 (TestName, ClassName, __VA_ARGS__)
1052 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1053 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1055 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1056 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1057 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1058 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1059 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1060 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1061 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1062 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1063 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1064 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1065 INTERNAL_CATCH_NTTP_REGISTER_METHOD0) \
1066 (TestName, __VA_ARGS__)
1067 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1068 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1070 INTERNAL_CATCH_NTTP_REGISTER, \
1071 INTERNAL_CATCH_NTTP_REGISTER, \
1072 INTERNAL_CATCH_NTTP_REGISTER, \
1073 INTERNAL_CATCH_NTTP_REGISTER, \
1074 INTERNAL_CATCH_NTTP_REGISTER, \
1075 INTERNAL_CATCH_NTTP_REGISTER, \
1076 INTERNAL_CATCH_NTTP_REGISTER, \
1077 INTERNAL_CATCH_NTTP_REGISTER, \
1078 INTERNAL_CATCH_NTTP_REGISTER, \
1079 INTERNAL_CATCH_NTTP_REGISTER0, \
1080 INTERNAL_CATCH_NTTP_REGISTER0) \
1081 (TestFunc, __VA_ARGS__)
1082 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1083 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1085 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1086 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1087 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1088 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1089 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1090 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1091 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1092 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1093 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1094 INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1095 INTERNAL_CATCH_DEFINE_SIG_TEST0) \
1096 (TestName, __VA_ARGS__)
1097 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1098 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1100 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1101 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1102 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1103 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1104 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1105 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1106 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1107 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1108 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1109 INTERNAL_CATCH_DECLARE_SIG_TEST1, \
1110 INTERNAL_CATCH_DECLARE_SIG_TEST0) \
1111 (TestName, __VA_ARGS__)
1112 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1113 INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \
1114 INTERNAL_CATCH_REMOVE_PARENS_11_ARG, \
1115 INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1116 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, \
1117 INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1118 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, \
1119 INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1120 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, \
1121 INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1122 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, \
1123 INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1124 INTERNAL_CATCH_REMOVE_PARENS_1_ARG) \
1127 #define INTERNAL_CATCH_NTTP_0(signature)
1128 #define INTERNAL_CATCH_NTTP_GEN(...) \
1129 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \
1130 INTERNAL_CATCH_NTTP_1, \
1131 INTERNAL_CATCH_NTTP_1, \
1132 INTERNAL_CATCH_NTTP_1, \
1133 INTERNAL_CATCH_NTTP_1, \
1134 INTERNAL_CATCH_NTTP_1, \
1135 INTERNAL_CATCH_NTTP_1, \
1136 INTERNAL_CATCH_NTTP_1, \
1137 INTERNAL_CATCH_NTTP_1, \
1138 INTERNAL_CATCH_NTTP_1, \
1139 INTERNAL_CATCH_NTTP_1, \
1140 INTERNAL_CATCH_NTTP_0)(__VA_ARGS__))
1141 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
1142 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1145 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1146 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1147 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1148 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1149 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1150 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1151 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1152 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1153 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1154 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1155 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
1156 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1157 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1160 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1161 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1162 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1163 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1164 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1165 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1166 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1167 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1168 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1169 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1170 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
1171 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1172 INTERNAL_CATCH_EXPAND_VARGS( \
1173 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1175 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1176 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1177 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1178 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1179 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1180 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1181 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1182 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1183 INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1184 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1185 INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
1186 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1187 INTERNAL_CATCH_EXPAND_VARGS( \
1188 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1190 INTERNAL_CATCH_NTTP_REGISTER, \
1191 INTERNAL_CATCH_NTTP_REGISTER, \
1192 INTERNAL_CATCH_NTTP_REGISTER, \
1193 INTERNAL_CATCH_NTTP_REGISTER, \
1194 INTERNAL_CATCH_NTTP_REGISTER, \
1195 INTERNAL_CATCH_NTTP_REGISTER, \
1196 INTERNAL_CATCH_NTTP_REGISTER, \
1197 INTERNAL_CATCH_NTTP_REGISTER, \
1198 INTERNAL_CATCH_NTTP_REGISTER, \
1199 INTERNAL_CATCH_NTTP_REGISTER0, \
1200 INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
1201 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1202 INTERNAL_CATCH_EXPAND_VARGS( \
1203 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1205 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1206 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1207 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1208 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1209 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1210 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1211 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1212 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1213 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1214 INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1215 INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
1216 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1217 INTERNAL_CATCH_EXPAND_VARGS( \
1218 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", \
1220 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1221 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1222 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1223 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1224 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1225 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1226 INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1227 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1228 INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1229 INTERNAL_CATCH_DECLARE_SIG_TEST1, \
1230 INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
1231 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1232 INTERNAL_CATCH_EXPAND_VARGS( \
1233 INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, \
1234 INTERNAL_CATCH_REMOVE_PARENS_11_ARG, \
1235 INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1236 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, \
1237 INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1238 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, \
1239 INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1240 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, \
1241 INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1242 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, \
1243 INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1244 INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
1247 // end catch_preprocessor.hpp
1248 // start catch_meta.hpp
1250 #include <type_traits>
1253 template <typename T> struct always_false : std::false_type {};
1255 template <typename> struct true_given : std::true_type {};
1256 struct is_callable_tester {
1257 template <typename Fun, typename... Args>
1258 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
1259 template <typename...> std::false_type static test(...);
1262 template <typename T> struct is_callable;
1264 template <typename Fun, typename... Args>
1265 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
1267 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
1268 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
1269 // replaced with std::invoke_result here.
1270 template <typename Func, typename... U>
1271 using FunctionReturnType =
1272 std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
1274 // Keep ::type here because we still support C++11
1275 template <typename Func, typename... U>
1276 using FunctionReturnType = typename std::remove_reference<
1277 typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
1280 } // namespace Catch
1286 // end catch_meta.hpp
1289 template <typename C> class TestInvokerAsMethod : public ITestInvoker {
1290 void (C::*m_testAsMethod)();
1293 TestInvokerAsMethod(void (C::*testAsMethod)()) noexcept : m_testAsMethod(testAsMethod) {}
1295 void invoke() const override {
1297 (obj.*m_testAsMethod)();
1301 auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker*;
1303 template <typename C>
1304 auto makeTestInvoker(void (C::*testAsMethod)()) noexcept -> ITestInvoker* {
1305 return new (std::nothrow) TestInvokerAsMethod<C>(testAsMethod);
1308 struct NameAndTags {
1309 NameAndTags(StringRef const& name_ = StringRef(),
1310 StringRef const& tags_ = StringRef()) noexcept;
1315 struct AutoReg : NonCopyable {
1316 AutoReg(ITestInvoker* invoker,
1317 SourceLineInfo const& lineInfo,
1318 StringRef const& classOrMethod,
1319 NameAndTags const& nameAndTags) noexcept;
1323 } // end namespace Catch
1325 #if defined(CATCH_CONFIG_DISABLE)
1326 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(TestName, ...) static void TestName()
1327 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(TestName, ClassName, ...) \
1329 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1333 void TestName::test()
1334 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1335 TestName, TestFunc, Name, Tags, Signature, ...) \
1336 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1337 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1338 TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
1340 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1341 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD( \
1342 TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1345 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1347 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1348 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1349 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1350 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1351 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____), \
1354 typename TestType, \
1357 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1358 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1359 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1360 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____), \
1363 typename TestType, \
1367 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1368 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1369 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_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____), \
1377 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1378 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1379 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1380 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____), \
1387 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1388 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1389 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1390 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____), \
1391 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1398 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1399 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1400 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____), \
1401 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1409 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1410 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( \
1411 ClassName, Name, Tags, Signature, ...) \
1412 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1413 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____), \
1414 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1421 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( \
1422 ClassName, Name, Tags, Signature, ...) \
1423 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1424 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____), \
1425 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1434 ///////////////////////////////////////////////////////////////////////////////
1435 #define INTERNAL_CATCH_TESTCASE2(TestName, ...) \
1436 static void TestName(); \
1437 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1438 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1441 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName), \
1442 CATCH_INTERNAL_LINEINFO, \
1443 Catch::StringRef(), \
1444 Catch::NameAndTags{__VA_ARGS__}); \
1446 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1447 static void TestName()
1448 #define INTERNAL_CATCH_TESTCASE(...) \
1449 INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), __VA_ARGS__)
1451 ///////////////////////////////////////////////////////////////////////////////
1452 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \
1453 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1454 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1457 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&QualifiedMethod), \
1458 CATCH_INTERNAL_LINEINFO, \
1459 "&" #QualifiedMethod, \
1460 Catch::NameAndTags{__VA_ARGS__}); \
1462 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1464 ///////////////////////////////////////////////////////////////////////////////
1465 #define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...) \
1466 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1467 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1469 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1472 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \
1473 Catch::makeTestInvoker(&TestName::test), \
1474 CATCH_INTERNAL_LINEINFO, \
1476 Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \
1478 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1479 void TestName::test()
1480 #define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \
1481 INTERNAL_CATCH_TEST_CASE_METHOD2( \
1482 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), ClassName, __VA_ARGS__)
1484 ///////////////////////////////////////////////////////////////////////////////
1485 #define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \
1486 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1487 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1488 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \
1489 Catch::makeTestInvoker(Function), \
1490 CATCH_INTERNAL_LINEINFO, \
1491 Catch::StringRef(), \
1492 Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \
1493 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1495 ///////////////////////////////////////////////////////////////////////////////
1496 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...) \
1497 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1498 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1499 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1500 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1501 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1503 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1504 INTERNAL_CATCH_TYPE_GEN \
1505 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1506 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1507 template <typename... Types> struct TestName { \
1510 constexpr char const* tmpl_types[] = { \
1511 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1512 using expander = int[]; \
1514 (reg_test(Types{}, \
1515 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), \
1517 index++)...}; /* NOLINT */ \
1520 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1521 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1526 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1527 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1529 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1530 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1531 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1532 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1533 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____), \
1536 typename TestType, \
1539 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1540 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1541 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1542 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____), \
1545 typename TestType, \
1549 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1550 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1551 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1552 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1553 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____), \
1559 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1560 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1561 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1562 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____), \
1569 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1570 TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1571 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1572 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1573 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1574 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1575 template <typename TestType> static void TestFuncName(); \
1577 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1578 INTERNAL_CATCH_TYPE_GEN \
1579 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1580 template <typename... Types> struct TestName { \
1581 void reg_tests() { \
1583 using expander = int[]; \
1584 constexpr char const* tmpl_types[] = { \
1585 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1586 INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1587 constexpr char const* types_list[] = { \
1588 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1589 INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1590 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1592 (Catch::AutoReg(Catch::makeTestInvoker(&TestFuncName<Types>), \
1593 CATCH_INTERNAL_LINEINFO, \
1594 Catch::StringRef(), \
1595 Catch::NameAndTags{ \
1597 std::string(tmpl_types[index / num_types]) + "<" + \
1598 std::string(types_list[index % num_types]) + ">", \
1600 index++)...}; /* NOLINT */ \
1603 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1604 using TestInit = typename create< \
1606 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1607 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1608 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1615 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1616 template <typename TestType> static void TestFuncName()
1618 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1619 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1620 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1621 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1622 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____), \
1628 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1629 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
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____), \
1638 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1639 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1640 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1641 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1642 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____), \
1648 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1649 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1650 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1651 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____), \
1658 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList) \
1659 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1660 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1661 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1662 template <typename TestType> static void TestFunc(); \
1664 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1665 INTERNAL_CATCH_TYPE_GEN \
1666 template <typename... Types> struct TestName { \
1667 void reg_tests() { \
1669 using expander = int[]; \
1671 (Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Types>), \
1672 CATCH_INTERNAL_LINEINFO, \
1673 Catch::StringRef(), \
1674 Catch::NameAndTags{ \
1676 std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1677 " - " + std::to_string(index), \
1679 index++)...}; /* NOLINT */ \
1682 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1683 using TestInit = typename convert<TestName, TmplList>::type; \
1690 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1691 template <typename TestType> static void TestFunc()
1693 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1694 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( \
1695 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1696 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____), \
1701 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1702 TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
1703 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1704 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1705 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1706 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1708 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1709 INTERNAL_CATCH_TYPE_GEN \
1710 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1711 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD( \
1712 TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1713 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1714 template <typename... Types> struct TestNameClass { \
1717 constexpr char const* tmpl_types[] = { \
1718 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1719 using expander = int[]; \
1721 (reg_test(Types{}, \
1723 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), \
1725 index++)...}; /* NOLINT */ \
1728 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1729 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1734 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1735 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1737 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1738 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1739 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1740 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____), \
1741 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1748 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1749 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1750 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____), \
1751 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1759 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1760 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1761 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1762 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____), \
1763 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1770 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1771 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1772 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____), \
1773 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1781 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1782 TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList) \
1783 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1784 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1785 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1786 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1787 template <typename TestType> \
1788 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \
1792 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) { \
1793 INTERNAL_CATCH_TYPE_GEN \
1794 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1795 template <typename... Types> struct TestNameClass { \
1796 void reg_tests() { \
1798 using expander = int[]; \
1799 constexpr char const* tmpl_types[] = { \
1800 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1801 INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1802 constexpr char const* types_list[] = { \
1803 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1804 INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1805 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1807 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1808 CATCH_INTERNAL_LINEINFO, \
1810 Catch::NameAndTags{ \
1812 std::string(tmpl_types[index / num_types]) + "<" + \
1813 std::string(types_list[index % num_types]) + ">", \
1815 index++)...}; /* NOLINT */ \
1818 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1819 using TestInit = typename create< \
1821 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1822 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1823 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1830 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1831 template <typename TestType> void TestName<TestType>::test()
1833 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1834 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1835 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1836 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1837 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____), \
1844 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1845 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1846 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1847 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____), \
1855 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1856 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( \
1857 ClassName, Name, Tags, Signature, ...) \
1858 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1859 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1860 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____), \
1867 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( \
1868 ClassName, Name, Tags, Signature, ...) \
1869 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1870 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1871 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____), \
1879 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \
1880 TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1881 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1882 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1883 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1884 template <typename TestType> \
1885 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \
1889 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1890 INTERNAL_CATCH_TYPE_GEN \
1891 template <typename... Types> struct TestNameClass { \
1892 void reg_tests() { \
1894 using expander = int[]; \
1896 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1897 CATCH_INTERNAL_LINEINFO, \
1899 Catch::NameAndTags{ \
1901 std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1902 " - " + std::to_string(index), \
1904 index++)...}; /* NOLINT */ \
1907 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1908 using TestInit = typename convert<TestNameClass, TmplList>::type; \
1915 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1916 template <typename TestType> void TestName<TestType>::test()
1918 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1919 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \
1920 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1921 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____), \
1927 // end catch_test_registry.h
1928 // start catch_capture.hpp
1930 // start catch_assertionhandler.h
1932 // start catch_assertioninfo.h
1934 // start catch_result_type.h
1938 // ResultWas::OfType enum
1948 ExpressionFailed = FailureBit | 1,
1949 ExplicitFailure = FailureBit | 2,
1951 Exception = 0x100 | FailureBit,
1953 ThrewException = Exception | 1,
1954 DidntThrowException = Exception | 2,
1956 FatalErrorCondition = 0x200 | FailureBit
1961 bool isOk(ResultWas::OfType resultType);
1962 bool isJustInfo(int flags);
1964 // ResultDisposition::Flags enum
1965 struct ResultDisposition {
1969 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1970 FalseTest = 0x04, // Prefix expression with !
1971 SuppressFail = 0x08 // Failures are reported but do not fail the test
1975 ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
1977 bool shouldContinueOnFailure(int flags);
1978 inline bool isFalseTest(int flags) { return (flags & ResultDisposition::FalseTest) != 0; }
1979 bool shouldSuppressFailure(int flags);
1981 } // end namespace Catch
1983 // end catch_result_type.h
1986 struct AssertionInfo {
1987 StringRef macroName;
1988 SourceLineInfo lineInfo;
1989 StringRef capturedExpression;
1990 ResultDisposition::Flags resultDisposition;
1992 // We want to delete this constructor but a compiler bug in 4.8 means
1993 // the struct is then treated as non-aggregate
1994 // AssertionInfo() = delete;
1997 } // end namespace Catch
1999 // end catch_assertioninfo.h
2000 // start catch_decomposer.h
2002 // start catch_tostring.h
2006 #include <type_traits>
2008 // start catch_stream.h
2016 std::ostream& cout();
2017 std::ostream& cerr();
2018 std::ostream& clog();
2024 virtual std::ostream& stream() const = 0;
2027 auto makeStream(StringRef const& filename) -> IStream const*;
2029 class ReusableStringStream : NonCopyable {
2030 std::size_t m_index;
2031 std::ostream* m_oss;
2034 ReusableStringStream();
2035 ~ReusableStringStream();
2037 auto str() const -> std::string;
2039 template <typename T> auto operator<<(T const& value) -> ReusableStringStream& {
2043 auto get() -> std::ostream& { return *m_oss; }
2045 } // namespace Catch
2047 // end catch_stream.h
2048 // start catch_interfaces_enum_values_registry.h
2057 std::vector<std::pair<int, StringRef>> m_values;
2061 StringRef lookup(int value) const;
2063 } // namespace Detail
2065 struct IMutableEnumValuesRegistry {
2066 virtual ~IMutableEnumValuesRegistry();
2068 virtual Detail::EnumInfo const&
2069 registerEnum(StringRef enumName, StringRef allEnums, std::vector<int> const& values) = 0;
2071 template <typename E>
2072 Detail::EnumInfo const&
2073 registerEnum(StringRef enumName, StringRef allEnums, std::initializer_list<E> values) {
2074 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
2075 std::vector<int> intValues;
2076 intValues.reserve(values.size());
2077 for (auto enumValue : values)
2078 intValues.push_back(static_cast<int>(enumValue));
2079 return registerEnum(enumName, allEnums, intValues);
2083 } // namespace Catch
2085 // end catch_interfaces_enum_values_registry.h
2087 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2088 #include <string_view>
2092 // start catch_objc_arc.hpp
2094 #import <Foundation/Foundation.h>
2096 #ifdef __has_feature
2097 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
2099 #define CATCH_ARC_ENABLED 0
2102 void arcSafeRelease(NSObject* obj);
2103 id performOptionalSelector(id obj, SEL sel);
2105 #if !CATCH_ARC_ENABLED
2106 inline void arcSafeRelease(NSObject* obj) { [obj release]; }
2107 inline id performOptionalSelector(id obj, SEL sel) {
2108 if ([obj respondsToSelector:sel])
2109 return [obj performSelector:sel];
2112 #define CATCH_UNSAFE_UNRETAINED
2113 #define CATCH_ARC_STRONG
2115 inline void arcSafeRelease(NSObject*) {}
2116 inline id performOptionalSelector(id obj, SEL sel) {
2118 #pragma clang diagnostic push
2119 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
2121 if ([obj respondsToSelector:sel])
2122 return [obj performSelector:sel];
2124 #pragma clang diagnostic pop
2128 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
2129 #define CATCH_ARC_STRONG __strong
2132 // end catch_objc_arc.hpp
2136 #pragma warning(push)
2137 #pragma warning(disable : 4180) // We attempt to stream a function (address) by const&,
2138 // which MSVC complains about but is harmless
2144 extern const std::string unprintableString;
2146 std::string rawMemoryToString(const void* object, std::size_t size);
2148 template <typename T> std::string rawMemoryToString(const T& object) {
2149 return rawMemoryToString(&object, sizeof(object));
2152 template <typename T> class IsStreamInsertable {
2153 template <typename Stream, typename U>
2154 static auto test(int)
2155 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
2157 template <typename, typename> static auto test(...) -> std::false_type;
2160 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
2163 template <typename E> std::string convertUnknownEnumToString(E e);
2165 template <typename T>
2166 typename std::enable_if<!std::is_enum<T>::value &&
2167 !std::is_base_of<std::exception, T>::value,
2169 convertUnstreamable(T const&) {
2170 return Detail::unprintableString;
2172 template <typename T>
2173 typename std::enable_if<!std::is_enum<T>::value &&
2174 std::is_base_of<std::exception, T>::value,
2176 convertUnstreamable(T const& ex) {
2180 template <typename T>
2181 typename std::enable_if<std::is_enum<T>::value, std::string>::type
2182 convertUnstreamable(T const& value) {
2183 return convertUnknownEnumToString(value);
2186 #if defined(_MANAGED)
2187 //! Convert a CLR string to a utf8 std::string
2188 template <typename T> std::string clrReferenceToString(T ^ ref) {
2190 return std::string("null");
2191 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
2192 cli::pin_ptr<System::Byte> p = &bytes[0];
2193 return std::string(reinterpret_cast<char const*>(p), bytes->Length);
2197 } // namespace Detail
2199 // If we decide for C++14, change these to enable_if_ts
2200 template <typename T, typename = void> struct StringMaker {
2201 template <typename Fake = T>
2202 static typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value,
2204 convert(const Fake& value) {
2205 ReusableStringStream rss;
2206 // NB: call using the function-like syntax to avoid ambiguity with
2207 // user-defined templated operator<< under clang.
2208 rss.operator<<(value);
2212 template <typename Fake = T>
2213 static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value,
2215 convert(const Fake& value) {
2216 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
2217 return Detail::convertUnstreamable(value);
2219 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
2226 // This function dispatches all stringification requests inside of
2227 // Catch. Should be preferably called fully qualified, like
2228 // ::Catch::Detail::stringify
2229 template <typename T> std::string stringify(const T& e) {
2230 return ::Catch::StringMaker<
2231 typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
2234 template <typename E> std::string convertUnknownEnumToString(E e) {
2235 return ::Catch::Detail::stringify(
2236 static_cast<typename std::underlying_type<E>::type>(e));
2239 #if defined(_MANAGED)
2240 template <typename T> std::string stringify(T ^ e) {
2241 return ::Catch::StringMaker<T ^>::convert(e);
2245 } // namespace Detail
2247 // Some predefined specializations
2249 template <> struct StringMaker<std::string> {
2250 static std::string convert(const std::string& str);
2253 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2254 template <> struct StringMaker<std::string_view> {
2255 static std::string convert(std::string_view str);
2259 template <> struct StringMaker<char const*> { static std::string convert(char const* str); };
2260 template <> struct StringMaker<char*> { static std::string convert(char* str); };
2262 #ifdef CATCH_CONFIG_WCHAR
2263 template <> struct StringMaker<std::wstring> {
2264 static std::string convert(const std::wstring& wstr);
2267 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2268 template <> struct StringMaker<std::wstring_view> {
2269 static std::string convert(std::wstring_view str);
2273 template <> struct StringMaker<wchar_t const*> {
2274 static std::string convert(wchar_t const* str);
2276 template <> struct StringMaker<wchar_t*> { static std::string convert(wchar_t* str); };
2279 // TBD: Should we use `strnlen` to ensure that we don't go out of the
2281 // while keeping string semantics?
2282 template <int SZ> struct StringMaker<char[SZ]> {
2283 static std::string convert(char const* str) {
2284 return ::Catch::Detail::stringify(std::string{str});
2287 template <int SZ> struct StringMaker<signed char[SZ]> {
2288 static std::string convert(signed char const* str) {
2289 return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const*>(str)});
2292 template <int SZ> struct StringMaker<unsigned char[SZ]> {
2293 static std::string convert(unsigned char const* str) {
2294 return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const*>(str)});
2298 #if defined(CATCH_CONFIG_CPP17_BYTE)
2299 template <> struct StringMaker<std::byte> { static std::string convert(std::byte value); };
2300 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
2301 template <> struct StringMaker<int> { static std::string convert(int value); };
2302 template <> struct StringMaker<long> { static std::string convert(long value); };
2303 template <> struct StringMaker<long long> { static std::string convert(long long value); };
2304 template <> struct StringMaker<unsigned int> {
2305 static std::string convert(unsigned int value);
2307 template <> struct StringMaker<unsigned long> {
2308 static std::string convert(unsigned long value);
2310 template <> struct StringMaker<unsigned long long> {
2311 static std::string convert(unsigned long long value);
2314 template <> struct StringMaker<bool> { static std::string convert(bool b); };
2316 template <> struct StringMaker<char> { static std::string convert(char c); };
2317 template <> struct StringMaker<signed char> { static std::string convert(signed char c); };
2318 template <> struct StringMaker<unsigned char> { static std::string convert(unsigned char c); };
2320 template <> struct StringMaker<std::nullptr_t> { static std::string convert(std::nullptr_t); };
2322 template <> struct StringMaker<float> {
2323 static std::string convert(float value);
2324 static int precision;
2327 template <> struct StringMaker<double> {
2328 static std::string convert(double value);
2329 static int precision;
2332 template <typename T> struct StringMaker<T*> {
2333 template <typename U> static std::string convert(U* p) {
2335 return ::Catch::Detail::rawMemoryToString(p);
2342 template <typename R, typename C> struct StringMaker<R C::*> {
2343 static std::string convert(R C::*p) {
2345 return ::Catch::Detail::rawMemoryToString(p);
2352 #if defined(_MANAGED)
2353 template <typename T> struct StringMaker<T ^> {
2354 static std::string convert(T ^ ref) { return ::Catch::Detail::clrReferenceToString(ref); }
2359 template <typename InputIterator, typename Sentinel = InputIterator>
2360 std::string rangeToString(InputIterator first, Sentinel last) {
2361 ReusableStringStream rss;
2363 if (first != last) {
2364 rss << ::Catch::Detail::stringify(*first);
2365 for (++first; first != last; ++first)
2366 rss << ", " << ::Catch::Detail::stringify(*first);
2371 } // namespace Detail
2374 template <> struct StringMaker<NSString*> {
2375 static std::string convert(NSString* nsstring) {
2378 return std::string("@") + [nsstring UTF8String];
2381 template <> struct StringMaker<NSObject*> {
2382 static std::string convert(NSObject* nsObject) {
2383 return ::Catch::Detail::stringify([nsObject description]);
2387 inline std::string stringify(NSString* nsstring) {
2388 return StringMaker<NSString*>::convert(nsstring);
2391 } // namespace Detail
2394 } // namespace Catch
2396 //////////////////////////////////////////////////////
2397 // Separate std-lib types stringification, so it can be selectively enabled
2398 // This means that we do not bring in
2400 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
2401 #define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2402 #define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2403 #define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2404 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2405 #define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2408 // Separate std::pair specialization
2409 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
2412 template <typename T1, typename T2> struct StringMaker<std::pair<T1, T2>> {
2413 static std::string convert(const std::pair<T1, T2>& pair) {
2414 ReusableStringStream rss;
2415 rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", "
2416 << ::Catch::Detail::stringify(pair.second) << " }";
2420 } // namespace Catch
2421 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2423 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
2426 template <typename T> struct StringMaker<std::optional<T>> {
2427 static std::string convert(const std::optional<T>& optional) {
2428 ReusableStringStream rss;
2429 if (optional.has_value()) {
2430 rss << ::Catch::Detail::stringify(*optional);
2437 } // namespace Catch
2438 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2440 // Separate std::tuple specialization
2441 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
2445 template <typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value)>
2446 struct TupleElementPrinter {
2447 static void print(const Tuple& tuple, std::ostream& os) {
2448 os << (N ? ", " : " ") << ::Catch::Detail::stringify(std::get<N>(tuple));
2449 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
2453 template <typename Tuple, std::size_t N> struct TupleElementPrinter<Tuple, N, false> {
2454 static void print(const Tuple&, std::ostream&) {}
2457 } // namespace Detail
2459 template <typename... Types> struct StringMaker<std::tuple<Types...>> {
2460 static std::string convert(const std::tuple<Types...>& tuple) {
2461 ReusableStringStream rss;
2463 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
2468 } // namespace Catch
2469 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2471 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
2474 template <> struct StringMaker<std::monostate> {
2475 static std::string convert(const std::monostate&) { return "{ }"; }
2478 template <typename... Elements> struct StringMaker<std::variant<Elements...>> {
2479 static std::string convert(const std::variant<Elements...>& variant) {
2480 if (variant.valueless_by_exception()) {
2481 return "{valueless variant}";
2484 [](const auto& value) { return ::Catch::Detail::stringify(value); }, variant);
2488 } // namespace Catch
2489 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2492 // Import begin/ end from std here
2497 template <typename...> struct void_type { using type = void; };
2499 template <typename T, typename = void> struct is_range_impl : std::false_type {};
2501 template <typename T>
2502 struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type>
2503 : std::true_type {};
2504 } // namespace detail
2506 template <typename T> struct is_range : detail::is_range_impl<T> {};
2508 #if defined(_MANAGED) // Managed types are never ranges
2509 template <typename T> struct is_range<T ^> { static const bool value = false; };
2512 template <typename Range> std::string rangeToString(Range const& range) {
2513 return ::Catch::Detail::rangeToString(begin(range), end(range));
2516 // Handle vector<bool> specially
2517 template <typename Allocator> std::string rangeToString(std::vector<bool, Allocator> const& v) {
2518 ReusableStringStream rss;
2526 rss << ::Catch::Detail::stringify(b);
2532 template <typename R>
2535 typename std::enable_if<is_range<R>::value &&
2536 !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2537 static std::string convert(R const& range) { return rangeToString(range); }
2540 template <typename T, int SZ> struct StringMaker<T[SZ]> {
2541 static std::string convert(T const (&arr)[SZ]) { return rangeToString(arr); }
2544 } // namespace Catch
2546 // Separate std::chrono::duration specialization
2547 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2554 template <class Ratio> struct ratio_string { static std::string symbol(); };
2556 template <class Ratio> std::string ratio_string<Ratio>::symbol() {
2557 Catch::ReusableStringStream rss;
2558 rss << '[' << Ratio::num << '/' << Ratio::den << ']';
2561 template <> struct ratio_string<std::atto> { static std::string symbol(); };
2562 template <> struct ratio_string<std::femto> { static std::string symbol(); };
2563 template <> struct ratio_string<std::pico> { static std::string symbol(); };
2564 template <> struct ratio_string<std::nano> { static std::string symbol(); };
2565 template <> struct ratio_string<std::micro> { static std::string symbol(); };
2566 template <> struct ratio_string<std::milli> { static std::string symbol(); };
2569 // std::chrono::duration specializations
2570 template <typename Value, typename Ratio>
2571 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2572 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2573 ReusableStringStream rss;
2574 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2578 template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2579 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2580 ReusableStringStream rss;
2581 rss << duration.count() << " s";
2585 template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2586 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2587 ReusableStringStream rss;
2588 rss << duration.count() << " m";
2592 template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2593 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2594 ReusableStringStream rss;
2595 rss << duration.count() << " h";
2601 // std::chrono::time_point specialization
2602 // Generic time_point cannot be specialized, only
2603 // std::chrono::time_point<system_clock>
2604 template <typename Clock, typename Duration>
2605 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2606 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2607 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2610 // std::chrono::time_point<system_clock> specialization
2611 template <typename Duration>
2612 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2614 convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2615 auto converted = std::chrono::system_clock::to_time_t(time_point);
2618 std::tm timeInfo = {};
2619 gmtime_s(&timeInfo, &converted);
2621 std::tm* timeInfo = std::gmtime(&converted);
2624 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2625 char timeStamp[timeStampSize];
2626 const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
2629 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2631 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2633 return std::string(timeStamp);
2636 } // namespace Catch
2637 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2639 #define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \
2641 template <> struct StringMaker<enumName> { \
2642 static std::string convert(enumName value) { \
2643 static const auto& enumInfo = \
2644 ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( \
2645 #enumName, #__VA_ARGS__, {__VA_ARGS__}); \
2646 return static_cast<std::string>(enumInfo.lookup(static_cast<int>(value))); \
2651 #define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM(enumName, __VA_ARGS__)
2654 #pragma warning(pop)
2657 // end catch_tostring.h
2661 #pragma warning(push)
2662 #pragma warning(disable : 4389) // '==' : signed/unsigned mismatch
2663 #pragma warning(disable : 4018) // more "signed/unsigned mismatch"
2664 #pragma warning(disable : 4312) // Converting int to T* using reinterpret_cast
2665 // (issue on x64 platform)
2666 #pragma warning(disable : 4180) // qualifier applied to function type has no meaning
2667 #pragma warning(disable : 4800) // Forcing result to true or false
2672 struct ITransientExpression {
2673 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2674 auto getResult() const -> bool { return m_result; }
2675 virtual void streamReconstructedExpression(std::ostream& os) const = 0;
2677 ITransientExpression(bool isBinaryExpression, bool result) :
2678 m_isBinaryExpression(isBinaryExpression), m_result(result) {}
2680 // We don't actually need a virtual destructor, but many static
2681 // analysers complain if it's not here :-(
2682 virtual ~ITransientExpression();
2684 bool m_isBinaryExpression;
2688 void formatReconstructedExpression(std::ostream& os,
2689 std::string const& lhs,
2691 std::string const& rhs);
2693 template <typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression {
2698 void streamReconstructedExpression(std::ostream& os) const override {
2699 formatReconstructedExpression(
2700 os, Catch::Detail::stringify(m_lhs), m_op, Catch::Detail::stringify(m_rhs));
2704 BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs) :
2705 ITransientExpression{true, comparisonResult}, m_lhs(lhs), m_op(op), m_rhs(rhs) {}
2707 template <typename T> auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2708 static_assert(always_false<T>::value,
2709 "chained comparisons are not supported inside assertions, "
2710 "wrap the expression inside parentheses, or decompose it");
2713 template <typename T> auto operator||(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2714 static_assert(always_false<T>::value,
2715 "chained comparisons are not supported inside assertions, "
2716 "wrap the expression inside parentheses, or decompose it");
2719 template <typename T> auto operator==(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2720 static_assert(always_false<T>::value,
2721 "chained comparisons are not supported inside assertions, "
2722 "wrap the expression inside parentheses, or decompose it");
2725 template <typename T> auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2726 static_assert(always_false<T>::value,
2727 "chained comparisons are not supported inside assertions, "
2728 "wrap the expression inside parentheses, or decompose it");
2731 template <typename T> auto operator>(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2732 static_assert(always_false<T>::value,
2733 "chained comparisons are not supported inside assertions, "
2734 "wrap the expression inside parentheses, or decompose it");
2737 template <typename T> auto operator<(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2738 static_assert(always_false<T>::value,
2739 "chained comparisons are not supported inside assertions, "
2740 "wrap the expression inside parentheses, or decompose it");
2743 template <typename T> auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2744 static_assert(always_false<T>::value,
2745 "chained comparisons are not supported inside assertions, "
2746 "wrap the expression inside parentheses, or decompose it");
2749 template <typename T> auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2750 static_assert(always_false<T>::value,
2751 "chained comparisons are not supported inside assertions, "
2752 "wrap the expression inside parentheses, or decompose it");
2756 template <typename LhsT> class UnaryExpr : public ITransientExpression {
2759 void streamReconstructedExpression(std::ostream& os) const override {
2760 os << Catch::Detail::stringify(m_lhs);
2764 explicit UnaryExpr(LhsT lhs) :
2765 ITransientExpression{false, static_cast<bool>(lhs)}, m_lhs(lhs) {}
2768 // Specialised comparison functions to handle equality comparisons between
2769 // ints and pointers (NULL deduces as an int)
2770 template <typename LhsT, typename RhsT>
2771 auto compareEqual(LhsT const& lhs, RhsT const& rhs) -> bool {
2772 return static_cast<bool>(lhs == rhs);
2774 template <typename T> auto compareEqual(T* const& lhs, int rhs) -> bool {
2775 return lhs == reinterpret_cast<void const*>(rhs);
2777 template <typename T> auto compareEqual(T* const& lhs, long rhs) -> bool {
2778 return lhs == reinterpret_cast<void const*>(rhs);
2780 template <typename T> auto compareEqual(int lhs, T* const& rhs) -> bool {
2781 return reinterpret_cast<void const*>(lhs) == rhs;
2783 template <typename T> auto compareEqual(long lhs, T* const& rhs) -> bool {
2784 return reinterpret_cast<void const*>(lhs) == rhs;
2787 template <typename LhsT, typename RhsT>
2788 auto compareNotEqual(LhsT const& lhs, RhsT&& rhs) -> bool {
2789 return static_cast<bool>(lhs != rhs);
2791 template <typename T> auto compareNotEqual(T* const& lhs, int rhs) -> bool {
2792 return lhs != reinterpret_cast<void const*>(rhs);
2794 template <typename T> auto compareNotEqual(T* const& lhs, long rhs) -> bool {
2795 return lhs != reinterpret_cast<void const*>(rhs);
2797 template <typename T> auto compareNotEqual(int lhs, T* const& rhs) -> bool {
2798 return reinterpret_cast<void const*>(lhs) != rhs;
2800 template <typename T> auto compareNotEqual(long lhs, T* const& rhs) -> bool {
2801 return reinterpret_cast<void const*>(lhs) != rhs;
2804 template <typename LhsT> class ExprLhs {
2808 explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {}
2810 template <typename RhsT>
2811 auto operator==(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2812 return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs};
2814 auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const {
2815 return {m_lhs == rhs, m_lhs, "==", rhs};
2818 template <typename RhsT>
2819 auto operator!=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2820 return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs};
2822 auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const {
2823 return {m_lhs != rhs, m_lhs, "!=", rhs};
2826 template <typename RhsT>
2827 auto operator>(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2828 return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs};
2830 template <typename RhsT>
2831 auto operator<(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2832 return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs};
2834 template <typename RhsT>
2835 auto operator>=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2836 return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs};
2838 template <typename RhsT>
2839 auto operator<=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2840 return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs};
2842 template <typename RhsT>
2843 auto operator|(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2844 return {static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs};
2846 template <typename RhsT>
2847 auto operator&(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2848 return {static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs};
2850 template <typename RhsT>
2851 auto operator^(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2852 return {static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs};
2855 template <typename RhsT>
2856 auto operator&&(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const {
2857 static_assert(always_false<RhsT>::value,
2858 "operator&& is not supported inside assertions, "
2859 "wrap the expression inside parentheses, or decompose it");
2862 template <typename RhsT>
2863 auto operator||(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const {
2864 static_assert(always_false<RhsT>::value,
2865 "operator|| is not supported inside assertions, "
2866 "wrap the expression inside parentheses, or decompose it");
2869 auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{m_lhs}; }
2872 void handleExpression(ITransientExpression const& expr);
2874 template <typename T> void handleExpression(ExprLhs<T> const& expr) {
2875 handleExpression(expr.makeUnaryExpr());
2879 template <typename T> auto operator<=(T const& lhs) -> ExprLhs<T const&> {
2880 return ExprLhs<T const&>{lhs};
2883 auto operator<=(bool value) -> ExprLhs<bool> { return ExprLhs<bool>{value}; }
2886 } // end namespace Catch
2889 #pragma warning(pop)
2892 // end catch_decomposer.h
2893 // start catch_interfaces_capture.h
2900 class AssertionResult;
2901 struct AssertionInfo;
2903 struct SectionEndInfo;
2905 struct MessageBuilder;
2907 struct AssertionReaction;
2908 struct SourceLineInfo;
2910 struct ITransientExpression;
2911 struct IGeneratorTracker;
2913 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2914 struct BenchmarkInfo;
2915 template <typename Duration = std::chrono::duration<double, std::nano>> struct BenchmarkStats;
2916 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2918 struct IResultCapture {
2920 virtual ~IResultCapture();
2922 virtual bool sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) = 0;
2923 virtual void sectionEnded(SectionEndInfo const& endInfo) = 0;
2924 virtual void sectionEndedEarly(SectionEndInfo const& endInfo) = 0;
2926 virtual auto acquireGeneratorTracker(StringRef generatorName,
2927 SourceLineInfo const& lineInfo)
2928 -> IGeneratorTracker& = 0;
2930 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2931 virtual void benchmarkPreparing(std::string const& name) = 0;
2932 virtual void benchmarkStarting(BenchmarkInfo const& info) = 0;
2933 virtual void benchmarkEnded(BenchmarkStats<> const& stats) = 0;
2934 virtual void benchmarkFailed(std::string const& error) = 0;
2935 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2937 virtual void pushScopedMessage(MessageInfo const& message) = 0;
2938 virtual void popScopedMessage(MessageInfo const& message) = 0;
2940 virtual void emplaceUnscopedMessage(MessageBuilder const& builder) = 0;
2942 virtual void handleFatalErrorCondition(StringRef message) = 0;
2944 virtual void handleExpr(AssertionInfo const& info,
2945 ITransientExpression const& expr,
2946 AssertionReaction& reaction) = 0;
2947 virtual void handleMessage(AssertionInfo const& info,
2948 ResultWas::OfType resultType,
2949 StringRef const& message,
2950 AssertionReaction& reaction) = 0;
2951 virtual void handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
2952 AssertionReaction& reaction) = 0;
2953 virtual void handleUnexpectedInflightException(AssertionInfo const& info,
2954 std::string const& message,
2955 AssertionReaction& reaction) = 0;
2956 virtual void handleIncomplete(AssertionInfo const& info) = 0;
2957 virtual void handleNonExpr(AssertionInfo const& info,
2958 ResultWas::OfType resultType,
2959 AssertionReaction& reaction) = 0;
2961 virtual bool lastAssertionPassed() = 0;
2962 virtual void assertionPassed() = 0;
2964 // Deprecated, do not use:
2965 virtual std::string getCurrentTestName() const = 0;
2966 virtual const AssertionResult* getLastResult() const = 0;
2967 virtual void exceptionEarlyReported() = 0;
2970 IResultCapture& getResultCapture();
2971 } // namespace Catch
2973 // end catch_interfaces_capture.h
2976 struct TestFailureException {};
2977 struct AssertionResultData;
2978 struct IResultCapture;
2981 class LazyExpression {
2982 friend class AssertionHandler;
2983 friend struct AssertionStats;
2984 friend class RunContext;
2986 ITransientExpression const* m_transientExpression = nullptr;
2990 LazyExpression(bool isNegated);
2991 LazyExpression(LazyExpression const& other);
2992 LazyExpression& operator=(LazyExpression const&) = delete;
2994 explicit operator bool() const;
2996 friend auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream&;
2999 struct AssertionReaction {
3000 bool shouldDebugBreak = false;
3001 bool shouldThrow = false;
3004 class AssertionHandler {
3005 AssertionInfo m_assertionInfo;
3006 AssertionReaction m_reaction;
3007 bool m_completed = false;
3008 IResultCapture& m_resultCapture;
3011 AssertionHandler(StringRef const& macroName,
3012 SourceLineInfo const& lineInfo,
3013 StringRef capturedExpression,
3014 ResultDisposition::Flags resultDisposition);
3015 ~AssertionHandler() {
3017 m_resultCapture.handleIncomplete(m_assertionInfo);
3021 template <typename T> void handleExpr(ExprLhs<T> const& expr) {
3022 handleExpr(expr.makeUnaryExpr());
3024 void handleExpr(ITransientExpression const& expr);
3026 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
3028 void handleExceptionThrownAsExpected();
3029 void handleUnexpectedExceptionNotThrown();
3030 void handleExceptionNotThrownAsExpected();
3031 void handleThrowingCallSkipped();
3032 void handleUnexpectedInflightException();
3035 void setCompleted();
3038 auto allowThrows() const -> bool;
3041 void handleExceptionMatchExpr(AssertionHandler& handler,
3042 std::string const& str,
3043 StringRef const& matcherString);
3045 } // namespace Catch
3047 // end catch_assertionhandler.h
3048 // start catch_message.h
3055 struct MessageInfo {
3056 MessageInfo(StringRef const& _macroName,
3057 SourceLineInfo const& _lineInfo,
3058 ResultWas::OfType _type);
3060 StringRef macroName;
3061 std::string message;
3062 SourceLineInfo lineInfo;
3063 ResultWas::OfType type;
3064 unsigned int sequence;
3066 bool operator==(MessageInfo const& other) const;
3067 bool operator<(MessageInfo const& other) const;
3070 static unsigned int globalCount;
3073 struct MessageStream {
3075 template <typename T> MessageStream& operator<<(T const& value) {
3080 ReusableStringStream m_stream;
3083 struct MessageBuilder : MessageStream {
3084 MessageBuilder(StringRef const& macroName,
3085 SourceLineInfo const& lineInfo,
3086 ResultWas::OfType type);
3088 template <typename T> MessageBuilder& operator<<(T const& value) {
3096 class ScopedMessage {
3098 explicit ScopedMessage(MessageBuilder const& builder);
3099 ScopedMessage(ScopedMessage& duplicate) = delete;
3100 ScopedMessage(ScopedMessage&& old);
3108 std::vector<MessageInfo> m_messages;
3109 IResultCapture& m_resultCapture = getResultCapture();
3110 size_t m_captured = 0;
3113 Capturer(StringRef macroName,
3114 SourceLineInfo const& lineInfo,
3115 ResultWas::OfType resultType,
3119 void captureValue(size_t index, std::string const& value);
3121 template <typename T> void captureValues(size_t index, T const& value) {
3122 captureValue(index, Catch::Detail::stringify(value));
3125 template <typename T, typename... Ts>
3126 void captureValues(size_t index, T const& value, Ts const&... values) {
3127 captureValue(index, Catch::Detail::stringify(value));
3128 captureValues(index + 1, values...);
3132 } // end namespace Catch
3134 // end catch_message.h
3135 #if !defined(CATCH_CONFIG_DISABLE)
3137 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
3138 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
3140 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
3143 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3145 ///////////////////////////////////////////////////////////////////////////////
3146 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
3148 #define INTERNAL_CATCH_TRY
3149 #define INTERNAL_CATCH_CATCH(capturer)
3151 #else // CATCH_CONFIG_FAST_COMPILE
3153 #define INTERNAL_CATCH_TRY try
3154 #define INTERNAL_CATCH_CATCH(handler) \
3156 handler.handleUnexpectedInflightException(); \
3161 #define INTERNAL_CATCH_REACT(handler) handler.complete();
3163 ///////////////////////////////////////////////////////////////////////////////
3164 #define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \
3166 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
3167 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, \
3168 CATCH_INTERNAL_LINEINFO, \
3169 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
3170 resultDisposition); \
3171 INTERNAL_CATCH_TRY { \
3172 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3173 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
3174 catchAssertionHandler.handleExpr(Catch::Decomposer() <= __VA_ARGS__); \
3175 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3177 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
3178 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3179 } while ((void)0, (false) && static_cast<bool>(!!(__VA_ARGS__)))
3181 ///////////////////////////////////////////////////////////////////////////////
3182 #define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \
3183 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
3184 if (Catch::getResultCapture().lastAssertionPassed())
3186 ///////////////////////////////////////////////////////////////////////////////
3187 #define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \
3188 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
3189 if (!Catch::getResultCapture().lastAssertionPassed())
3191 ///////////////////////////////////////////////////////////////////////////////
3192 #define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \
3194 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, \
3195 CATCH_INTERNAL_LINEINFO, \
3196 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
3197 resultDisposition); \
3199 static_cast<void>(__VA_ARGS__); \
3200 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
3202 catchAssertionHandler.handleUnexpectedInflightException(); \
3204 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3207 ///////////////////////////////////////////////////////////////////////////////
3208 #define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \
3210 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, \
3211 CATCH_INTERNAL_LINEINFO, \
3212 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
3213 resultDisposition); \
3214 if (catchAssertionHandler.allowThrows()) \
3216 static_cast<void>(__VA_ARGS__); \
3217 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3219 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3222 catchAssertionHandler.handleThrowingCallSkipped(); \
3223 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3226 ///////////////////////////////////////////////////////////////////////////////
3227 #define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr) \
3229 Catch::AssertionHandler catchAssertionHandler( \
3230 macroName##_catch_sr, \
3231 CATCH_INTERNAL_LINEINFO, \
3232 CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), \
3233 resultDisposition); \
3234 if (catchAssertionHandler.allowThrows()) \
3236 static_cast<void>(expr); \
3237 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3238 } catch (exceptionType const&) { \
3239 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3241 catchAssertionHandler.handleUnexpectedInflightException(); \
3244 catchAssertionHandler.handleThrowingCallSkipped(); \
3245 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3248 ///////////////////////////////////////////////////////////////////////////////
3249 #define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \
3251 Catch::AssertionHandler catchAssertionHandler( \
3252 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition); \
3253 catchAssertionHandler.handleMessage( \
3255 (Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop()).m_stream.str()); \
3256 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3259 ///////////////////////////////////////////////////////////////////////////////
3260 #define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \
3262 Catch::Capturer(macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__); \
3263 varName.captureValues(0, __VA_ARGS__)
3265 ///////////////////////////////////////////////////////////////////////////////
3266 #define INTERNAL_CATCH_INFO(macroName, log) \
3267 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage)( \
3268 Catch::MessageBuilder( \
3269 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info) \
3272 ///////////////////////////////////////////////////////////////////////////////
3273 #define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \
3274 Catch::getResultCapture().emplaceUnscopedMessage( \
3275 Catch::MessageBuilder( \
3276 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info) \
3279 ///////////////////////////////////////////////////////////////////////////////
3280 // Although this is matcher-based, it can be used with just a string
3281 #define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...) \
3283 Catch::AssertionHandler catchAssertionHandler( \
3284 macroName##_catch_sr, \
3285 CATCH_INTERNAL_LINEINFO, \
3286 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
3287 resultDisposition); \
3288 if (catchAssertionHandler.allowThrows()) \
3290 static_cast<void>(__VA_ARGS__); \
3291 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3293 Catch::handleExceptionMatchExpr( \
3294 catchAssertionHandler, matcher, #matcher##_catch_sr); \
3297 catchAssertionHandler.handleThrowingCallSkipped(); \
3298 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3301 #endif // CATCH_CONFIG_DISABLE
3303 // end catch_capture.hpp
3304 // start catch_section.h
3306 // start catch_section_info.h
3308 // start catch_totals.h
3315 Counts operator-(Counts const& other) const;
3316 Counts& operator+=(Counts const& other);
3318 std::size_t total() const;
3319 bool allPassed() const;
3322 std::size_t passed = 0;
3323 std::size_t failed = 0;
3324 std::size_t failedButOk = 0;
3329 Totals operator-(Totals const& other) const;
3330 Totals& operator+=(Totals const& other);
3332 Totals delta(Totals const& prevTotals) const;
3338 } // namespace Catch
3340 // end catch_totals.h
3345 struct SectionInfo {
3346 SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name);
3349 SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name, std::string const&) :
3350 SectionInfo(_lineInfo, _name) {}
3353 std::string description; // !Deprecated: this will always be empty
3354 SourceLineInfo lineInfo;
3357 struct SectionEndInfo {
3358 SectionInfo sectionInfo;
3359 Counts prevAssertions;
3360 double durationInSeconds;
3363 } // end namespace Catch
3365 // end catch_section_info.h
3366 // start catch_timer.h
3372 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
3373 auto getEstimatedClockResolution() -> uint64_t;
3376 uint64_t m_nanoseconds = 0;
3380 auto getElapsedNanoseconds() const -> uint64_t;
3381 auto getElapsedMicroseconds() const -> uint64_t;
3382 auto getElapsedMilliseconds() const -> unsigned int;
3383 auto getElapsedSeconds() const -> double;
3386 } // namespace Catch
3388 // end catch_timer.h
3393 class Section : NonCopyable {
3395 Section(SectionInfo const& info);
3398 // This indicates whether the section should be executed or not
3399 explicit operator bool() const;
3405 Counts m_assertions;
3406 bool m_sectionIncluded;
3410 } // end namespace Catch
3412 #define INTERNAL_CATCH_SECTION(...) \
3413 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3414 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3415 if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3416 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__)) \
3417 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3419 #define INTERNAL_CATCH_DYNAMIC_SECTION(...) \
3420 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3421 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3422 if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3423 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, \
3424 (Catch::ReusableStringStream() << __VA_ARGS__).str())) \
3425 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3427 // end catch_section.h
3428 // start catch_interfaces_exception.h
3430 // start catch_interfaces_registry_hub.h
3438 struct ITestCaseRegistry;
3439 struct IExceptionTranslatorRegistry;
3440 struct IExceptionTranslator;
3441 struct IReporterRegistry;
3442 struct IReporterFactory;
3443 struct ITagAliasRegistry;
3444 struct IMutableEnumValuesRegistry;
3446 class StartupExceptionRegistry;
3448 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
3450 struct IRegistryHub {
3451 virtual ~IRegistryHub();
3453 virtual IReporterRegistry const& getReporterRegistry() const = 0;
3454 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
3455 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
3456 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
3458 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
3461 struct IMutableRegistryHub {
3462 virtual ~IMutableRegistryHub();
3463 virtual void registerReporter(std::string const& name,
3464 IReporterFactoryPtr const& factory) = 0;
3465 virtual void registerListener(IReporterFactoryPtr const& factory) = 0;
3466 virtual void registerTest(TestCase const& testInfo) = 0;
3467 virtual void registerTranslator(const IExceptionTranslator* translator) = 0;
3468 virtual void registerTagAlias(std::string const& alias,
3469 std::string const& tag,
3470 SourceLineInfo const& lineInfo) = 0;
3471 virtual void registerStartupException() noexcept = 0;
3472 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
3475 IRegistryHub const& getRegistryHub();
3476 IMutableRegistryHub& getMutableRegistryHub();
3478 std::string translateActiveException();
3480 } // namespace Catch
3482 // end catch_interfaces_registry_hub.h
3483 #if defined(CATCH_CONFIG_DISABLE)
3484 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(translatorName, signature) \
3485 static std::string translatorName(signature)
3488 #include <exception>
3493 using exceptionTranslateFunction = std::string (*)();
3495 struct IExceptionTranslator;
3496 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3498 struct IExceptionTranslator {
3499 virtual ~IExceptionTranslator();
3500 virtual std::string translate(ExceptionTranslators::const_iterator it,
3501 ExceptionTranslators::const_iterator itEnd) const = 0;
3504 struct IExceptionTranslatorRegistry {
3505 virtual ~IExceptionTranslatorRegistry();
3507 virtual std::string translateActiveException() const = 0;
3510 class ExceptionTranslatorRegistrar {
3511 template <typename T> class ExceptionTranslator : public IExceptionTranslator {
3513 ExceptionTranslator(std::string (*translateFunction)(T&)) :
3514 m_translateFunction(translateFunction) {}
3516 std::string translate(ExceptionTranslators::const_iterator it,
3517 ExceptionTranslators::const_iterator itEnd) const override {
3518 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3523 std::rethrow_exception(std::current_exception());
3525 return (*it)->translate(it + 1, itEnd);
3527 return m_translateFunction(ex);
3533 std::string (*m_translateFunction)(T&);
3537 template <typename T> ExceptionTranslatorRegistrar(std::string (*translateFunction)(T&)) {
3538 getMutableRegistryHub().registerTranslator(
3539 new ExceptionTranslator<T>(translateFunction));
3542 } // namespace Catch
3544 ///////////////////////////////////////////////////////////////////////////////
3545 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \
3546 static std::string translatorName(signature); \
3547 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3548 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3550 Catch::ExceptionTranslatorRegistrar \
3551 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionRegistrar)(&translatorName); \
3553 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3554 static std::string translatorName(signature)
3556 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) \
3557 INTERNAL_CATCH_TRANSLATE_EXCEPTION2( \
3558 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
3560 // end catch_interfaces_exception.h
3561 // start catch_approx.h
3563 #include <type_traits>
3570 bool equalityComparisonImpl(double other) const;
3571 // Validates the new margin (margin >= 0)
3572 // out-of-line to avoid including stdexcept in the header
3573 void setMargin(double margin);
3574 // Validates the new epsilon (0 < epsilon < 1)
3575 // out-of-line to avoid including stdexcept in the header
3576 void setEpsilon(double epsilon);
3579 explicit Approx(double value);
3581 static Approx custom();
3583 Approx operator-() const;
3587 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3588 Approx operator()(T const& value) {
3589 Approx approx(static_cast<double>(value));
3590 approx.m_epsilon = m_epsilon;
3591 approx.m_margin = m_margin;
3592 approx.m_scale = m_scale;
3598 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3599 explicit Approx(T const& value) : Approx(static_cast<double>(value)) {}
3603 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3604 friend bool operator==(const T& lhs, Approx const& rhs) {
3605 auto lhs_v = static_cast<double>(lhs);
3606 return rhs.equalityComparisonImpl(lhs_v);
3611 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3612 friend bool operator==(Approx const& lhs, const T& rhs) {
3613 return operator==(rhs, lhs);
3618 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3619 friend bool operator!=(T const& lhs, Approx const& rhs) {
3620 return !operator==(lhs, rhs);
3625 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3626 friend bool operator!=(Approx const& lhs, T const& rhs) {
3627 return !operator==(rhs, lhs);
3632 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3633 friend bool operator<=(T const& lhs, Approx const& rhs) {
3634 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3639 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3640 friend bool operator<=(Approx const& lhs, T const& rhs) {
3641 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3646 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3647 friend bool operator>=(T const& lhs, Approx const& rhs) {
3648 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3653 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3654 friend bool operator>=(Approx const& lhs, T const& rhs) {
3655 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3660 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3661 Approx& epsilon(T const& newEpsilon) {
3662 double epsilonAsDouble = static_cast<double>(newEpsilon);
3663 setEpsilon(epsilonAsDouble);
3669 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3670 Approx& margin(T const& newMargin) {
3671 double marginAsDouble = static_cast<double>(newMargin);
3672 setMargin(marginAsDouble);
3678 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3679 Approx& scale(T const& newScale) {
3680 m_scale = static_cast<double>(newScale);
3684 std::string toString() const;
3692 } // end namespace Detail
3694 namespace literals {
3695 Detail::Approx operator"" _a(long double val);
3696 Detail::Approx operator"" _a(unsigned long long val);
3697 } // end namespace literals
3699 template <> struct StringMaker<Catch::Detail::Approx> {
3700 static std::string convert(Catch::Detail::Approx const& value);
3703 } // end namespace Catch
3705 // end catch_approx.h
3706 // start catch_string_manip.h
3714 bool startsWith(std::string const& s, std::string const& prefix);
3715 bool startsWith(std::string const& s, char prefix);
3716 bool endsWith(std::string const& s, std::string const& suffix);
3717 bool endsWith(std::string const& s, char suffix);
3718 bool contains(std::string const& s, std::string const& infix);
3719 void toLowerInPlace(std::string& s);
3720 std::string toLower(std::string const& s);
3721 //! Returns a new string without whitespace at the start/end
3722 std::string trim(std::string const& str);
3723 //! Returns a substring of the original ref without whitespace. Beware
3725 StringRef trim(StringRef ref);
3727 // !!! Be aware, returns refs into original string - make sure original
3728 // string outlives them
3729 std::vector<StringRef> splitStringRef(StringRef str, char delimiter);
3731 replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis);
3734 pluralise(std::size_t count, std::string const& label);
3736 friend std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser);
3738 std::size_t m_count;
3739 std::string m_label;
3741 } // namespace Catch
3743 // end catch_string_manip.h
3744 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3745 // start catch_capture_matchers.h
3747 // start catch_matchers.h
3753 namespace Matchers {
3756 template <typename ArgT> struct MatchAllOf;
3757 template <typename ArgT> struct MatchAnyOf;
3758 template <typename ArgT> struct MatchNotOf;
3760 class MatcherUntypedBase {
3762 MatcherUntypedBase() = default;
3763 MatcherUntypedBase(MatcherUntypedBase const&) = default;
3764 MatcherUntypedBase& operator=(MatcherUntypedBase const&) = delete;
3765 std::string toString() const;
3768 virtual ~MatcherUntypedBase();
3769 virtual std::string describe() const = 0;
3770 mutable std::string m_cachedToString;
3774 #pragma clang diagnostic push
3775 #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3778 template <typename ObjectT> struct MatcherMethod {
3779 virtual bool match(ObjectT const& arg) const = 0;
3782 #if defined(__OBJC__)
3783 // Hack to fix Catch GH issue #1661. Could use id for generic Object
3784 // support. use of const for Object pointers is very uncommon and
3785 // under ARC it causes some kind of signature mismatch that breaks
3787 template <> struct MatcherMethod<NSString*> {
3788 virtual bool match(NSString* arg) const = 0;
3793 #pragma clang diagnostic pop
3796 template <typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3798 MatchAllOf<T> operator&&(MatcherBase const& other) const;
3799 MatchAnyOf<T> operator||(MatcherBase const& other) const;
3800 MatchNotOf<T> operator!() const;
3803 template <typename ArgT> struct MatchAllOf : MatcherBase<ArgT> {
3804 bool match(ArgT const& arg) const override {
3805 for (auto matcher : m_matchers) {
3806 if (!matcher->match(arg))
3811 std::string describe() const override {
3812 std::string description;
3813 description.reserve(4 + m_matchers.size() * 32);
3814 description += "( ";
3816 for (auto matcher : m_matchers) {
3820 description += " and ";
3821 description += matcher->toString();
3823 description += " )";
3827 MatchAllOf<ArgT> operator&&(MatcherBase<ArgT> const& other) {
3829 copy.m_matchers.push_back(&other);
3833 std::vector<MatcherBase<ArgT> const*> m_matchers;
3835 template <typename ArgT> struct MatchAnyOf : MatcherBase<ArgT> {
3837 bool match(ArgT const& arg) const override {
3838 for (auto matcher : m_matchers) {
3839 if (matcher->match(arg))
3844 std::string describe() const override {
3845 std::string description;
3846 description.reserve(4 + m_matchers.size() * 32);
3847 description += "( ";
3849 for (auto matcher : m_matchers) {
3853 description += " or ";
3854 description += matcher->toString();
3856 description += " )";
3860 MatchAnyOf<ArgT> operator||(MatcherBase<ArgT> const& other) {
3862 copy.m_matchers.push_back(&other);
3866 std::vector<MatcherBase<ArgT> const*> m_matchers;
3869 template <typename ArgT> struct MatchNotOf : MatcherBase<ArgT> {
3871 MatchNotOf(MatcherBase<ArgT> const& underlyingMatcher) :
3872 m_underlyingMatcher(underlyingMatcher) {}
3874 bool match(ArgT const& arg) const override {
3875 return !m_underlyingMatcher.match(arg);
3878 std::string describe() const override {
3879 return "not " + m_underlyingMatcher.toString();
3881 MatcherBase<ArgT> const& m_underlyingMatcher;
3884 template <typename T>
3885 MatchAllOf<T> MatcherBase<T>::operator&&(MatcherBase const& other) const {
3886 return MatchAllOf<T>() && *this && other;
3888 template <typename T>
3889 MatchAnyOf<T> MatcherBase<T>::operator||(MatcherBase const& other) const {
3890 return MatchAnyOf<T>() || *this || other;
3892 template <typename T> MatchNotOf<T> MatcherBase<T>::operator!() const {
3893 return MatchNotOf<T>(*this);
3898 } // namespace Matchers
3900 using namespace Matchers;
3901 using Matchers::Impl::MatcherBase;
3903 } // namespace Catch
3905 // end catch_matchers.h
3906 // start catch_matchers_exception.hpp
3909 namespace Matchers {
3910 namespace Exception {
3912 class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3913 std::string m_message;
3916 ExceptionMessageMatcher(std::string const& message) : m_message(message) {}
3918 bool match(std::exception const& ex) const override;
3920 std::string describe() const override;
3923 } // namespace Exception
3925 Exception::ExceptionMessageMatcher Message(std::string const& message);
3927 } // namespace Matchers
3928 } // namespace Catch
3930 // end catch_matchers_exception.hpp
3931 // start catch_matchers_floating.h
3934 namespace Matchers {
3936 namespace Floating {
3938 enum class FloatingPointKind : uint8_t;
3940 struct WithinAbsMatcher : MatcherBase<double> {
3941 WithinAbsMatcher(double target, double margin);
3942 bool match(double const& matchee) const override;
3943 std::string describe() const override;
3950 struct WithinUlpsMatcher : MatcherBase<double> {
3951 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3952 bool match(double const& matchee) const override;
3953 std::string describe() const override;
3958 FloatingPointKind m_type;
3961 // Given IEEE-754 format for floats and doubles, we can assume
3962 // that float -> double promotion is lossless. Given this, we can
3963 // assume that if we do the standard relative comparison of
3964 // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3965 // the same result if we do this for floats, as if we do this for
3966 // doubles that were promoted from floats.
3967 struct WithinRelMatcher : MatcherBase<double> {
3968 WithinRelMatcher(double target, double epsilon);
3969 bool match(double const& matchee) const override;
3970 std::string describe() const override;
3977 } // namespace Floating
3979 // The following functions create the actual matcher objects.
3980 // This allows the types to be inferred
3981 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3982 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3983 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3984 Floating::WithinRelMatcher WithinRel(double target, double eps);
3985 // defaults epsilon to 100*numeric_limits<double>::epsilon()
3986 Floating::WithinRelMatcher WithinRel(double target);
3987 Floating::WithinRelMatcher WithinRel(float target, float eps);
3988 // defaults epsilon to 100*numeric_limits<float>::epsilon()
3989 Floating::WithinRelMatcher WithinRel(float target);
3991 } // namespace Matchers
3992 } // namespace Catch
3994 // end catch_matchers_floating.h
3995 // start catch_matchers_generic.hpp
3997 #include <functional>
4001 namespace Matchers {
4005 std::string finalizeDescription(const std::string& desc);
4008 template <typename T> class PredicateMatcher : public MatcherBase<T> {
4009 std::function<bool(T const&)> m_predicate;
4010 std::string m_description;
4013 PredicateMatcher(std::function<bool(T const&)> const& elem,
4014 std::string const& descr) :
4015 m_predicate(std::move(elem)),
4016 m_description(Detail::finalizeDescription(descr)) {}
4018 bool match(T const& item) const override { return m_predicate(item); }
4020 std::string describe() const override { return m_description; }
4023 } // namespace Generic
4025 // The following functions create the actual matcher objects.
4026 // The user has to explicitly specify type to the function, because
4027 // inferring std::function<bool(T const&)> is hard (but possible) and
4028 // requires a lot of TMP.
4029 template <typename T>
4030 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate,
4031 std::string const& description = "") {
4032 return Generic::PredicateMatcher<T>(predicate, description);
4035 } // namespace Matchers
4036 } // namespace Catch
4038 // end catch_matchers_generic.hpp
4039 // start catch_matchers_string.h
4044 namespace Matchers {
4046 namespace StdString {
4048 struct CasedString {
4049 CasedString(std::string const& str, CaseSensitive::Choice caseSensitivity);
4050 std::string adjustString(std::string const& str) const;
4051 std::string caseSensitivitySuffix() const;
4053 CaseSensitive::Choice m_caseSensitivity;
4057 struct StringMatcherBase : MatcherBase<std::string> {
4058 StringMatcherBase(std::string const& operation, CasedString const& comparator);
4059 std::string describe() const override;
4061 CasedString m_comparator;
4062 std::string m_operation;
4065 struct EqualsMatcher : StringMatcherBase {
4066 EqualsMatcher(CasedString const& comparator);
4067 bool match(std::string const& source) const override;
4069 struct ContainsMatcher : StringMatcherBase {
4070 ContainsMatcher(CasedString const& comparator);
4071 bool match(std::string const& source) const override;
4073 struct StartsWithMatcher : StringMatcherBase {
4074 StartsWithMatcher(CasedString const& comparator);
4075 bool match(std::string const& source) const override;
4077 struct EndsWithMatcher : StringMatcherBase {
4078 EndsWithMatcher(CasedString const& comparator);
4079 bool match(std::string const& source) const override;
4082 struct RegexMatcher : MatcherBase<std::string> {
4083 RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
4084 bool match(std::string const& matchee) const override;
4085 std::string describe() const override;
4088 std::string m_regex;
4089 CaseSensitive::Choice m_caseSensitivity;
4092 } // namespace StdString
4094 // The following functions create the actual matcher objects.
4095 // This allows the types to be inferred
4097 StdString::EqualsMatcher Equals(std::string const& str,
4098 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4099 StdString::ContainsMatcher
4100 Contains(std::string const& str,
4101 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4102 StdString::EndsWithMatcher
4103 EndsWith(std::string const& str,
4104 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4105 StdString::StartsWithMatcher
4106 StartsWith(std::string const& str,
4107 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4108 StdString::RegexMatcher Matches(std::string const& regex,
4109 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4111 } // namespace Matchers
4112 } // namespace Catch
4114 // end catch_matchers_string.h
4115 // start catch_matchers_vector.h
4117 #include <algorithm>
4120 namespace Matchers {
4123 template <typename T, typename Alloc>
4124 struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
4126 ContainsElementMatcher(T const& comparator) : m_comparator(comparator) {}
4128 bool match(std::vector<T, Alloc> const& v) const override {
4129 for (auto const& el : v) {
4130 if (el == m_comparator) {
4137 std::string describe() const override {
4138 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
4141 T const& m_comparator;
4144 template <typename T, typename AllocComp, typename AllocMatch>
4145 struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4147 ContainsMatcher(std::vector<T, AllocComp> const& comparator) :
4148 m_comparator(comparator) {}
4150 bool match(std::vector<T, AllocMatch> const& v) const override {
4151 // !TBD: see note in EqualsMatcher
4152 if (m_comparator.size() > v.size())
4154 for (auto const& comparator : m_comparator) {
4155 auto present = false;
4156 for (const auto& el : v) {
4157 if (el == comparator) {
4168 std::string describe() const override {
4169 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
4172 std::vector<T, AllocComp> const& m_comparator;
4175 template <typename T, typename AllocComp, typename AllocMatch>
4176 struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4178 EqualsMatcher(std::vector<T, AllocComp> const& comparator) :
4179 m_comparator(comparator) {}
4181 bool match(std::vector<T, AllocMatch> const& v) const override {
4182 // !TBD: This currently works if all elements can be
4183 // compared using !=
4184 // - a more general approach would be via a compare template
4185 // that defaults to using !=. but could be specialised for,
4186 // e.g. std::vector<T, Alloc> etc
4187 // - then just call that directly
4188 if (m_comparator.size() != v.size())
4190 for (std::size_t i = 0; i < v.size(); ++i)
4191 if (m_comparator[i] != v[i])
4195 std::string describe() const override {
4196 return "Equals: " + ::Catch::Detail::stringify(m_comparator);
4198 std::vector<T, AllocComp> const& m_comparator;
4201 template <typename T, typename AllocComp, typename AllocMatch>
4202 struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4204 ApproxMatcher(std::vector<T, AllocComp> const& comparator) :
4205 m_comparator(comparator) {}
4207 bool match(std::vector<T, AllocMatch> const& v) const override {
4208 if (m_comparator.size() != v.size())
4210 for (std::size_t i = 0; i < v.size(); ++i)
4211 if (m_comparator[i] != approx(v[i]))
4215 std::string describe() const override {
4216 return "is approx: " + ::Catch::Detail::stringify(m_comparator);
4218 template <typename = typename std::enable_if<
4219 std::is_constructible<double, T>::value>::type>
4220 ApproxMatcher& epsilon(T const& newEpsilon) {
4221 approx.epsilon(newEpsilon);
4224 template <typename = typename std::enable_if<
4225 std::is_constructible<double, T>::value>::type>
4226 ApproxMatcher& margin(T const& newMargin) {
4227 approx.margin(newMargin);
4230 template <typename = typename std::enable_if<
4231 std::is_constructible<double, T>::value>::type>
4232 ApproxMatcher& scale(T const& newScale) {
4233 approx.scale(newScale);
4237 std::vector<T, AllocComp> const& m_comparator;
4238 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
4241 template <typename T, typename AllocComp, typename AllocMatch>
4242 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4243 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) :
4245 bool match(std::vector<T, AllocMatch> const& vec) const override {
4246 if (m_target.size() != vec.size()) {
4249 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
4252 std::string describe() const override {
4253 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
4257 std::vector<T, AllocComp> const& m_target;
4260 } // namespace Vector
4262 // The following functions create the actual matcher objects.
4263 // This allows the types to be inferred
4265 template <typename T,
4266 typename AllocComp = std::allocator<T>,
4267 typename AllocMatch = AllocComp>
4268 Vector::ContainsMatcher<T, AllocComp, AllocMatch>
4269 Contains(std::vector<T, AllocComp> const& comparator) {
4270 return Vector::ContainsMatcher<T, AllocComp, AllocMatch>(comparator);
4273 template <typename T, typename Alloc = std::allocator<T>>
4274 Vector::ContainsElementMatcher<T, Alloc> VectorContains(T const& comparator) {
4275 return Vector::ContainsElementMatcher<T, Alloc>(comparator);
4278 template <typename T,
4279 typename AllocComp = std::allocator<T>,
4280 typename AllocMatch = AllocComp>
4281 Vector::EqualsMatcher<T, AllocComp, AllocMatch>
4282 Equals(std::vector<T, AllocComp> const& comparator) {
4283 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>(comparator);
4286 template <typename T,
4287 typename AllocComp = std::allocator<T>,
4288 typename AllocMatch = AllocComp>
4289 Vector::ApproxMatcher<T, AllocComp, AllocMatch>
4290 Approx(std::vector<T, AllocComp> const& comparator) {
4291 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>(comparator);
4294 template <typename T,
4295 typename AllocComp = std::allocator<T>,
4296 typename AllocMatch = AllocComp>
4297 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>
4298 UnorderedEquals(std::vector<T, AllocComp> const& target) {
4299 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>(target);
4302 } // namespace Matchers
4303 } // namespace Catch
4305 // end catch_matchers_vector.h
4308 template <typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression {
4311 StringRef m_matcherString;
4314 MatchExpr(ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString) :
4315 ITransientExpression{true, matcher.match(arg)},
4318 m_matcherString(matcherString) {}
4320 void streamReconstructedExpression(std::ostream& os) const override {
4321 auto matcherAsString = m_matcher.toString();
4322 os << Catch::Detail::stringify(m_arg) << ' ';
4323 if (matcherAsString == Detail::unprintableString)
4324 os << m_matcherString;
4326 os << matcherAsString;
4330 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
4332 void handleExceptionMatchExpr(AssertionHandler& handler,
4333 StringMatcher const& matcher,
4334 StringRef const& matcherString);
4336 template <typename ArgT, typename MatcherT>
4337 auto makeMatchExpr(ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString)
4338 -> MatchExpr<ArgT, MatcherT> {
4339 return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString);
4342 } // namespace Catch
4344 ///////////////////////////////////////////////////////////////////////////////
4345 #define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \
4347 Catch::AssertionHandler catchAssertionHandler( \
4348 macroName##_catch_sr, \
4349 CATCH_INTERNAL_LINEINFO, \
4350 CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
4351 resultDisposition); \
4352 INTERNAL_CATCH_TRY { \
4353 catchAssertionHandler.handleExpr( \
4354 Catch::makeMatchExpr(arg, matcher, #matcher##_catch_sr)); \
4356 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
4357 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4360 ///////////////////////////////////////////////////////////////////////////////
4361 #define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...) \
4363 Catch::AssertionHandler catchAssertionHandler( \
4364 macroName##_catch_sr, \
4365 CATCH_INTERNAL_LINEINFO, \
4366 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY( \
4367 exceptionType) "," \
4368 " " CATCH_INTERNAL_STRINGIFY(matcher), \
4369 resultDisposition); \
4370 if (catchAssertionHandler.allowThrows()) \
4372 static_cast<void>(__VA_ARGS__); \
4373 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
4374 } catch (exceptionType const& ex) { \
4375 catchAssertionHandler.handleExpr( \
4376 Catch::makeMatchExpr(ex, matcher, #matcher##_catch_sr)); \
4378 catchAssertionHandler.handleUnexpectedInflightException(); \
4381 catchAssertionHandler.handleThrowingCallSkipped(); \
4382 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4385 // end catch_capture_matchers.h
4387 // start catch_generators.hpp
4389 // start catch_interfaces_generatortracker.h
4395 namespace Generators {
4396 class GeneratorUntypedBase {
4398 GeneratorUntypedBase() = default;
4399 virtual ~GeneratorUntypedBase();
4400 // Attempts to move the generator to the next element
4402 // Returns true iff the move succeeded (and a valid element
4403 // can be retrieved).
4404 virtual bool next() = 0;
4406 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
4408 } // namespace Generators
4410 struct IGeneratorTracker {
4411 virtual ~IGeneratorTracker();
4412 virtual auto hasGenerator() const -> bool = 0;
4413 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
4414 virtual void setGenerator(Generators::GeneratorBasePtr&& generator) = 0;
4417 } // namespace Catch
4419 // end catch_interfaces_generatortracker.h
4420 // start catch_enforce.h
4422 #include <exception>
4425 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
4426 template <typename Ex> [[noreturn]] void throw_exception(Ex const& e) { throw e; }
4427 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
4428 [[noreturn]] void throw_exception(std::exception const& e);
4431 [[noreturn]] void throw_logic_error(std::string const& msg);
4432 [[noreturn]] void throw_domain_error(std::string const& msg);
4433 [[noreturn]] void throw_runtime_error(std::string const& msg);
4435 } // namespace Catch
4437 #define CATCH_MAKE_MSG(...) (Catch::ReusableStringStream() << __VA_ARGS__).str()
4439 #define CATCH_INTERNAL_ERROR(...) \
4440 Catch::throw_logic_error( \
4441 CATCH_MAKE_MSG(CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
4443 #define CATCH_ERROR(...) Catch::throw_domain_error(CATCH_MAKE_MSG(__VA_ARGS__))
4445 #define CATCH_RUNTIME_ERROR(...) Catch::throw_runtime_error(CATCH_MAKE_MSG(__VA_ARGS__))
4447 #define CATCH_ENFORCE(condition, ...) \
4450 CATCH_ERROR(__VA_ARGS__); \
4453 // end catch_enforce.h
4459 #include <exception>
4463 class GeneratorException : public std::exception {
4464 const char* const m_msg = "";
4467 GeneratorException(const char* msg) : m_msg(msg) {}
4469 const char* what() const noexcept override final;
4472 namespace Generators {
4474 // !TBD move this into its own location?
4476 template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
4477 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
4481 template <typename T> struct IGenerator : GeneratorUntypedBase {
4482 virtual ~IGenerator() = default;
4484 // Returns the current element of the generator
4486 // \Precondition The generator is either freshly constructed,
4487 // or the last call to `next()` returned true
4488 virtual T const& get() const = 0;
4492 template <typename T> class SingleValueGenerator final : public IGenerator<T> {
4496 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
4498 T const& get() const override { return m_value; }
4499 bool next() override { return false; }
4502 template <typename T> class FixedValuesGenerator final : public IGenerator<T> {
4503 static_assert(!std::is_same<T, bool>::value,
4504 "FixedValuesGenerator does not support bools because "
4505 "of std::vector<bool>"
4506 "specialization, use SingleValue Generator instead.");
4507 std::vector<T> m_values;
4511 FixedValuesGenerator(std::initializer_list<T> values) : m_values(values) {}
4513 T const& get() const override { return m_values[m_idx]; }
4514 bool next() override {
4516 return m_idx < m_values.size();
4520 template <typename T> class GeneratorWrapper final {
4521 std::unique_ptr<IGenerator<T>> m_generator;
4524 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator) :
4525 m_generator(std::move(generator)) {}
4526 T const& get() const { return m_generator->get(); }
4527 bool next() { return m_generator->next(); }
4530 template <typename T> GeneratorWrapper<T> value(T&& value) {
4531 return GeneratorWrapper<T>(
4532 pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4534 template <typename T> GeneratorWrapper<T> values(std::initializer_list<T> values) {
4535 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4538 template <typename T> class Generators : public IGenerator<T> {
4539 std::vector<GeneratorWrapper<T>> m_generators;
4540 size_t m_current = 0;
4542 void populate(GeneratorWrapper<T>&& generator) {
4543 m_generators.emplace_back(std::move(generator));
4545 void populate(T&& val) { m_generators.emplace_back(value(std::forward<T>(val))); }
4546 template <typename U> void populate(U&& val) { populate(T(std::forward<U>(val))); }
4547 template <typename U, typename... Gs>
4548 void populate(U&& valueOrGenerator, Gs&&... moreGenerators) {
4549 populate(std::forward<U>(valueOrGenerator));
4550 populate(std::forward<Gs>(moreGenerators)...);
4554 template <typename... Gs> Generators(Gs&&... moreGenerators) {
4555 m_generators.reserve(sizeof...(Gs));
4556 populate(std::forward<Gs>(moreGenerators)...);
4559 T const& get() const override { return m_generators[m_current].get(); }
4561 bool next() override {
4562 if (m_current >= m_generators.size()) {
4565 const bool current_status = m_generators[m_current].next();
4566 if (!current_status) {
4569 return m_current < m_generators.size();
4573 template <typename... Ts>
4574 GeneratorWrapper<std::tuple<Ts...>>
4575 table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples) {
4576 return values<std::tuple<Ts...>>(tuples);
4579 // Tag type to signal that a generator sequence should convert arguments
4580 // to a specific type
4581 template <typename T> struct as {};
4583 template <typename T, typename... Gs>
4584 auto makeGenerators(GeneratorWrapper<T>&& generator, Gs&&... moreGenerators)
4586 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4588 template <typename T>
4589 auto makeGenerators(GeneratorWrapper<T>&& generator) -> Generators<T> {
4590 return Generators<T>(std::move(generator));
4592 template <typename T, typename... Gs>
4593 auto makeGenerators(T&& val, Gs&&... moreGenerators) -> Generators<T> {
4594 return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
4596 template <typename T, typename U, typename... Gs>
4597 auto makeGenerators(as<T>, U&& val, Gs&&... moreGenerators) -> Generators<T> {
4598 return makeGenerators(value(T(std::forward<U>(val))),
4599 std::forward<Gs>(moreGenerators)...);
4602 auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
4603 -> IGeneratorTracker&;
4605 template <typename L>
4606 // Note: The type after -> is weird, because VS2015 cannot parse
4607 // the expression used in the typedef inside, when it is in
4608 // return type. Yeah.
4609 auto generate(StringRef generatorName,
4610 SourceLineInfo const& lineInfo,
4611 L const& generatorExpression)
4612 -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4613 using UnderlyingType = typename decltype(generatorExpression())::type;
4615 IGeneratorTracker& tracker = acquireGeneratorTracker(generatorName, lineInfo);
4616 if (!tracker.hasGenerator()) {
4617 tracker.setGenerator(
4618 pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4621 auto const& generator =
4622 static_cast<IGenerator<UnderlyingType> const&>(*tracker.getGenerator());
4623 return generator.get();
4626 } // namespace Generators
4627 } // namespace Catch
4629 #define GENERATE(...) \
4630 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4631 CATCH_INTERNAL_LINEINFO, \
4633 using namespace Catch::Generators; \
4634 return makeGenerators(__VA_ARGS__); \
4635 }) // NOLINT(google-build-using-namespace)
4636 #define GENERATE_COPY(...) \
4637 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4638 CATCH_INTERNAL_LINEINFO, \
4640 using namespace Catch::Generators; \
4641 return makeGenerators(__VA_ARGS__); \
4642 }) // NOLINT(google-build-using-namespace)
4643 #define GENERATE_REF(...) \
4644 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4645 CATCH_INTERNAL_LINEINFO, \
4647 using namespace Catch::Generators; \
4648 return makeGenerators(__VA_ARGS__); \
4649 }) // NOLINT(google-build-using-namespace)
4651 // end catch_generators.hpp
4652 // start catch_generators_generic.hpp
4655 namespace Generators {
4657 template <typename T> class TakeGenerator : public IGenerator<T> {
4658 GeneratorWrapper<T> m_generator;
4659 size_t m_returned = 0;
4663 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator) :
4664 m_generator(std::move(generator)), m_target(target) {
4665 assert(target != 0 && "Empty generators are not allowed");
4667 T const& get() const override { return m_generator.get(); }
4668 bool next() override {
4670 if (m_returned >= m_target) {
4674 const auto success = m_generator.next();
4675 // If the underlying generator does not contain enough values
4676 // then we cut short as well
4678 m_returned = m_target;
4684 template <typename T>
4685 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4686 return GeneratorWrapper<T>(
4687 pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4690 template <typename T, typename Predicate> class FilterGenerator : public IGenerator<T> {
4691 GeneratorWrapper<T> m_generator;
4692 Predicate m_predicate;
4695 template <typename P = Predicate>
4696 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator) :
4697 m_generator(std::move(generator)), m_predicate(std::forward<P>(pred)) {
4698 if (!m_predicate(m_generator.get())) {
4699 // It might happen that there are no values that pass the
4700 // filter. In that case we throw an exception.
4701 auto has_initial_value = next();
4702 if (!has_initial_value) {
4703 Catch::throw_exception(
4704 GeneratorException("No valid value found in filtered generator"));
4709 T const& get() const override { return m_generator.get(); }
4711 bool next() override {
4712 bool success = m_generator.next();
4716 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true)
4722 template <typename T, typename Predicate>
4723 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4724 return GeneratorWrapper<T>(
4725 std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(
4726 std::forward<Predicate>(pred), std::move(generator))));
4729 template <typename T> class RepeatGenerator : public IGenerator<T> {
4730 static_assert(!std::is_same<T, bool>::value,
4731 "RepeatGenerator currently does not support bools"
4732 "because of std::vector<bool> specialization");
4733 GeneratorWrapper<T> m_generator;
4734 mutable std::vector<T> m_returned;
4735 size_t m_target_repeats;
4736 size_t m_current_repeat = 0;
4737 size_t m_repeat_index = 0;
4740 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator) :
4741 m_generator(std::move(generator)), m_target_repeats(repeats) {
4742 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4745 T const& get() const override {
4746 if (m_current_repeat == 0) {
4747 m_returned.push_back(m_generator.get());
4748 return m_returned.back();
4750 return m_returned[m_repeat_index];
4753 bool next() override {
4754 // There are 2 basic cases:
4755 // 1) We are still reading the generator
4756 // 2) We are reading our own cache
4758 // In the first case, we need to poke the underlying generator.
4759 // If it happily moves, we are left in that state, otherwise it
4760 // is time to start reading from our cache
4761 if (m_current_repeat == 0) {
4762 const auto success = m_generator.next();
4766 return m_current_repeat < m_target_repeats;
4769 // In the second case, we need to move indices forward and check
4770 // that we haven't run up against the end
4772 if (m_repeat_index == m_returned.size()) {
4776 return m_current_repeat < m_target_repeats;
4780 template <typename T>
4781 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4782 return GeneratorWrapper<T>(
4783 pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4786 template <typename T, typename U, typename Func> class MapGenerator : public IGenerator<T> {
4787 // TBD: provide static assert for mapping function, for friendly
4789 GeneratorWrapper<U> m_generator;
4791 // To avoid returning dangling reference, we have to save the values
4795 template <typename F2 = Func>
4796 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4797 m_generator(std::move(generator)),
4798 m_function(std::forward<F2>(function)),
4799 m_cache(m_function(m_generator.get())) {}
4801 T const& get() const override { return m_cache; }
4802 bool next() override {
4803 const auto success = m_generator.next();
4805 m_cache = m_function(m_generator.get());
4811 template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4812 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4813 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4814 std::forward<Func>(function), std::move(generator)));
4817 template <typename T, typename U, typename Func>
4818 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4819 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4820 std::forward<Func>(function), std::move(generator)));
4823 template <typename T> class ChunkGenerator final : public IGenerator<std::vector<T>> {
4824 std::vector<T> m_chunk;
4825 size_t m_chunk_size;
4826 GeneratorWrapper<T> m_generator;
4827 bool m_used_up = false;
4830 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4831 m_chunk_size(size), m_generator(std::move(generator)) {
4832 m_chunk.reserve(m_chunk_size);
4833 if (m_chunk_size != 0) {
4834 m_chunk.push_back(m_generator.get());
4835 for (size_t i = 1; i < m_chunk_size; ++i) {
4836 if (!m_generator.next()) {
4837 Catch::throw_exception(
4838 GeneratorException("Not enough values to initialize the first "
4841 m_chunk.push_back(m_generator.get());
4845 std::vector<T> const& get() const override { return m_chunk; }
4846 bool next() override {
4848 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4849 if (!m_generator.next()) {
4852 m_chunk.push_back(m_generator.get());
4858 template <typename T>
4859 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4860 return GeneratorWrapper<std::vector<T>>(
4861 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator)));
4864 } // namespace Generators
4865 } // namespace Catch
4867 // end catch_generators_generic.hpp
4868 // start catch_generators_specific.hpp
4870 // start catch_context.h
4876 struct IResultCapture;
4879 struct IMutableContext;
4881 using IConfigPtr = std::shared_ptr<IConfig const>;
4884 virtual ~IContext();
4886 virtual IResultCapture* getResultCapture() = 0;
4887 virtual IRunner* getRunner() = 0;
4888 virtual IConfigPtr const& getConfig() const = 0;
4891 struct IMutableContext : IContext {
4892 virtual ~IMutableContext();
4893 virtual void setResultCapture(IResultCapture* resultCapture) = 0;
4894 virtual void setRunner(IRunner* runner) = 0;
4895 virtual void setConfig(IConfigPtr const& config) = 0;
4898 static IMutableContext* currentContext;
4899 friend IMutableContext& getCurrentMutableContext();
4900 friend void cleanUpContext();
4901 static void createContext();
4904 inline IMutableContext& getCurrentMutableContext() {
4905 if (!IMutableContext::currentContext)
4906 IMutableContext::createContext();
4907 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4908 return *IMutableContext::currentContext;
4911 inline IContext& getCurrentContext() { return getCurrentMutableContext(); }
4913 void cleanUpContext();
4917 } // namespace Catch
4919 // end catch_context.h
4920 // start catch_interfaces_config.h
4922 // start catch_option.hpp
4927 template <typename T> class Option {
4929 Option() : nullableValue(nullptr) {}
4930 Option(T const& _value) : nullableValue(new (storage) T(_value)) {}
4931 Option(Option const& _other) : nullableValue(_other ? new (storage) T(*_other) : nullptr) {}
4933 ~Option() { reset(); }
4935 Option& operator=(Option const& _other) {
4936 if (&_other != this) {
4939 nullableValue = new (storage) T(*_other);
4943 Option& operator=(T const& _value) {
4945 nullableValue = new (storage) T(_value);
4951 nullableValue->~T();
4952 nullableValue = nullptr;
4955 T& operator*() { return *nullableValue; }
4956 T const& operator*() const { return *nullableValue; }
4957 T* operator->() { return nullableValue; }
4958 const T* operator->() const { return nullableValue; }
4960 T valueOr(T const& defaultValue) const {
4961 return nullableValue ? *nullableValue : defaultValue;
4964 bool some() const { return nullableValue != nullptr; }
4965 bool none() const { return nullableValue == nullptr; }
4967 bool operator!() const { return nullableValue == nullptr; }
4968 explicit operator bool() const { return some(); }
4972 alignas(alignof(T)) char storage[sizeof(T)];
4975 } // end namespace Catch
4977 // end catch_option.hpp
4986 enum class Verbosity { Quiet = 0, Normal, High };
4989 enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 };
4992 struct ShowDurations {
4993 enum OrNot { DefaultForReporter, Always, Never };
4996 enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder };
4999 enum YesOrNo { Auto, Yes, No };
5001 struct WaitForKeypress {
5006 BeforeStartAndExit = BeforeStart | BeforeExit
5012 struct IConfig : NonCopyable {
5016 virtual bool allowThrows() const = 0;
5017 virtual std::ostream& stream() const = 0;
5018 virtual std::string name() const = 0;
5019 virtual bool includeSuccessfulResults() const = 0;
5020 virtual bool shouldDebugBreak() const = 0;
5021 virtual bool warnAboutMissingAssertions() const = 0;
5022 virtual bool warnAboutNoTests() const = 0;
5023 virtual int abortAfter() const = 0;
5024 virtual bool showInvisibles() const = 0;
5025 virtual ShowDurations::OrNot showDurations() const = 0;
5026 virtual double minDuration() const = 0;
5027 virtual TestSpec const& testSpec() const = 0;
5028 virtual bool hasTestFilters() const = 0;
5029 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
5030 virtual RunTests::InWhatOrder runOrder() const = 0;
5031 virtual unsigned int rngSeed() const = 0;
5032 virtual UseColour::YesOrNo useColour() const = 0;
5033 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
5034 virtual Verbosity verbosity() const = 0;
5036 virtual bool benchmarkNoAnalysis() const = 0;
5037 virtual int benchmarkSamples() const = 0;
5038 virtual double benchmarkConfidenceInterval() const = 0;
5039 virtual unsigned int benchmarkResamples() const = 0;
5040 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
5043 using IConfigPtr = std::shared_ptr<IConfig const>;
5044 } // namespace Catch
5046 // end catch_interfaces_config.h
5047 // start catch_random_number_generator.h
5053 // This is a simple implementation of C++11 Uniform Random Number
5054 // Generator. It does not provide all operators, because Catch2
5055 // does not use it, but it should behave as expected inside stdlib's
5057 // The implementation is based on the PCG family (http://pcg-random.org)
5059 using state_type = std::uint64_t;
5062 using result_type = std::uint32_t;
5063 static constexpr result_type(min)() { return 0; }
5064 static constexpr result_type(max)() { return static_cast<result_type>(-1); }
5066 // Provide some default initial state for the default constructor
5067 SimplePcg32() : SimplePcg32(0xed743cc4U) {}
5069 explicit SimplePcg32(result_type seed_);
5071 void seed(result_type seed_);
5072 void discard(uint64_t skip);
5074 result_type operator()();
5077 friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
5078 friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
5080 // In theory we also need operator<< and operator>>
5081 // In practice we do not use them, so we will skip them for now
5083 std::uint64_t m_state;
5084 // This part of the state determines which "stream" of the numbers
5085 // is chosen -- we take it as a constant for Catch2, so we only
5086 // need to deal with seeding the main state.
5087 // Picked by reading 8 bytes from `/dev/random` :-)
5088 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
5091 } // end namespace Catch
5093 // end catch_random_number_generator.h
5097 namespace Generators {
5099 template <typename Float> class RandomFloatingGenerator final : public IGenerator<Float> {
5100 Catch::SimplePcg32& m_rng;
5101 std::uniform_real_distribution<Float> m_dist;
5102 Float m_current_number;
5105 RandomFloatingGenerator(Float a, Float b) : m_rng(rng()), m_dist(a, b) {
5106 static_cast<void>(next());
5109 Float const& get() const override { return m_current_number; }
5110 bool next() override {
5111 m_current_number = m_dist(m_rng);
5116 template <typename Integer>
5117 class RandomIntegerGenerator final : public IGenerator<Integer> {
5118 Catch::SimplePcg32& m_rng;
5119 std::uniform_int_distribution<Integer> m_dist;
5120 Integer m_current_number;
5123 RandomIntegerGenerator(Integer a, Integer b) : m_rng(rng()), m_dist(a, b) {
5124 static_cast<void>(next());
5127 Integer const& get() const override { return m_current_number; }
5128 bool next() override {
5129 m_current_number = m_dist(m_rng);
5134 // TODO: Ideally this would be also constrained against the various char
5136 // but I don't expect users to run into that in practice.
5137 template <typename T>
5138 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
5139 GeneratorWrapper<T>>::type
5141 return GeneratorWrapper<T>(pf::make_unique<RandomIntegerGenerator<T>>(a, b));
5144 template <typename T>
5145 typename std::enable_if<std::is_floating_point<T>::value, GeneratorWrapper<T>>::type
5147 return GeneratorWrapper<T>(pf::make_unique<RandomFloatingGenerator<T>>(a, b));
5150 template <typename T> class RangeGenerator final : public IGenerator<T> {
5157 RangeGenerator(T const& start, T const& end, T const& step) :
5158 m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0)) {
5159 assert(m_current != m_end && "Range start and end cannot be equal");
5160 assert(m_step != T(0) && "Step size cannot be zero");
5162 ((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
5163 "Step moves away from end");
5166 RangeGenerator(T const& start, T const& end) :
5167 RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {}
5169 T const& get() const override { return m_current; }
5171 bool next() override {
5172 m_current += m_step;
5173 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
5177 template <typename T>
5178 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
5179 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
5180 "Type must be numeric");
5181 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
5184 template <typename T> GeneratorWrapper<T> range(T const& start, T const& end) {
5185 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
5186 "Type must be an integer");
5187 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
5190 template <typename T> class IteratorGenerator final : public IGenerator<T> {
5191 static_assert(!std::is_same<T, bool>::value,
5192 "IteratorGenerator currently does not support bools"
5193 "because of std::vector<bool> specialization");
5195 std::vector<T> m_elems;
5196 size_t m_current = 0;
5199 template <typename InputIterator, typename InputSentinel>
5200 IteratorGenerator(InputIterator first, InputSentinel last) : m_elems(first, last) {
5201 if (m_elems.empty()) {
5202 Catch::throw_exception(
5203 GeneratorException("IteratorGenerator received no valid values"));
5207 T const& get() const override { return m_elems[m_current]; }
5209 bool next() override {
5211 return m_current != m_elems.size();
5215 template <typename InputIterator,
5216 typename InputSentinel,
5217 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
5218 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
5219 return GeneratorWrapper<ResultType>(
5220 pf::make_unique<IteratorGenerator<ResultType>>(from, to));
5223 template <typename Container, typename ResultType = typename Container::value_type>
5224 GeneratorWrapper<ResultType> from_range(Container const& cnt) {
5225 return GeneratorWrapper<ResultType>(
5226 pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
5229 } // namespace Generators
5230 } // namespace Catch
5232 // end catch_generators_specific.hpp
5234 // These files are included here so the single_include script doesn't put them
5235 // in the conditionally compiled sections
5236 // start catch_test_case_info.h
5243 #pragma clang diagnostic push
5244 #pragma clang diagnostic ignored "-Wpadded"
5249 struct ITestInvoker;
5251 struct TestCaseInfo {
5252 enum SpecialProperties {
5255 ShouldFail = 1 << 2,
5258 NonPortable = 1 << 5,
5262 TestCaseInfo(std::string const& _name,
5263 std::string const& _className,
5264 std::string const& _description,
5265 std::vector<std::string> const& _tags,
5266 SourceLineInfo const& _lineInfo);
5268 friend void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags);
5270 bool isHidden() const;
5271 bool throws() const;
5272 bool okToFail() const;
5273 bool expectedToFail() const;
5275 std::string tagsAsString() const;
5278 std::string className;
5279 std::string description;
5280 std::vector<std::string> tags;
5281 std::vector<std::string> lcaseTags;
5282 SourceLineInfo lineInfo;
5283 SpecialProperties properties;
5286 class TestCase : public TestCaseInfo {
5288 TestCase(ITestInvoker* testCase, TestCaseInfo&& info);
5290 TestCase withName(std::string const& _newName) const;
5292 void invoke() const;
5294 TestCaseInfo const& getTestCaseInfo() const;
5296 bool operator==(TestCase const& other) const;
5297 bool operator<(TestCase const& other) const;
5300 std::shared_ptr<ITestInvoker> test;
5303 TestCase makeTestCase(ITestInvoker* testCase,
5304 std::string const& className,
5305 NameAndTags const& nameAndTags,
5306 SourceLineInfo const& lineInfo);
5307 } // namespace Catch
5310 #pragma clang diagnostic pop
5313 // end catch_test_case_info.h
5314 // start catch_interfaces_runner.h
5320 virtual bool aborting() const = 0;
5322 } // namespace Catch
5324 // end catch_interfaces_runner.h
5327 // start catch_objc.hpp
5329 #import <objc/runtime.h>
5333 // NB. Any general catch headers included here must be included
5334 // in catch.hpp first to make sure they are included by the single
5335 // header for non obj-usage
5337 ///////////////////////////////////////////////////////////////////////////////
5338 // This protocol is really only here for (self) documenting purposes, since
5339 // all its methods are optional.
5351 class OcMethod : public ITestInvoker {
5354 OcMethod(Class cls, SEL sel) : m_cls(cls), m_sel(sel) {}
5356 virtual void invoke() const {
5357 id obj = [[m_cls alloc] init];
5359 performOptionalSelector(obj, @selector(setUp));
5360 performOptionalSelector(obj, m_sel);
5361 performOptionalSelector(obj, @selector(tearDown));
5363 arcSafeRelease(obj);
5367 virtual ~OcMethod() {}
5375 inline std::string getAnnotation(Class cls,
5376 std::string const& annotationName,
5377 std::string const& testCaseName) {
5378 NSString* selStr = [[NSString alloc]
5379 initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
5380 SEL sel = NSSelectorFromString(selStr);
5381 arcSafeRelease(selStr);
5382 id value = performOptionalSelector(cls, sel);
5384 return [(NSString*)value UTF8String];
5387 } // namespace Detail
5389 inline std::size_t registerTestMethods() {
5390 std::size_t noTestMethods = 0;
5391 int noClasses = objc_getClassList(nullptr, 0);
5393 Class* classes = (CATCH_UNSAFE_UNRETAINED Class*)malloc(sizeof(Class) * noClasses);
5394 objc_getClassList(classes, noClasses);
5396 for (int c = 0; c < noClasses; c++) {
5397 Class cls = classes[c];
5400 Method* methods = class_copyMethodList(cls, &count);
5401 for (u_int m = 0; m < count; m++) {
5402 SEL selector = method_getName(methods[m]);
5403 std::string methodName = sel_getName(selector);
5404 if (startsWith(methodName, "Catch_TestCase_")) {
5405 std::string testCaseName = methodName.substr(15);
5406 std::string name = Detail::getAnnotation(cls, "Name", testCaseName);
5407 std::string desc = Detail::getAnnotation(cls, "Description", testCaseName);
5408 const char* className = class_getName(cls);
5410 getMutableRegistryHub().registerTest(
5411 makeTestCase(new OcMethod(cls, selector),
5413 NameAndTags(name.c_str(), desc.c_str()),
5414 SourceLineInfo("", 0)));
5421 return noTestMethods;
5424 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
5426 namespace Matchers {
5428 namespace NSStringMatchers {
5430 struct StringHolder : MatcherBase<NSString*> {
5431 StringHolder(NSString* substr) : m_substr([substr copy]) {}
5432 StringHolder(StringHolder const& other) : m_substr([other.m_substr copy]) {}
5433 StringHolder() { arcSafeRelease(m_substr); }
5435 bool match(NSString* str) const override { return false; }
5437 NSString* CATCH_ARC_STRONG m_substr;
5440 struct Equals : StringHolder {
5441 Equals(NSString* substr) : StringHolder(substr) {}
5443 bool match(NSString* str) const override {
5444 return (str != nil || m_substr == nil) && [str isEqualToString:m_substr];
5447 std::string describe() const override {
5448 return "equals string: " + Catch::Detail::stringify(m_substr);
5452 struct Contains : StringHolder {
5453 Contains(NSString* substr) : StringHolder(substr) {}
5455 bool match(NSString* str) const override {
5456 return (str != nil || m_substr == nil) &&
5457 [str rangeOfString:m_substr].location != NSNotFound;
5460 std::string describe() const override {
5461 return "contains string: " + Catch::Detail::stringify(m_substr);
5465 struct StartsWith : StringHolder {
5466 StartsWith(NSString* substr) : StringHolder(substr) {}
5468 bool match(NSString* str) const override {
5469 return (str != nil || m_substr == nil) &&
5470 [str rangeOfString:m_substr].location == 0;
5473 std::string describe() const override {
5474 return "starts with: " + Catch::Detail::stringify(m_substr);
5477 struct EndsWith : StringHolder {
5478 EndsWith(NSString* substr) : StringHolder(substr) {}
5480 bool match(NSString* str) const override {
5481 return (str != nil || m_substr == nil) &&
5482 [str rangeOfString:m_substr].location ==
5483 [str length] - [m_substr length];
5486 std::string describe() const override {
5487 return "ends with: " + Catch::Detail::stringify(m_substr);
5491 } // namespace NSStringMatchers
5494 inline Impl::NSStringMatchers::Equals Equals(NSString* substr) {
5495 return Impl::NSStringMatchers::Equals(substr);
5498 inline Impl::NSStringMatchers::Contains Contains(NSString* substr) {
5499 return Impl::NSStringMatchers::Contains(substr);
5502 inline Impl::NSStringMatchers::StartsWith StartsWith(NSString* substr) {
5503 return Impl::NSStringMatchers::StartsWith(substr);
5506 inline Impl::NSStringMatchers::EndsWith EndsWith(NSString* substr) {
5507 return Impl::NSStringMatchers::EndsWith(substr);
5510 } // namespace Matchers
5512 using namespace Matchers;
5514 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5516 } // namespace Catch
5518 ///////////////////////////////////////////////////////////////////////////////
5519 #define OC_MAKE_UNIQUE_NAME(root, uniqueSuffix) root##uniqueSuffix
5520 #define OC_TEST_CASE2(name, desc, uniqueSuffix) \
5521 +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Name_test_, uniqueSuffix) { \
5524 +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Description_test_, uniqueSuffix) { \
5527 -(void)OC_MAKE_UNIQUE_NAME(Catch_TestCase_test_, uniqueSuffix)
5529 #define OC_TEST_CASE(name, desc) OC_TEST_CASE2(name, desc, __LINE__)
5531 // end catch_objc.hpp
5534 // Benchmarking needs the externally-facing parts of reporters to work
5535 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5536 // start catch_external_interfaces.h
5538 // start catch_reporter_bases.hpp
5540 // start catch_interfaces_reporter.h
5542 // start catch_config.hpp
5544 // start catch_test_spec_parser.h
5547 #pragma clang diagnostic push
5548 #pragma clang diagnostic ignored "-Wpadded"
5551 // start catch_test_spec.h
5554 #pragma clang diagnostic push
5555 #pragma clang diagnostic ignored "-Wpadded"
5558 // start catch_wildcard_pattern.h
5561 class WildcardPattern {
5562 enum WildcardPosition {
5564 WildcardAtStart = 1,
5566 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5570 WildcardPattern(std::string const& pattern, CaseSensitive::Choice caseSensitivity);
5571 virtual ~WildcardPattern() = default;
5572 virtual bool matches(std::string const& str) const;
5575 std::string normaliseString(std::string const& str) const;
5576 CaseSensitive::Choice m_caseSensitivity;
5577 WildcardPosition m_wildcard = NoWildcard;
5578 std::string m_pattern;
5580 } // namespace Catch
5582 // end catch_wildcard_pattern.h
5594 explicit Pattern(std::string const& name);
5596 virtual bool matches(TestCaseInfo const& testCase) const = 0;
5597 std::string const& name() const;
5600 std::string const m_name;
5602 using PatternPtr = std::shared_ptr<Pattern>;
5604 class NamePattern : public Pattern {
5606 explicit NamePattern(std::string const& name, std::string const& filterString);
5607 bool matches(TestCaseInfo const& testCase) const override;
5610 WildcardPattern m_wildcardPattern;
5613 class TagPattern : public Pattern {
5615 explicit TagPattern(std::string const& tag, std::string const& filterString);
5616 bool matches(TestCaseInfo const& testCase) const override;
5622 class ExcludedPattern : public Pattern {
5624 explicit ExcludedPattern(PatternPtr const& underlyingPattern);
5625 bool matches(TestCaseInfo const& testCase) const override;
5628 PatternPtr m_underlyingPattern;
5632 std::vector<PatternPtr> m_patterns;
5634 bool matches(TestCaseInfo const& testCase) const;
5635 std::string name() const;
5639 struct FilterMatch {
5641 std::vector<TestCase const*> tests;
5643 using Matches = std::vector<FilterMatch>;
5644 using vectorStrings = std::vector<std::string>;
5646 bool hasFilters() const;
5647 bool matches(TestCaseInfo const& testCase) const;
5648 Matches matchesByFilter(std::vector<TestCase> const& testCases,
5649 IConfig const& config) const;
5650 const vectorStrings& getInvalidArgs() const;
5653 std::vector<Filter> m_filters;
5654 std::vector<std::string> m_invalidArgs;
5655 friend class TestSpecParser;
5657 } // namespace Catch
5660 #pragma clang diagnostic pop
5663 // end catch_test_spec.h
5664 // start catch_interfaces_tag_alias_registry.h
5672 struct ITagAliasRegistry {
5673 virtual ~ITagAliasRegistry();
5674 // Nullptr if not present
5675 virtual TagAlias const* find(std::string const& alias) const = 0;
5676 virtual std::string expandAliases(std::string const& unexpandedTestSpec) const = 0;
5678 static ITagAliasRegistry const& get();
5681 } // end namespace Catch
5683 // end catch_interfaces_tag_alias_registry.h
5686 class TestSpecParser {
5687 enum Mode { None, Name, QuotedName, Tag, EscapedName };
5689 Mode lastMode = None;
5690 bool m_exclusion = false;
5691 std::size_t m_pos = 0;
5692 std::size_t m_realPatternPos = 0;
5694 std::string m_substring;
5695 std::string m_patternName;
5696 std::vector<std::size_t> m_escapeChars;
5697 TestSpec::Filter m_currentFilter;
5698 TestSpec m_testSpec;
5699 ITagAliasRegistry const* m_tagAliases = nullptr;
5702 TestSpecParser(ITagAliasRegistry const& tagAliases);
5704 TestSpecParser& parse(std::string const& arg);
5705 TestSpec testSpec();
5708 bool visitChar(char c);
5709 void startNewMode(Mode mode);
5710 bool processNoneChar(char c);
5711 void processNameChar(char c);
5712 bool processOtherChar(char c);
5715 bool isControlChar(char c) const;
5716 void saveLastMode();
5717 void revertBackToLastMode();
5721 // Handles common preprocessing of the pattern for name/tag patterns
5722 std::string preprocessPattern();
5723 // Adds the current pattern as a test name
5724 void addNamePattern();
5725 // Adds the current pattern as a tag
5726 void addTagPattern();
5728 inline void addCharToPattern(char c) {
5734 TestSpec parseTestSpec(std::string const& arg);
5736 } // namespace Catch
5739 #pragma clang diagnostic pop
5742 // end catch_test_spec_parser.h
5743 // Libstdc++ doesn't like incomplete classes for unique_ptr
5749 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5750 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5758 bool listTests = false;
5759 bool listTags = false;
5760 bool listReporters = false;
5761 bool listTestNamesOnly = false;
5763 bool showSuccessfulTests = false;
5764 bool shouldDebugBreak = false;
5765 bool noThrow = false;
5766 bool showHelp = false;
5767 bool showInvisibles = false;
5768 bool filenamesAsTags = false;
5769 bool libIdentify = false;
5771 int abortAfter = -1;
5772 unsigned int rngSeed = 0;
5774 bool benchmarkNoAnalysis = false;
5775 unsigned int benchmarkSamples = 100;
5776 double benchmarkConfidenceInterval = 0.95;
5777 unsigned int benchmarkResamples = 100000;
5778 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5780 Verbosity verbosity = Verbosity::Normal;
5781 WarnAbout::What warnings = WarnAbout::Nothing;
5782 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5783 double minDuration = -1;
5784 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5785 UseColour::YesOrNo useColour = UseColour::Auto;
5786 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5788 std::string outputFilename;
5790 std::string processName;
5791 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5792 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5794 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5795 #undef CATCH_CONFIG_DEFAULT_REPORTER
5797 std::vector<std::string> testsOrTags;
5798 std::vector<std::string> sectionsToRun;
5801 class Config : public IConfig {
5804 Config(ConfigData const& data);
5805 virtual ~Config() = default;
5807 std::string const& getFilename() const;
5809 bool listTests() const;
5810 bool listTestNamesOnly() const;
5811 bool listTags() const;
5812 bool listReporters() const;
5814 std::string getProcessName() const;
5815 std::string const& getReporterName() const;
5817 std::vector<std::string> const& getTestsOrTags() const override;
5818 std::vector<std::string> const& getSectionsToRun() const override;
5820 TestSpec const& testSpec() const override;
5821 bool hasTestFilters() const override;
5823 bool showHelp() const;
5825 // IConfig interface
5826 bool allowThrows() const override;
5827 std::ostream& stream() const override;
5828 std::string name() const override;
5829 bool includeSuccessfulResults() const override;
5830 bool warnAboutMissingAssertions() const override;
5831 bool warnAboutNoTests() const override;
5832 ShowDurations::OrNot showDurations() const override;
5833 double minDuration() const override;
5834 RunTests::InWhatOrder runOrder() const override;
5835 unsigned int rngSeed() const override;
5836 UseColour::YesOrNo useColour() const override;
5837 bool shouldDebugBreak() const override;
5838 int abortAfter() const override;
5839 bool showInvisibles() const override;
5840 Verbosity verbosity() const override;
5841 bool benchmarkNoAnalysis() const override;
5842 int benchmarkSamples() const override;
5843 double benchmarkConfidenceInterval() const override;
5844 unsigned int benchmarkResamples() const override;
5845 std::chrono::milliseconds benchmarkWarmupTime() const override;
5848 IStream const* openStream();
5851 std::unique_ptr<IStream const> m_stream;
5852 TestSpec m_testSpec;
5853 bool m_hasTestFilters = false;
5856 } // end namespace Catch
5858 // end catch_config.hpp
5859 // start catch_assertionresult.h
5865 struct AssertionResultData {
5866 AssertionResultData() = delete;
5868 AssertionResultData(ResultWas::OfType _resultType, LazyExpression const& _lazyExpression);
5870 std::string message;
5871 mutable std::string reconstructedExpression;
5872 LazyExpression lazyExpression;
5873 ResultWas::OfType resultType;
5875 std::string reconstructExpression() const;
5878 class AssertionResult {
5880 AssertionResult() = delete;
5881 AssertionResult(AssertionInfo const& info, AssertionResultData const& data);
5884 bool succeeded() const;
5885 ResultWas::OfType getResultType() const;
5886 bool hasExpression() const;
5887 bool hasMessage() const;
5888 std::string getExpression() const;
5889 std::string getExpressionInMacro() const;
5890 bool hasExpandedExpression() const;
5891 std::string getExpandedExpression() const;
5892 std::string getMessage() const;
5893 SourceLineInfo getSourceInfo() const;
5894 StringRef getTestMacroName() const;
5897 AssertionInfo m_info;
5898 AssertionResultData m_resultData;
5901 } // end namespace Catch
5903 // end catch_assertionresult.h
5904 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5905 // start catch_estimate.hpp
5907 // Statistics estimates
5910 namespace Benchmark {
5911 template <typename Duration> struct Estimate {
5913 Duration lower_bound;
5914 Duration upper_bound;
5915 double confidence_interval;
5917 template <typename Duration2> operator Estimate<Duration2>() const {
5918 return {point, lower_bound, upper_bound, confidence_interval};
5921 } // namespace Benchmark
5922 } // namespace Catch
5924 // end catch_estimate.hpp
5925 // start catch_outlier_classification.hpp
5927 // Outlier information
5930 namespace Benchmark {
5931 struct OutlierClassification {
5932 int samples_seen = 0;
5933 int low_severe = 0; // more than 3 times IQR below Q1
5934 int low_mild = 0; // 1.5 to 3 times IQR below Q1
5935 int high_mild = 0; // 1.5 to 3 times IQR above Q3
5936 int high_severe = 0; // more than 3 times IQR above Q3
5938 int total() const { return low_severe + low_mild + high_mild + high_severe; }
5940 } // namespace Benchmark
5941 } // namespace Catch
5943 // end catch_outlier_classification.hpp
5946 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5953 #include <algorithm>
5957 struct ReporterConfig {
5958 explicit ReporterConfig(IConfigPtr const& _fullConfig);
5960 ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream);
5962 std::ostream& stream() const;
5963 IConfigPtr fullConfig() const;
5966 std::ostream* m_stream;
5967 IConfigPtr m_fullConfig;
5970 struct ReporterPreferences {
5971 bool shouldRedirectStdOut = false;
5972 bool shouldReportAllAssertions = false;
5975 template <typename T> struct LazyStat : Option<T> {
5976 LazyStat& operator=(T const& _value) {
5977 Option<T>::operator=(_value);
5988 struct TestRunInfo {
5989 TestRunInfo(std::string const& _name);
5993 GroupInfo(std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount);
5996 std::size_t groupIndex;
5997 std::size_t groupsCounts;
6000 struct AssertionStats {
6001 AssertionStats(AssertionResult const& _assertionResult,
6002 std::vector<MessageInfo> const& _infoMessages,
6003 Totals const& _totals);
6005 AssertionStats(AssertionStats const&) = default;
6006 AssertionStats(AssertionStats&&) = default;
6007 AssertionStats& operator=(AssertionStats const&) = delete;
6008 AssertionStats& operator=(AssertionStats&&) = delete;
6009 virtual ~AssertionStats();
6011 AssertionResult assertionResult;
6012 std::vector<MessageInfo> infoMessages;
6016 struct SectionStats {
6017 SectionStats(SectionInfo const& _sectionInfo,
6018 Counts const& _assertions,
6019 double _durationInSeconds,
6020 bool _missingAssertions);
6021 SectionStats(SectionStats const&) = default;
6022 SectionStats(SectionStats&&) = default;
6023 SectionStats& operator=(SectionStats const&) = default;
6024 SectionStats& operator=(SectionStats&&) = default;
6025 virtual ~SectionStats();
6027 SectionInfo sectionInfo;
6029 double durationInSeconds;
6030 bool missingAssertions;
6033 struct TestCaseStats {
6034 TestCaseStats(TestCaseInfo const& _testInfo,
6035 Totals const& _totals,
6036 std::string const& _stdOut,
6037 std::string const& _stdErr,
6040 TestCaseStats(TestCaseStats const&) = default;
6041 TestCaseStats(TestCaseStats&&) = default;
6042 TestCaseStats& operator=(TestCaseStats const&) = default;
6043 TestCaseStats& operator=(TestCaseStats&&) = default;
6044 virtual ~TestCaseStats();
6046 TestCaseInfo testInfo;
6053 struct TestGroupStats {
6054 TestGroupStats(GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting);
6055 TestGroupStats(GroupInfo const& _groupInfo);
6057 TestGroupStats(TestGroupStats const&) = default;
6058 TestGroupStats(TestGroupStats&&) = default;
6059 TestGroupStats& operator=(TestGroupStats const&) = default;
6060 TestGroupStats& operator=(TestGroupStats&&) = default;
6061 virtual ~TestGroupStats();
6063 GroupInfo groupInfo;
6068 struct TestRunStats {
6069 TestRunStats(TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting);
6071 TestRunStats(TestRunStats const&) = default;
6072 TestRunStats(TestRunStats&&) = default;
6073 TestRunStats& operator=(TestRunStats const&) = default;
6074 TestRunStats& operator=(TestRunStats&&) = default;
6075 virtual ~TestRunStats();
6077 TestRunInfo runInfo;
6082 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6083 struct BenchmarkInfo {
6085 double estimatedDuration;
6088 unsigned int resamples;
6089 double clockResolution;
6093 template <class Duration> struct BenchmarkStats {
6096 std::vector<Duration> samples;
6097 Benchmark::Estimate<Duration> mean;
6098 Benchmark::Estimate<Duration> standardDeviation;
6099 Benchmark::OutlierClassification outliers;
6100 double outlierVariance;
6102 template <typename Duration2> operator BenchmarkStats<Duration2>() const {
6103 std::vector<Duration2> samples2;
6104 samples2.reserve(samples.size());
6105 std::transform(samples.begin(),
6107 std::back_inserter(samples2),
6108 [](Duration d) { return Duration2(d); });
6111 std::move(samples2),
6119 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6121 struct IStreamingReporter {
6122 virtual ~IStreamingReporter() = default;
6124 // Implementing class must also provide the following static methods:
6125 // static std::string getDescription();
6126 // static std::set<Verbosity> getSupportedVerbosities()
6128 virtual ReporterPreferences getPreferences() const = 0;
6130 virtual void noMatchingTestCases(std::string const& spec) = 0;
6132 virtual void reportInvalidArguments(std::string const&) {}
6134 virtual void testRunStarting(TestRunInfo const& testRunInfo) = 0;
6135 virtual void testGroupStarting(GroupInfo const& groupInfo) = 0;
6137 virtual void testCaseStarting(TestCaseInfo const& testInfo) = 0;
6138 virtual void sectionStarting(SectionInfo const& sectionInfo) = 0;
6140 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6141 virtual void benchmarkPreparing(std::string const&) {}
6142 virtual void benchmarkStarting(BenchmarkInfo const&) {}
6143 virtual void benchmarkEnded(BenchmarkStats<> const&) {}
6144 virtual void benchmarkFailed(std::string const&) {}
6145 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6147 virtual void assertionStarting(AssertionInfo const& assertionInfo) = 0;
6149 // The return value indicates if the messages buffer should be cleared:
6150 virtual bool assertionEnded(AssertionStats const& assertionStats) = 0;
6152 virtual void sectionEnded(SectionStats const& sectionStats) = 0;
6153 virtual void testCaseEnded(TestCaseStats const& testCaseStats) = 0;
6154 virtual void testGroupEnded(TestGroupStats const& testGroupStats) = 0;
6155 virtual void testRunEnded(TestRunStats const& testRunStats) = 0;
6157 virtual void skipTest(TestCaseInfo const& testInfo) = 0;
6159 // Default empty implementation provided
6160 virtual void fatalErrorEncountered(StringRef name);
6162 virtual bool isMulti() const;
6164 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
6166 struct IReporterFactory {
6167 virtual ~IReporterFactory();
6168 virtual IStreamingReporterPtr create(ReporterConfig const& config) const = 0;
6169 virtual std::string getDescription() const = 0;
6171 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
6173 struct IReporterRegistry {
6174 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
6175 using Listeners = std::vector<IReporterFactoryPtr>;
6177 virtual ~IReporterRegistry();
6178 virtual IStreamingReporterPtr create(std::string const& name,
6179 IConfigPtr const& config) const = 0;
6180 virtual FactoryMap const& getFactories() const = 0;
6181 virtual Listeners const& getListeners() const = 0;
6184 } // end namespace Catch
6186 // end catch_interfaces_reporter.h
6187 #include <algorithm>
6196 void prepareExpandedExpression(AssertionResult& result);
6198 // Returns double formatted as %.3f (format expected on output)
6199 std::string getFormattedDuration(double duration);
6201 //! Should the reporter show
6202 bool shouldShowDuration(IConfig const& config, double duration);
6204 std::string serializeFilters(std::vector<std::string> const& container);
6206 template <typename DerivedT> struct StreamingReporterBase : IStreamingReporter {
6208 StreamingReporterBase(ReporterConfig const& _config) :
6209 m_config(_config.fullConfig()), stream(_config.stream()) {
6210 m_reporterPrefs.shouldRedirectStdOut = false;
6211 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6212 CATCH_ERROR("Verbosity level not supported by this reporter");
6215 ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6217 static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6219 ~StreamingReporterBase() override = default;
6221 void noMatchingTestCases(std::string const&) override {}
6223 void reportInvalidArguments(std::string const&) override {}
6225 void testRunStarting(TestRunInfo const& _testRunInfo) override {
6226 currentTestRunInfo = _testRunInfo;
6229 void testGroupStarting(GroupInfo const& _groupInfo) override {
6230 currentGroupInfo = _groupInfo;
6233 void testCaseStarting(TestCaseInfo const& _testInfo) override {
6234 currentTestCaseInfo = _testInfo;
6236 void sectionStarting(SectionInfo const& _sectionInfo) override {
6237 m_sectionStack.push_back(_sectionInfo);
6240 void sectionEnded(SectionStats const& /* _sectionStats */) override {
6241 m_sectionStack.pop_back();
6243 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
6244 currentTestCaseInfo.reset();
6246 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
6247 currentGroupInfo.reset();
6249 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
6250 currentTestCaseInfo.reset();
6251 currentGroupInfo.reset();
6252 currentTestRunInfo.reset();
6255 void skipTest(TestCaseInfo const&) override {
6256 // Don't do anything with this by default.
6257 // It can optionally be overridden in the derived class.
6260 IConfigPtr m_config;
6261 std::ostream& stream;
6263 LazyStat<TestRunInfo> currentTestRunInfo;
6264 LazyStat<GroupInfo> currentGroupInfo;
6265 LazyStat<TestCaseInfo> currentTestCaseInfo;
6267 std::vector<SectionInfo> m_sectionStack;
6268 ReporterPreferences m_reporterPrefs;
6271 template <typename DerivedT> struct CumulativeReporterBase : IStreamingReporter {
6272 template <typename T, typename ChildNodeT> struct Node {
6273 explicit Node(T const& _value) : value(_value) {}
6276 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
6278 ChildNodes children;
6280 struct SectionNode {
6281 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
6282 virtual ~SectionNode() = default;
6284 bool operator==(SectionNode const& other) const {
6285 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
6287 bool operator==(std::shared_ptr<SectionNode> const& other) const {
6288 return operator==(*other);
6292 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
6293 using Assertions = std::vector<AssertionStats>;
6294 ChildSections childSections;
6295 Assertions assertions;
6300 struct BySectionInfo {
6301 BySectionInfo(SectionInfo const& other) : m_other(other) {}
6302 BySectionInfo(BySectionInfo const& other) : m_other(other.m_other) {}
6303 bool operator()(std::shared_ptr<SectionNode> const& node) const {
6304 return ((node->stats.sectionInfo.name == m_other.name) &&
6305 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
6307 void operator=(BySectionInfo const&) = delete;
6310 SectionInfo const& m_other;
6313 using TestCaseNode = Node<TestCaseStats, SectionNode>;
6314 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
6315 using TestRunNode = Node<TestRunStats, TestGroupNode>;
6317 CumulativeReporterBase(ReporterConfig const& _config) :
6318 m_config(_config.fullConfig()), stream(_config.stream()) {
6319 m_reporterPrefs.shouldRedirectStdOut = false;
6320 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6321 CATCH_ERROR("Verbosity level not supported by this reporter");
6323 ~CumulativeReporterBase() override = default;
6325 ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6327 static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6329 void testRunStarting(TestRunInfo const&) override {}
6330 void testGroupStarting(GroupInfo const&) override {}
6332 void testCaseStarting(TestCaseInfo const&) override {}
6334 void sectionStarting(SectionInfo const& sectionInfo) override {
6335 SectionStats incompleteStats(sectionInfo, Counts(), 0, false);
6336 std::shared_ptr<SectionNode> node;
6337 if (m_sectionStack.empty()) {
6339 m_rootSection = std::make_shared<SectionNode>(incompleteStats);
6340 node = m_rootSection;
6342 SectionNode& parentNode = *m_sectionStack.back();
6343 auto it = std::find_if(parentNode.childSections.begin(),
6344 parentNode.childSections.end(),
6345 BySectionInfo(sectionInfo));
6346 if (it == parentNode.childSections.end()) {
6347 node = std::make_shared<SectionNode>(incompleteStats);
6348 parentNode.childSections.push_back(node);
6352 m_sectionStack.push_back(node);
6353 m_deepestSection = std::move(node);
6356 void assertionStarting(AssertionInfo const&) override {}
6358 bool assertionEnded(AssertionStats const& assertionStats) override {
6359 assert(!m_sectionStack.empty());
6360 // AssertionResult holds a pointer to a temporary
6361 // DecomposedExpression, which getExpandedExpression() calls to
6362 // build the expression string. Our section stack copy of the
6363 // assertionResult will likely outlive the temporary, so it must be
6364 // expanded or discarded now to avoid calling a destroyed object
6366 prepareExpandedExpression(const_cast<AssertionResult&>(assertionStats.assertionResult));
6367 SectionNode& sectionNode = *m_sectionStack.back();
6368 sectionNode.assertions.push_back(assertionStats);
6371 void sectionEnded(SectionStats const& sectionStats) override {
6372 assert(!m_sectionStack.empty());
6373 SectionNode& node = *m_sectionStack.back();
6374 node.stats = sectionStats;
6375 m_sectionStack.pop_back();
6377 void testCaseEnded(TestCaseStats const& testCaseStats) override {
6378 auto node = std::make_shared<TestCaseNode>(testCaseStats);
6379 assert(m_sectionStack.size() == 0);
6380 node->children.push_back(m_rootSection);
6381 m_testCases.push_back(node);
6382 m_rootSection.reset();
6384 assert(m_deepestSection);
6385 m_deepestSection->stdOut = testCaseStats.stdOut;
6386 m_deepestSection->stdErr = testCaseStats.stdErr;
6388 void testGroupEnded(TestGroupStats const& testGroupStats) override {
6389 auto node = std::make_shared<TestGroupNode>(testGroupStats);
6390 node->children.swap(m_testCases);
6391 m_testGroups.push_back(node);
6393 void testRunEnded(TestRunStats const& testRunStats) override {
6394 auto node = std::make_shared<TestRunNode>(testRunStats);
6395 node->children.swap(m_testGroups);
6396 m_testRuns.push_back(node);
6397 testRunEndedCumulative();
6399 virtual void testRunEndedCumulative() = 0;
6401 void skipTest(TestCaseInfo const&) override {}
6403 IConfigPtr m_config;
6404 std::ostream& stream;
6405 std::vector<AssertionStats> m_assertions;
6406 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
6407 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
6408 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
6410 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
6412 std::shared_ptr<SectionNode> m_rootSection;
6413 std::shared_ptr<SectionNode> m_deepestSection;
6414 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
6415 ReporterPreferences m_reporterPrefs;
6418 template <char C> char const* getLineOfChars() {
6419 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
6421 std::memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1);
6422 line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0;
6427 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
6428 TestEventListenerBase(ReporterConfig const& _config);
6430 static std::set<Verbosity> getSupportedVerbosities();
6432 void assertionStarting(AssertionInfo const&) override;
6433 bool assertionEnded(AssertionStats const&) override;
6436 } // end namespace Catch
6438 // end catch_reporter_bases.hpp
6439 // start catch_console_colour.h
6457 BrightRed = Bright | Red,
6458 BrightGreen = Bright | Green,
6459 LightGrey = Bright | Grey,
6460 BrightWhite = Bright | White,
6461 BrightYellow = Bright | Yellow,
6464 FileName = LightGrey,
6465 Warning = BrightYellow,
6466 ResultError = BrightRed,
6467 ResultSuccess = BrightGreen,
6468 ResultExpectedFailure = Warning,
6473 OriginalExpression = Cyan,
6474 ReconstructedExpression = BrightYellow,
6476 SecondaryText = LightGrey,
6480 // Use constructed object for RAII guard
6481 Colour(Code _colourCode);
6482 Colour(Colour&& other) noexcept;
6483 Colour& operator=(Colour&& other) noexcept;
6486 // Use static method for one-shot changes
6487 static void use(Code _colourCode);
6490 bool m_moved = false;
6493 std::ostream& operator<<(std::ostream& os, Colour const&);
6495 } // end namespace Catch
6497 // end catch_console_colour.h
6498 // start catch_reporter_registrars.hpp
6502 template <typename T> class ReporterRegistrar {
6504 class ReporterFactory : public IReporterFactory {
6506 IStreamingReporterPtr create(ReporterConfig const& config) const override {
6507 return std::unique_ptr<T>(new T(config));
6510 std::string getDescription() const override { return T::getDescription(); }
6514 explicit ReporterRegistrar(std::string const& name) {
6515 getMutableRegistryHub().registerReporter(name, std::make_shared<ReporterFactory>());
6519 template <typename T> class ListenerRegistrar {
6521 class ListenerFactory : public IReporterFactory {
6523 IStreamingReporterPtr create(ReporterConfig const& config) const override {
6524 return std::unique_ptr<T>(new T(config));
6526 std::string getDescription() const override { return std::string(); }
6530 ListenerRegistrar() {
6531 getMutableRegistryHub().registerListener(std::make_shared<ListenerFactory>());
6534 } // namespace Catch
6536 #if !defined(CATCH_CONFIG_DISABLE)
6538 #define CATCH_REGISTER_REPORTER(name, reporterType) \
6539 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6540 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6542 Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType(name); \
6544 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6546 #define CATCH_REGISTER_LISTENER(listenerType) \
6547 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6548 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6550 Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; \
6552 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6553 #else // CATCH_CONFIG_DISABLE
6555 #define CATCH_REGISTER_REPORTER(name, reporterType)
6556 #define CATCH_REGISTER_LISTENER(listenerType)
6558 #endif // CATCH_CONFIG_DISABLE
6560 // end catch_reporter_registrars.hpp
6561 // Allow users to base their work off existing reporters
6562 // start catch_reporter_compact.h
6566 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6568 using StreamingReporterBase::StreamingReporterBase;
6570 ~CompactReporter() override;
6572 static std::string getDescription();
6574 void noMatchingTestCases(std::string const& spec) override;
6576 void assertionStarting(AssertionInfo const&) override;
6578 bool assertionEnded(AssertionStats const& _assertionStats) override;
6580 void sectionEnded(SectionStats const& _sectionStats) override;
6582 void testRunEnded(TestRunStats const& _testRunStats) override;
6585 } // end namespace Catch
6587 // end catch_reporter_compact.h
6588 // start catch_reporter_console.h
6590 #if defined(_MSC_VER)
6591 #pragma warning(push)
6592 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in
6593 // switch Note that 4062 (not all labels are
6594 // handled and default is missing) is enabled
6599 struct SummaryColumn;
6602 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6603 std::unique_ptr<TablePrinter> m_tablePrinter;
6605 ConsoleReporter(ReporterConfig const& config);
6606 ~ConsoleReporter() override;
6607 static std::string getDescription();
6609 void noMatchingTestCases(std::string const& spec) override;
6611 void reportInvalidArguments(std::string const& arg) override;
6613 void assertionStarting(AssertionInfo const&) override;
6615 bool assertionEnded(AssertionStats const& _assertionStats) override;
6617 void sectionStarting(SectionInfo const& _sectionInfo) override;
6618 void sectionEnded(SectionStats const& _sectionStats) override;
6620 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6621 void benchmarkPreparing(std::string const& name) override;
6622 void benchmarkStarting(BenchmarkInfo const& info) override;
6623 void benchmarkEnded(BenchmarkStats<> const& stats) override;
6624 void benchmarkFailed(std::string const& error) override;
6625 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6627 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6628 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6629 void testRunEnded(TestRunStats const& _testRunStats) override;
6630 void testRunStarting(TestRunInfo const& _testRunInfo) override;
6635 void lazyPrintWithoutClosingBenchmarkTable();
6636 void lazyPrintRunInfo();
6637 void lazyPrintGroupInfo();
6638 void printTestCaseAndSectionHeader();
6640 void printClosedHeader(std::string const& _name);
6641 void printOpenHeader(std::string const& _name);
6643 // if string has a : in first line will set indent to follow it on
6645 void printHeaderString(std::string const& _string, std::size_t indent = 0);
6647 void printTotals(Totals const& totals);
6648 void printSummaryRow(std::string const& label,
6649 std::vector<SummaryColumn> const& cols,
6652 void printTotalsDivider(Totals const& totals);
6653 void printSummaryDivider();
6654 void printTestFilters();
6657 bool m_headerPrinted = false;
6660 } // end namespace Catch
6662 #if defined(_MSC_VER)
6663 #pragma warning(pop)
6666 // end catch_reporter_console.h
6667 // start catch_reporter_junit.h
6669 // start catch_xmlwriter.h
6674 enum class XmlFormatting {
6680 XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs);
6681 XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs);
6685 enum ForWhat { ForTextNodes, ForAttributes };
6687 XmlEncode(std::string const& str, ForWhat forWhat = ForTextNodes);
6689 void encodeTo(std::ostream& os) const;
6691 friend std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode);
6700 class ScopedElement {
6702 ScopedElement(XmlWriter* writer, XmlFormatting fmt);
6704 ScopedElement(ScopedElement&& other) noexcept;
6705 ScopedElement& operator=(ScopedElement&& other) noexcept;
6709 ScopedElement& writeText(std::string const& text,
6710 XmlFormatting fmt = XmlFormatting::Newline |
6711 XmlFormatting::Indent);
6713 template <typename T>
6714 ScopedElement& writeAttribute(std::string const& name, T const& attribute) {
6715 m_writer->writeAttribute(name, attribute);
6720 mutable XmlWriter* m_writer = nullptr;
6721 XmlFormatting m_fmt;
6724 XmlWriter(std::ostream& os = Catch::cout());
6727 XmlWriter(XmlWriter const&) = delete;
6728 XmlWriter& operator=(XmlWriter const&) = delete;
6730 XmlWriter& startElement(std::string const& name,
6731 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6733 ScopedElement scopedElement(std::string const& name,
6734 XmlFormatting fmt = XmlFormatting::Newline |
6735 XmlFormatting::Indent);
6737 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6739 XmlWriter& writeAttribute(std::string const& name, std::string const& attribute);
6741 XmlWriter& writeAttribute(std::string const& name, bool attribute);
6743 template <typename T>
6744 XmlWriter& writeAttribute(std::string const& name, T const& attribute) {
6745 ReusableStringStream rss;
6747 return writeAttribute(name, rss.str());
6750 XmlWriter& writeText(std::string const& text,
6751 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6753 XmlWriter& writeComment(std::string const& text,
6754 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6756 void writeStylesheetRef(std::string const& url);
6758 XmlWriter& writeBlankLine();
6760 void ensureTagClosed();
6763 void applyFormatting(XmlFormatting fmt);
6765 void writeDeclaration();
6767 void newlineIfNecessary();
6769 bool m_tagIsOpen = false;
6770 bool m_needsNewline = false;
6771 std::vector<std::string> m_tags;
6772 std::string m_indent;
6776 } // namespace Catch
6778 // end catch_xmlwriter.h
6781 class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6783 JunitReporter(ReporterConfig const& _config);
6785 ~JunitReporter() override;
6787 static std::string getDescription();
6789 void noMatchingTestCases(std::string const& /*spec*/) override;
6791 void testRunStarting(TestRunInfo const& runInfo) override;
6793 void testGroupStarting(GroupInfo const& groupInfo) override;
6795 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6796 bool assertionEnded(AssertionStats const& assertionStats) override;
6798 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6800 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6802 void testRunEndedCumulative() override;
6804 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6806 void writeTestCase(TestCaseNode const& testCaseNode);
6808 void writeSection(std::string const& className,
6809 std::string const& rootName,
6810 SectionNode const& sectionNode,
6813 void writeAssertions(SectionNode const& sectionNode);
6814 void writeAssertion(AssertionStats const& stats);
6818 std::string stdOutForSuite;
6819 std::string stdErrForSuite;
6820 unsigned int unexpectedExceptions = 0;
6821 bool m_okToFail = false;
6824 } // end namespace Catch
6826 // end catch_reporter_junit.h
6827 // start catch_reporter_xml.h
6830 class XmlReporter : public StreamingReporterBase<XmlReporter> {
6832 XmlReporter(ReporterConfig const& _config);
6834 ~XmlReporter() override;
6836 static std::string getDescription();
6838 virtual std::string getStylesheetRef() const;
6840 void writeSourceInfo(SourceLineInfo const& sourceInfo);
6842 public: // StreamingReporterBase
6843 void noMatchingTestCases(std::string const& s) override;
6845 void testRunStarting(TestRunInfo const& testInfo) override;
6847 void testGroupStarting(GroupInfo const& groupInfo) override;
6849 void testCaseStarting(TestCaseInfo const& testInfo) override;
6851 void sectionStarting(SectionInfo const& sectionInfo) override;
6853 void assertionStarting(AssertionInfo const&) override;
6855 bool assertionEnded(AssertionStats const& assertionStats) override;
6857 void sectionEnded(SectionStats const& sectionStats) override;
6859 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6861 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6863 void testRunEnded(TestRunStats const& testRunStats) override;
6865 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6866 void benchmarkPreparing(std::string const& name) override;
6867 void benchmarkStarting(BenchmarkInfo const&) override;
6868 void benchmarkEnded(BenchmarkStats<> const&) override;
6869 void benchmarkFailed(std::string const&) override;
6870 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6873 Timer m_testCaseTimer;
6875 int m_sectionDepth = 0;
6878 } // end namespace Catch
6880 // end catch_reporter_xml.h
6882 // end catch_external_interfaces.h
6885 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6886 // start catch_benchmarking_all.hpp
6888 // A proxy header that includes all of the benchmarking headers to allow
6889 // concise include of the benchmarking features. You should prefer the
6890 // individual includes in standard use.
6892 // start catch_benchmark.hpp
6896 // start catch_chronometer.hpp
6898 // User-facing chronometer
6900 // start catch_clock.hpp
6908 namespace Benchmark {
6909 template <typename Clock> using ClockDuration = typename Clock::duration;
6910 template <typename Clock>
6911 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6913 template <typename Clock> using TimePoint = typename Clock::time_point;
6915 using default_clock = std::chrono::steady_clock;
6917 template <typename Clock> struct now {
6918 TimePoint<Clock> operator()() const { return Clock::now(); }
6921 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6922 } // namespace Benchmark
6923 } // namespace Catch
6925 // end catch_clock.hpp
6926 // start catch_optimizer.hpp
6928 // Hinting the optimizer
6930 #if defined(_MSC_VER)
6931 #include <atomic> // atomic_thread_fence
6935 namespace Benchmark {
6936 #if defined(__GNUC__) || defined(__clang__)
6937 template <typename T> inline void keep_memory(T* p) {
6938 asm volatile("" : : "g"(p) : "memory");
6940 inline void keep_memory() { asm volatile("" : : : "memory"); }
6943 inline void optimizer_barrier() { keep_memory(); }
6944 } // namespace Detail
6945 #elif defined(_MSC_VER)
6947 #pragma optimize("", off)
6948 template <typename T> inline void keep_memory(T* p) {
6949 // thanks @milleniumbug
6950 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6952 // TODO equivalent keep_memory()
6953 #pragma optimize("", on)
6956 inline void optimizer_barrier() { std::atomic_thread_fence(std::memory_order_seq_cst); }
6957 } // namespace Detail
6961 template <typename T> inline void deoptimize_value(T&& x) { keep_memory(&x); }
6963 template <typename Fn, typename... Args>
6964 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6965 typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6966 deoptimize_value(std::forward<Fn>(fn)(std::forward<Args...>(args...)));
6969 template <typename Fn, typename... Args>
6970 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6971 typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6972 std::forward<Fn>(fn)(std::forward<Args...>(args...));
6974 } // namespace Benchmark
6975 } // namespace Catch
6977 // end catch_optimizer.hpp
6978 // start catch_complete_invoke.hpp
6980 // Invoke with a special case for void
6982 #include <type_traits>
6986 namespace Benchmark {
6988 template <typename T> struct CompleteType { using type = T; };
6989 template <> struct CompleteType<void> {
6993 template <typename T> using CompleteType_t = typename CompleteType<T>::type;
6995 template <typename Result> struct CompleteInvoker {
6996 template <typename Fun, typename... Args>
6997 static Result invoke(Fun&& fun, Args&&... args) {
6998 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
7001 template <> struct CompleteInvoker<void> {
7002 template <typename Fun, typename... Args>
7003 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
7004 std::forward<Fun>(fun)(std::forward<Args>(args)...);
7009 // invoke and not return void :(
7010 template <typename Fun, typename... Args>
7011 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun,
7013 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(
7014 std::forward<Fun>(fun), std::forward<Args>(args)...);
7017 const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
7018 } // namespace Detail
7020 template <typename Fun>
7021 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
7022 CATCH_TRY { return Detail::complete_invoke(std::forward<Fun>(fun)); }
7024 getResultCapture().benchmarkFailed(translateActiveException());
7025 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
7028 } // namespace Benchmark
7029 } // namespace Catch
7031 // end catch_complete_invoke.hpp
7033 namespace Benchmark {
7035 struct ChronometerConcept {
7036 virtual void start() = 0;
7037 virtual void finish() = 0;
7038 virtual ~ChronometerConcept() = default;
7040 template <typename Clock> struct ChronometerModel final : public ChronometerConcept {
7041 void start() override { started = Clock::now(); }
7042 void finish() override { finished = Clock::now(); }
7044 ClockDuration<Clock> elapsed() const { return finished - started; }
7046 TimePoint<Clock> started;
7047 TimePoint<Clock> finished;
7049 } // namespace Detail
7051 struct Chronometer {
7053 template <typename Fun> void measure(Fun&& fun) {
7054 measure(std::forward<Fun>(fun), is_callable<Fun(int)>());
7057 int runs() const { return k; }
7059 Chronometer(Detail::ChronometerConcept& meter, int k) : impl(&meter), k(k) {}
7062 template <typename Fun> void measure(Fun&& fun, std::false_type) {
7063 measure([&fun](int) { return fun(); }, std::true_type());
7066 template <typename Fun> void measure(Fun&& fun, std::true_type) {
7067 Detail::optimizer_barrier();
7069 for (int i = 0; i < k; ++i)
7070 invoke_deoptimized(fun, i);
7072 Detail::optimizer_barrier();
7075 Detail::ChronometerConcept* impl;
7078 } // namespace Benchmark
7079 } // namespace Catch
7081 // end catch_chronometer.hpp
7082 // start catch_environment.hpp
7084 // Environment information
7087 namespace Benchmark {
7088 template <typename Duration> struct EnvironmentEstimate {
7090 OutlierClassification outliers;
7092 template <typename Duration2> operator EnvironmentEstimate<Duration2>() const {
7093 return {mean, outliers};
7096 template <typename Clock> struct Environment {
7097 using clock_type = Clock;
7098 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
7099 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
7101 } // namespace Benchmark
7102 } // namespace Catch
7104 // end catch_environment.hpp
7105 // start catch_execution_plan.hpp
7109 // start catch_benchmark_function.hpp
7111 // Dumb std::function implementation for consistent call overhead
7114 #include <type_traits>
7119 namespace Benchmark {
7121 template <typename T> using Decay = typename std::decay<T>::type;
7122 template <typename T, typename U>
7123 struct is_related : std::is_same<Decay<T>, Decay<U>> {};
7125 /// We need to reinvent std::function because every piece of code
7126 /// that might add overhead in a measurement context needs to have
7127 /// consistent performance characteristics so that we can account
7128 /// for it in the measurement. Implementations of std::function with
7129 /// optimizations that aren't always applicable, like small buffer
7130 /// optimizations, are not uncommon. This is effectively an
7131 /// implementation of std::function without any such optimizations;
7132 /// it may be slow, but it is consistently slow.
7133 struct BenchmarkFunction {
7136 virtual void call(Chronometer meter) const = 0;
7137 virtual callable* clone() const = 0;
7138 virtual ~callable() = default;
7140 template <typename Fun> struct model : public callable {
7141 model(Fun&& fun) : fun(std::move(fun)) {}
7142 model(Fun const& fun) : fun(fun) {}
7144 model<Fun>* clone() const override { return new model<Fun>(*this); }
7146 void call(Chronometer meter) const override {
7147 call(meter, is_callable<Fun(Chronometer)>());
7149 void call(Chronometer meter, std::true_type) const { fun(meter); }
7150 void call(Chronometer meter, std::false_type) const { meter.measure(fun); }
7156 void operator()() const {}
7159 template <typename T> BenchmarkFunction(model<T>* c) : f(c) {}
7162 BenchmarkFunction() : f(new model<do_nothing>{{}}) {}
7164 template <typename Fun,
7165 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
7167 BenchmarkFunction(Fun&& fun) :
7168 f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
7170 BenchmarkFunction(BenchmarkFunction&& that) : f(std::move(that.f)) {}
7172 BenchmarkFunction(BenchmarkFunction const& that) : f(that.f->clone()) {}
7174 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
7175 f = std::move(that.f);
7179 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
7180 f.reset(that.f->clone());
7184 void operator()(Chronometer meter) const { f->call(meter); }
7187 std::unique_ptr<callable> f;
7189 } // namespace Detail
7190 } // namespace Benchmark
7191 } // namespace Catch
7193 // end catch_benchmark_function.hpp
7194 // start catch_repeat.hpp
7198 #include <type_traits>
7202 namespace Benchmark {
7204 template <typename Fun> struct repeater {
7205 void operator()(int k) const {
7206 for (int i = 0; i < k; ++i) {
7212 template <typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
7213 return {std::forward<Fun>(fun)};
7215 } // namespace Detail
7216 } // namespace Benchmark
7217 } // namespace Catch
7219 // end catch_repeat.hpp
7220 // start catch_run_for_at_least.hpp
7222 // Run a function for a minimum amount of time
7224 // start catch_measure.hpp
7228 // start catch_timing.hpp
7233 #include <type_traits>
7236 namespace Benchmark {
7237 template <typename Duration, typename Result> struct Timing {
7242 template <typename Clock, typename Func, typename... Args>
7244 Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
7245 } // namespace Benchmark
7246 } // namespace Catch
7248 // end catch_timing.hpp
7252 namespace Benchmark {
7254 template <typename Clock, typename Fun, typename... Args>
7255 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
7256 auto start = Clock::now();
7257 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
7258 auto end = Clock::now();
7259 auto delta = end - start;
7260 return {delta, std::forward<decltype(r)>(r), 1};
7262 } // namespace Detail
7263 } // namespace Benchmark
7264 } // namespace Catch
7266 // end catch_measure.hpp
7268 #include <type_traits>
7271 namespace Benchmark {
7273 template <typename Clock, typename Fun>
7274 TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
7275 return Detail::measure<Clock>(fun, iters);
7277 template <typename Clock, typename Fun>
7278 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
7279 Detail::ChronometerModel<Clock> meter;
7280 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
7282 return {meter.elapsed(), std::move(result), iters};
7285 template <typename Clock, typename Fun>
7286 using run_for_at_least_argument_t = typename std::
7287 conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
7289 struct optimized_away_error : std::exception {
7290 const char* what() const noexcept override {
7291 return "could not measure benchmark, maybe it was "
7296 template <typename Clock, typename Fun>
7297 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>>
7298 run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
7300 while (iters < (1 << 30)) {
7301 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
7303 if (Timing.elapsed >= how_long) {
7304 return {Timing.elapsed, std::move(Timing.result), iters};
7308 Catch::throw_exception(optimized_away_error{});
7310 } // namespace Detail
7311 } // namespace Benchmark
7312 } // namespace Catch
7314 // end catch_run_for_at_least.hpp
7315 #include <algorithm>
7319 namespace Benchmark {
7320 template <typename Duration> struct ExecutionPlan {
7321 int iterations_per_sample;
7322 Duration estimated_duration;
7323 Detail::BenchmarkFunction benchmark;
7324 Duration warmup_time;
7325 int warmup_iterations;
7327 template <typename Duration2> operator ExecutionPlan<Duration2>() const {
7328 return {iterations_per_sample,
7335 template <typename Clock>
7336 std::vector<FloatDuration<Clock>> run(const IConfig& cfg,
7337 Environment<FloatDuration<Clock>> env) const {
7339 Detail::run_for_at_least<Clock>(
7340 std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time),
7342 Detail::repeat(now<Clock>{}));
7344 std::vector<FloatDuration<Clock>> times;
7345 times.reserve(cfg.benchmarkSamples());
7346 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
7347 Detail::ChronometerModel<Clock> model;
7348 this->benchmark(Chronometer(model, iterations_per_sample));
7349 auto sample_time = model.elapsed() - env.clock_cost.mean;
7350 if (sample_time < FloatDuration<Clock>::zero())
7351 sample_time = FloatDuration<Clock>::zero();
7352 return sample_time / iterations_per_sample;
7357 } // namespace Benchmark
7358 } // namespace Catch
7360 // end catch_execution_plan.hpp
7361 // start catch_estimate_clock.hpp
7363 // Environment measurement
7365 // start catch_stats.hpp
7367 // Statistical analysis tools
7369 #include <algorithm>
7370 #include <functional>
7381 namespace Benchmark {
7383 using sample = std::vector<double>;
7385 double weighted_average_quantile(int k,
7387 std::vector<double>::iterator first,
7388 std::vector<double>::iterator last);
7390 template <typename Iterator>
7391 OutlierClassification classify_outliers(Iterator first, Iterator last) {
7392 std::vector<double> copy(first, last);
7394 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
7395 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
7397 auto los = q1 - (iqr * 3.);
7398 auto lom = q1 - (iqr * 1.5);
7399 auto him = q3 + (iqr * 1.5);
7400 auto his = q3 + (iqr * 3.);
7402 OutlierClassification o;
7403 for (; first != last; ++first) {
7418 template <typename Iterator> double mean(Iterator first, Iterator last) {
7419 auto count = last - first;
7420 double sum = std::accumulate(first, last, 0.);
7424 template <typename URng, typename Iterator, typename Estimator>
7426 URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
7427 auto n = last - first;
7428 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7431 out.reserve(resamples);
7433 std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7434 std::vector<double> resampled;
7435 resampled.reserve(n);
7436 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
7437 return first[dist(rng)];
7439 return estimator(resampled.begin(), resampled.end());
7441 std::sort(out.begin(), out.end());
7445 template <typename Estimator, typename Iterator>
7446 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7447 auto n = last - first;
7448 auto second = std::next(first);
7452 for (auto it = first; it != last; ++it) {
7453 std::iter_swap(it, first);
7454 results.push_back(estimator(second, last));
7460 inline double normal_cdf(double x) { return std::erfc(-x / std::sqrt(2.0)) / 2.0; }
7462 double erfc_inv(double x);
7464 double normal_quantile(double p);
7466 template <typename Iterator, typename Estimator>
7467 Estimate<double> bootstrap(double confidence_level,
7470 sample const& resample,
7471 Estimator&& estimator) {
7472 auto n_samples = last - first;
7474 double point = estimator(first, last);
7475 // Degenerate case with a single sample
7477 return {point, point, point, confidence_level};
7479 sample jack = jackknife(estimator, first, last);
7480 double jack_mean = mean(jack.begin(), jack.end());
7481 double sum_squares, sum_cubes;
7482 std::tie(sum_squares, sum_cubes) =
7483 std::accumulate(jack.begin(),
7485 std::make_pair(0., 0.),
7486 [jack_mean](std::pair<double, double> sqcb,
7487 double x) -> std::pair<double, double> {
7488 auto d = jack_mean - x;
7491 return {sqcb.first + d2, sqcb.second + d3};
7494 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7495 int n = static_cast<int>(resample.size());
7496 double prob_n = std::count_if(resample.begin(),
7498 [point](double x) { return x < point; }) /
7500 // degenerate case with uniform samples
7502 return {point, point, point, confidence_level};
7504 double bias = normal_quantile(prob_n);
7505 double z1 = normal_quantile((1. - confidence_level) / 2.);
7507 auto cumn = [n](double x) -> int { return std::lround(normal_cdf(x) * n); };
7508 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7509 double b1 = bias + z1;
7510 double b2 = bias - z1;
7513 auto lo = (std::max)(cumn(a1), 0);
7514 auto hi = (std::min)(cumn(a2), n - 1);
7516 return {point, resample[lo], resample[hi], confidence_level};
7519 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7521 struct bootstrap_analysis {
7522 Estimate<double> mean;
7523 Estimate<double> standard_deviation;
7524 double outlier_variance;
7527 bootstrap_analysis analyse_samples(double confidence_level,
7529 std::vector<double>::iterator first,
7530 std::vector<double>::iterator last);
7531 } // namespace Detail
7532 } // namespace Benchmark
7533 } // namespace Catch
7535 // end catch_stats.hpp
7536 #include <algorithm>
7543 namespace Benchmark {
7545 template <typename Clock> std::vector<double> resolution(int k) {
7546 std::vector<TimePoint<Clock>> times;
7547 times.reserve(k + 1);
7548 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7550 std::vector<double> deltas;
7552 std::transform(std::next(times.begin()),
7555 std::back_inserter(deltas),
7556 [](TimePoint<Clock> a, TimePoint<Clock> b) {
7557 return static_cast<double>((a - b).count());
7563 const auto warmup_iterations = 10000;
7564 const auto warmup_time = std::chrono::milliseconds(100);
7565 const auto minimum_ticks = 1000;
7566 const auto warmup_seed = 10000;
7567 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7568 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7569 const auto clock_cost_estimation_tick_limit = 100000;
7570 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7571 const auto clock_cost_estimation_iterations = 10000;
7573 template <typename Clock> int warmup() {
7574 return run_for_at_least<Clock>(
7575 std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time),
7580 template <typename Clock>
7581 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7582 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(
7583 clock_resolution_estimation_time),
7588 FloatDuration<Clock>(mean(r.begin(), r.end())),
7589 classify_outliers(r.begin(), r.end()),
7592 template <typename Clock>
7593 EnvironmentEstimate<FloatDuration<Clock>>
7594 estimate_clock_cost(FloatDuration<Clock> resolution) {
7596 (std::min)(resolution * clock_cost_estimation_tick_limit,
7597 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7598 auto time_clock = [](int k) {
7599 return Detail::measure<Clock>([k] {
7600 for (int i = 0; i < k; ++i) {
7601 volatile auto ignored = Clock::now();
7608 int iters = clock_cost_estimation_iterations;
7609 auto&& r = run_for_at_least<Clock>(
7610 std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time),
7613 std::vector<double> times;
7614 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7615 times.reserve(nsamples);
7616 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7617 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7620 FloatDuration<Clock>(mean(times.begin(), times.end())),
7621 classify_outliers(times.begin(), times.end()),
7625 template <typename Clock> Environment<FloatDuration<Clock>> measure_environment() {
7626 static Environment<FloatDuration<Clock>>* env = nullptr;
7631 auto iters = Detail::warmup<Clock>();
7632 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7633 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7635 env = new Environment<FloatDuration<Clock>>{resolution, cost};
7638 } // namespace Detail
7639 } // namespace Benchmark
7640 } // namespace Catch
7642 // end catch_estimate_clock.hpp
7643 // start catch_analyse.hpp
7645 // Run and analyse one benchmark
7647 // start catch_sample_analysis.hpp
7649 // Benchmark results
7651 #include <algorithm>
7657 namespace Benchmark {
7658 template <typename Duration> struct SampleAnalysis {
7659 std::vector<Duration> samples;
7660 Estimate<Duration> mean;
7661 Estimate<Duration> standard_deviation;
7662 OutlierClassification outliers;
7663 double outlier_variance;
7665 template <typename Duration2> operator SampleAnalysis<Duration2>() const {
7666 std::vector<Duration2> samples2;
7667 samples2.reserve(samples.size());
7668 std::transform(samples.begin(),
7670 std::back_inserter(samples2),
7671 [](Duration d) { return Duration2(d); });
7673 std::move(samples2),
7681 } // namespace Benchmark
7682 } // namespace Catch
7684 // end catch_sample_analysis.hpp
7685 #include <algorithm>
7690 namespace Benchmark {
7692 template <typename Duration, typename Iterator>
7693 SampleAnalysis<Duration>
7694 analyse(const IConfig& cfg, Environment<Duration>, Iterator first, Iterator last) {
7695 if (!cfg.benchmarkNoAnalysis()) {
7696 std::vector<double> samples;
7697 samples.reserve(last - first);
7698 std::transform(first, last, std::back_inserter(samples), [](Duration d) {
7703 Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(),
7704 cfg.benchmarkResamples(),
7708 Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7710 auto wrap_estimate = [](Estimate<double> e) {
7711 return Estimate<Duration>{
7713 Duration(e.lower_bound),
7714 Duration(e.upper_bound),
7715 e.confidence_interval,
7718 std::vector<Duration> samples2;
7719 samples2.reserve(samples.size());
7720 std::transform(samples.begin(),
7722 std::back_inserter(samples2),
7723 [](double d) { return Duration(d); });
7725 std::move(samples2),
7726 wrap_estimate(analysis.mean),
7727 wrap_estimate(analysis.standard_deviation),
7729 analysis.outlier_variance,
7732 std::vector<Duration> samples;
7733 samples.reserve(last - first);
7735 Duration mean = Duration(0);
7737 for (auto it = first; it < last; ++it, ++i) {
7738 samples.push_back(Duration(*it));
7739 mean += Duration(*it);
7743 return {std::move(samples),
7744 Estimate<Duration>{mean, mean, mean, 0.0},
7745 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7746 OutlierClassification{},
7750 } // namespace Detail
7751 } // namespace Benchmark
7752 } // namespace Catch
7754 // end catch_analyse.hpp
7755 #include <algorithm>
7756 #include <functional>
7762 namespace Benchmark {
7764 Benchmark(std::string&& name) : name(std::move(name)) {}
7766 template <class FUN>
7767 Benchmark(std::string&& name, FUN&& func) :
7768 fun(std::move(func)), name(std::move(name)) {}
7770 template <typename Clock>
7771 ExecutionPlan<FloatDuration<Clock>>
7772 prepare(const IConfig& cfg, Environment<FloatDuration<Clock>> env) const {
7773 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7774 auto run_time = std::max(
7776 std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7777 auto&& test = Detail::run_for_at_least<Clock>(
7778 std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7780 static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7782 test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(),
7784 std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()),
7785 Detail::warmup_iterations};
7788 template <typename Clock = default_clock> void run() {
7789 IConfigPtr cfg = getCurrentContext().getConfig();
7791 auto env = Detail::measure_environment<Clock>();
7793 getResultCapture().benchmarkPreparing(name);
7795 auto plan = user_code([&] { return prepare<Clock>(*cfg, env); });
7797 BenchmarkInfo info{name,
7798 plan.estimated_duration.count(),
7799 plan.iterations_per_sample,
7800 cfg->benchmarkSamples(),
7801 cfg->benchmarkResamples(),
7802 env.clock_resolution.mean.count(),
7803 env.clock_cost.mean.count()};
7805 getResultCapture().benchmarkStarting(info);
7807 auto samples = user_code([&] { return plan.template run<Clock>(*cfg, env); });
7809 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7810 BenchmarkStats<FloatDuration<Clock>> stats{info,
7813 analysis.standard_deviation,
7815 analysis.outlier_variance};
7816 getResultCapture().benchmarkEnded(stats);
7819 if (translateActiveException() !=
7820 Detail::benchmarkErrorMsg) // benchmark errors have been
7821 // reported, otherwise
7823 std::rethrow_exception(std::current_exception());
7827 // sets lambda to be used in fun *and* executes benchmark!
7830 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
7831 Benchmark& operator=(Fun func) {
7832 fun = Detail::BenchmarkFunction(func);
7837 explicit operator bool() { return true; }
7840 Detail::BenchmarkFunction fun;
7843 } // namespace Benchmark
7844 } // namespace Catch
7846 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7847 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7849 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex) \
7850 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
7851 BenchmarkName = [&](int benchmarkIndex)
7853 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name) \
7854 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
7857 // end catch_benchmark.hpp
7858 // start catch_constructor.hpp
7860 // Constructor and destructor helpers
7862 #include <type_traits>
7865 namespace Benchmark {
7867 template <typename T, bool Destruct> struct ObjectStorage {
7869 typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7871 ObjectStorage() : data() {}
7873 ObjectStorage(const ObjectStorage& other) { new (&data) T(other.stored_object()); }
7875 ObjectStorage(ObjectStorage&& other) {
7876 new (&data) T(std::move(other.stored_object()));
7879 ~ObjectStorage() { destruct_on_exit<T>(); }
7881 template <typename... Args> void construct(Args&&... args) {
7882 new (&data) T(std::forward<Args>(args)...);
7885 template <bool AllowManualDestruction = !Destruct>
7886 typename std::enable_if<AllowManualDestruction>::type destruct() {
7887 stored_object().~T();
7891 // If this is a constructor benchmark, destruct the underlying
7893 template <typename U>
7894 void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) {
7898 template <typename U>
7899 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) {}
7901 T& stored_object() { return *static_cast<T*>(static_cast<void*>(&data)); }
7903 T const& stored_object() const {
7904 return *static_cast<T*>(static_cast<void*>(&data));
7909 } // namespace Detail
7911 template <typename T> using storage_for = Detail::ObjectStorage<T, true>;
7913 template <typename T> using destructable_object = Detail::ObjectStorage<T, false>;
7914 } // namespace Benchmark
7915 } // namespace Catch
7917 // end catch_constructor.hpp
7918 // end catch_benchmarking_all.hpp
7921 #endif // ! CATCH_CONFIG_IMPL_ONLY
7924 // start catch_impl.hpp
7927 #pragma clang diagnostic push
7928 #pragma clang diagnostic ignored "-Wweak-vtables"
7931 // Keep these here for external reporters
7932 // start catch_test_case_tracker.h
7939 namespace TestCaseTracking {
7941 struct NameAndLocation {
7943 SourceLineInfo location;
7945 NameAndLocation(std::string const& _name, SourceLineInfo const& _location);
7946 friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7947 return lhs.name == rhs.name && lhs.location == rhs.location;
7953 using ITrackerPtr = std::shared_ptr<ITracker>;
7956 NameAndLocation m_nameAndLocation;
7959 ITracker(NameAndLocation const& nameAndLoc) : m_nameAndLocation(nameAndLoc) {}
7962 NameAndLocation const& nameAndLocation() const { return m_nameAndLocation; }
7964 virtual ~ITracker();
7967 virtual bool isComplete() const = 0; // Successfully completed or failed
7968 virtual bool isSuccessfullyCompleted() const = 0;
7969 virtual bool isOpen() const = 0; // Started but not complete
7970 virtual bool hasChildren() const = 0;
7971 virtual bool hasStarted() const = 0;
7973 virtual ITracker& parent() = 0;
7976 virtual void close() = 0; // Successfully complete
7977 virtual void fail() = 0;
7978 virtual void markAsNeedingAnotherRun() = 0;
7980 virtual void addChild(ITrackerPtr const& child) = 0;
7981 virtual ITrackerPtr findChild(NameAndLocation const& nameAndLocation) = 0;
7982 virtual void openChild() = 0;
7985 virtual bool isSectionTracker() const = 0;
7986 virtual bool isGeneratorTracker() const = 0;
7989 class TrackerContext {
7991 enum RunState { NotStarted, Executing, CompletedCycle };
7993 ITrackerPtr m_rootTracker;
7994 ITracker* m_currentTracker = nullptr;
7995 RunState m_runState = NotStarted;
7998 ITracker& startRun();
8002 void completeCycle();
8004 bool completedCycle() const;
8005 ITracker& currentTracker();
8006 void setCurrentTracker(ITracker* tracker);
8009 class TrackerBase : public ITracker {
8016 CompletedSuccessfully,
8020 using Children = std::vector<ITrackerPtr>;
8021 TrackerContext& m_ctx;
8023 Children m_children;
8024 CycleState m_runState = NotStarted;
8027 TrackerBase(NameAndLocation const& nameAndLocation,
8028 TrackerContext& ctx,
8031 bool isComplete() const override;
8032 bool isSuccessfullyCompleted() const override;
8033 bool isOpen() const override;
8034 bool hasChildren() const override;
8035 bool hasStarted() const override { return m_runState != NotStarted; }
8037 void addChild(ITrackerPtr const& child) override;
8039 ITrackerPtr findChild(NameAndLocation const& nameAndLocation) override;
8040 ITracker& parent() override;
8042 void openChild() override;
8044 bool isSectionTracker() const override;
8045 bool isGeneratorTracker() const override;
8049 void close() override;
8050 void fail() override;
8051 void markAsNeedingAnotherRun() override;
8054 void moveToParent();
8058 class SectionTracker : public TrackerBase {
8059 std::vector<std::string> m_filters;
8060 std::string m_trimmed_name;
8063 SectionTracker(NameAndLocation const& nameAndLocation,
8064 TrackerContext& ctx,
8067 bool isSectionTracker() const override;
8069 bool isComplete() const override;
8071 static SectionTracker& acquire(TrackerContext& ctx,
8072 NameAndLocation const& nameAndLocation);
8076 void addInitialFilters(std::vector<std::string> const& filters);
8077 void addNextFilters(std::vector<std::string> const& filters);
8078 //! Returns filters active in this tracker
8079 std::vector<std::string> const& getFilters() const;
8080 //! Returns whitespace-trimmed name of the tracked section
8081 std::string const& trimmedName() const;
8084 } // namespace TestCaseTracking
8086 using TestCaseTracking::ITracker;
8087 using TestCaseTracking::SectionTracker;
8088 using TestCaseTracking::TrackerContext;
8090 } // namespace Catch
8092 // end catch_test_case_tracker.h
8094 // start catch_leak_detector.h
8098 struct LeakDetector {
8103 } // namespace Catch
8104 // end catch_leak_detector.h
8105 // Cpp files will be included in the single-header file here
8106 // start catch_stats.cpp
8108 // Statistical analysis tools
8110 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8115 #if defined(CATCH_CONFIG_USE_ASYNC)
8120 double erf_inv(double x) {
8121 // Code accompanying the article "Approximating the erfinv function" in
8122 // GPU Computing Gems, Volume 2
8125 w = -log((1.0 - x) * (1.0 + x));
8129 p = -3.6444120640178196996e-21;
8130 p = -1.685059138182016589e-19 + p * w;
8131 p = 1.2858480715256400167e-18 + p * w;
8132 p = 1.115787767802518096e-17 + p * w;
8133 p = -1.333171662854620906e-16 + p * w;
8134 p = 2.0972767875968561637e-17 + p * w;
8135 p = 6.6376381343583238325e-15 + p * w;
8136 p = -4.0545662729752068639e-14 + p * w;
8137 p = -8.1519341976054721522e-14 + p * w;
8138 p = 2.6335093153082322977e-12 + p * w;
8139 p = -1.2975133253453532498e-11 + p * w;
8140 p = -5.4154120542946279317e-11 + p * w;
8141 p = 1.051212273321532285e-09 + p * w;
8142 p = -4.1126339803469836976e-09 + p * w;
8143 p = -2.9070369957882005086e-08 + p * w;
8144 p = 4.2347877827932403518e-07 + p * w;
8145 p = -1.3654692000834678645e-06 + p * w;
8146 p = -1.3882523362786468719e-05 + p * w;
8147 p = 0.0001867342080340571352 + p * w;
8148 p = -0.00074070253416626697512 + p * w;
8149 p = -0.0060336708714301490533 + p * w;
8150 p = 0.24015818242558961693 + p * w;
8151 p = 1.6536545626831027356 + p * w;
8152 } else if (w < 16.000000) {
8153 w = sqrt(w) - 3.250000;
8154 p = 2.2137376921775787049e-09;
8155 p = 9.0756561938885390979e-08 + p * w;
8156 p = -2.7517406297064545428e-07 + p * w;
8157 p = 1.8239629214389227755e-08 + p * w;
8158 p = 1.5027403968909827627e-06 + p * w;
8159 p = -4.013867526981545969e-06 + p * w;
8160 p = 2.9234449089955446044e-06 + p * w;
8161 p = 1.2475304481671778723e-05 + p * w;
8162 p = -4.7318229009055733981e-05 + p * w;
8163 p = 6.8284851459573175448e-05 + p * w;
8164 p = 2.4031110387097893999e-05 + p * w;
8165 p = -0.0003550375203628474796 + p * w;
8166 p = 0.00095328937973738049703 + p * w;
8167 p = -0.0016882755560235047313 + p * w;
8168 p = 0.0024914420961078508066 + p * w;
8169 p = -0.0037512085075692412107 + p * w;
8170 p = 0.005370914553590063617 + p * w;
8171 p = 1.0052589676941592334 + p * w;
8172 p = 3.0838856104922207635 + p * w;
8174 w = sqrt(w) - 5.000000;
8175 p = -2.7109920616438573243e-11;
8176 p = -2.5556418169965252055e-10 + p * w;
8177 p = 1.5076572693500548083e-09 + p * w;
8178 p = -3.7894654401267369937e-09 + p * w;
8179 p = 7.6157012080783393804e-09 + p * w;
8180 p = -1.4960026627149240478e-08 + p * w;
8181 p = 2.9147953450901080826e-08 + p * w;
8182 p = -6.7711997758452339498e-08 + p * w;
8183 p = 2.2900482228026654717e-07 + p * w;
8184 p = -9.9298272942317002539e-07 + p * w;
8185 p = 4.5260625972231537039e-06 + p * w;
8186 p = -1.9681778105531670567e-05 + p * w;
8187 p = 7.5995277030017761139e-05 + p * w;
8188 p = -0.00021503011930044477347 + p * w;
8189 p = -0.00013871931833623122026 + p * w;
8190 p = 1.0103004648645343977 + p * w;
8191 p = 4.8499064014085844221 + p * w;
8196 double standard_deviation(std::vector<double>::iterator first,
8197 std::vector<double>::iterator last) {
8198 auto m = Catch::Benchmark::Detail::mean(first, last);
8199 double variance = std::accumulate(first,
8202 [m](double a, double b) {
8203 double diff = b - m;
8204 return a + diff * diff;
8207 return std::sqrt(variance);
8213 namespace Benchmark {
8216 double weighted_average_quantile(int k,
8218 std::vector<double>::iterator first,
8219 std::vector<double>::iterator last) {
8220 auto count = last - first;
8221 double idx = (count - 1) * k / static_cast<double>(q);
8222 int j = static_cast<int>(idx);
8224 std::nth_element(first, first + j, last);
8229 auto xj1 = *std::min_element(first + (j + 1), last);
8230 return xj + g * (xj1 - xj);
8233 double erfc_inv(double x) { return erf_inv(1.0 - x); }
8235 double normal_quantile(double p) {
8236 static const double ROOT_TWO = std::sqrt(2.0);
8238 double result = 0.0;
8239 assert(p >= 0 && p <= 1);
8240 if (p < 0 || p > 1) {
8244 result = -erfc_inv(2.0 * p);
8245 // result *= normal distribution standard deviation (1.0) *
8247 result *= /*sd * */ ROOT_TWO;
8248 // result += normal disttribution mean (0)
8252 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
8253 double sb = stddev.point;
8254 double mn = mean.point / n;
8255 double mg_min = mn / 2.;
8256 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
8257 double sg2 = sg * sg;
8258 double sb2 = sb * sb;
8260 auto c_max = [n, mn, sb2, sg2](double x) -> double {
8264 double k0 = -n * nd;
8265 double k1 = sb2 - n * sg2 + nd;
8266 double det = k1 * k1 - 4 * sg2 * k0;
8267 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
8270 auto var_out = [n, sb2, sg2](double c) {
8272 return (nc / n) * (sb2 - nc * sg2);
8275 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
8278 bootstrap_analysis analyse_samples(double confidence_level,
8280 std::vector<double>::iterator first,
8281 std::vector<double>::iterator last) {
8282 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
8283 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
8284 static std::random_device entropy;
8285 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
8287 auto n = static_cast<int>(last - first); // seriously, one can't use integral types
8288 // without hell in C++
8290 auto mean = &Detail::mean<std::vector<double>::iterator>;
8291 auto stddev = &standard_deviation;
8293 #if defined(CATCH_CONFIG_USE_ASYNC)
8295 [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
8296 auto seed = entropy();
8297 return std::async(std::launch::async, [=] {
8298 std::mt19937 rng(seed);
8299 auto resampled = resample(rng, n_resamples, first, last, f);
8300 return bootstrap(confidence_level, first, last, resampled, f);
8304 auto mean_future = Estimate(mean);
8305 auto stddev_future = Estimate(stddev);
8307 auto mean_estimate = mean_future.get();
8308 auto stddev_estimate = stddev_future.get();
8311 [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
8312 auto seed = entropy();
8313 std::mt19937 rng(seed);
8314 auto resampled = resample(rng, n_resamples, first, last, f);
8315 return bootstrap(confidence_level, first, last, resampled, f);
8318 auto mean_estimate = Estimate(mean);
8319 auto stddev_estimate = Estimate(stddev);
8320 #endif // CATCH_USE_ASYNC
8322 double outlier_variance =
8323 Detail::outlier_variance(mean_estimate, stddev_estimate, n);
8325 return {mean_estimate, stddev_estimate, outlier_variance};
8327 } // namespace Detail
8328 } // namespace Benchmark
8329 } // namespace Catch
8331 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8332 // end catch_stats.cpp
8333 // start catch_approx.cpp
8340 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
8341 // But without the subtraction to allow for INFINITY in comparison
8342 bool marginComparison(double lhs, double rhs, double margin) {
8343 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
8351 Approx::Approx(double value) :
8352 m_epsilon(std::numeric_limits<float>::epsilon() * 100),
8357 Approx Approx::custom() { return Approx(0); }
8359 Approx Approx::operator-() const {
8361 temp.m_value = -temp.m_value;
8365 std::string Approx::toString() const {
8366 ReusableStringStream rss;
8367 rss << "Approx( " << ::Catch::Detail::stringify(m_value) << " )";
8371 bool Approx::equalityComparisonImpl(const double other) const {
8372 // First try with fixed margin, then compute margin based on
8373 // epsilon, scale and Approx's value Thanks to Richard Harris for
8374 // his help refining the scaled margin value
8375 return marginComparison(m_value, other, m_margin) ||
8376 marginComparison(m_value,
8379 (m_scale + std::fabs(std::isinf(m_value) ? 0 : m_value)));
8382 void Approx::setMargin(double newMargin) {
8383 CATCH_ENFORCE(newMargin >= 0,
8384 "Invalid Approx::margin: " << newMargin << '.'
8385 << " Approx::Margin has to be non-negative.");
8386 m_margin = newMargin;
8389 void Approx::setEpsilon(double newEpsilon) {
8390 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
8391 "Invalid Approx::epsilon: " << newEpsilon << '.'
8392 << " Approx::epsilon has to be in [0, 1]");
8393 m_epsilon = newEpsilon;
8396 } // end namespace Detail
8398 namespace literals {
8399 Detail::Approx operator"" _a(long double val) { return Detail::Approx(val); }
8400 Detail::Approx operator"" _a(unsigned long long val) { return Detail::Approx(val); }
8401 } // end namespace literals
8403 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
8404 return value.toString();
8407 } // end namespace Catch
8408 // end catch_approx.cpp
8409 // start catch_assertionhandler.cpp
8411 // start catch_debugger.h
8414 bool isDebuggerActive();
8417 #ifdef CATCH_PLATFORM_MAC
8419 #if defined(__i386__) || defined(__x86_64__)
8420 #define CATCH_TRAP() __asm__("int $3\n" : :) /* NOLINT */
8421 #elif defined(__aarch64__)
8422 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8425 #elif defined(CATCH_PLATFORM_IPHONE)
8427 // use inline assembler
8428 #if defined(__i386__) || defined(__x86_64__)
8429 #define CATCH_TRAP() __asm__("int $3")
8430 #elif defined(__aarch64__)
8431 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8432 #elif defined(__arm__) && !defined(__thumb__)
8433 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
8434 #elif defined(__arm__) && defined(__thumb__)
8435 #define CATCH_TRAP() __asm__(".inst 0xde01")
8438 #elif defined(CATCH_PLATFORM_LINUX)
8439 // If we can use inline assembler, do it because this allows us to break
8440 // directly at the location of the failing check instead of breaking inside
8441 // raise() called from it, i.e. one stack frame below.
8442 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
8443 #define CATCH_TRAP() asm volatile("int $3") /* NOLINT */
8444 #else // Fall back to the generic way.
8447 #define CATCH_TRAP() raise(SIGTRAP)
8449 #elif defined(_MSC_VER)
8450 #define CATCH_TRAP() __debugbreak()
8451 #elif defined(__MINGW32__)
8452 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
8453 #define CATCH_TRAP() DebugBreak()
8456 #ifndef CATCH_BREAK_INTO_DEBUGGER
8458 #define CATCH_BREAK_INTO_DEBUGGER() \
8460 if (Catch::isDebuggerActive()) { \
8465 #define CATCH_BREAK_INTO_DEBUGGER() [] {}()
8469 // end catch_debugger.h
8470 // start catch_run_context.h
8472 // start catch_fatal_condition.h
8478 // Wrapper for platform-specific fatal error (signals/SEH) handlers
8480 // Tries to be cooperative with other handlers, and not step over
8481 // other handlers. This means that unknown structured exceptions
8482 // are passed on, previous signal handlers are called, and so on.
8484 // Can only be instantiated once, and assumes that once a signal
8485 // is caught, the binary will end up terminating. Thus, there
8486 class FatalConditionHandler {
8487 bool m_started = false;
8489 // Install/disengage implementation for specific platform.
8490 // Should be if-defed to work on current platform, can assume
8491 // engage-disengage 1:1 pairing.
8492 void engage_platform();
8493 void disengage_platform();
8496 // Should also have platform-specific implementations as needed
8497 FatalConditionHandler();
8498 ~FatalConditionHandler();
8501 assert(!m_started && "Handler cannot be installed twice.");
8507 assert(m_started && "Handler cannot be uninstalled without being installed first");
8509 disengage_platform();
8513 //! Simple RAII guard for (dis)engaging the FatalConditionHandler
8514 class FatalConditionHandlerGuard {
8515 FatalConditionHandler* m_handler;
8518 FatalConditionHandlerGuard(FatalConditionHandler* handler) : m_handler(handler) {
8519 m_handler->engage();
8521 ~FatalConditionHandlerGuard() { m_handler->disengage(); }
8524 } // end namespace Catch
8526 // end catch_fatal_condition.h
8531 struct IMutableContext;
8533 ///////////////////////////////////////////////////////////////////////////
8535 class RunContext : public IResultCapture, public IRunner {
8538 RunContext(RunContext const&) = delete;
8539 RunContext& operator=(RunContext const&) = delete;
8541 explicit RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter);
8543 ~RunContext() override;
8545 void testGroupStarting(std::string const& testSpec,
8546 std::size_t groupIndex,
8547 std::size_t groupsCount);
8548 void testGroupEnded(std::string const& testSpec,
8549 Totals const& totals,
8550 std::size_t groupIndex,
8551 std::size_t groupsCount);
8553 Totals runTest(TestCase const& testCase);
8555 IConfigPtr config() const;
8556 IStreamingReporter& reporter() const;
8558 public: // IResultCapture
8559 // Assertion handlers
8560 void handleExpr(AssertionInfo const& info,
8561 ITransientExpression const& expr,
8562 AssertionReaction& reaction) override;
8563 void handleMessage(AssertionInfo const& info,
8564 ResultWas::OfType resultType,
8565 StringRef const& message,
8566 AssertionReaction& reaction) override;
8567 void handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
8568 AssertionReaction& reaction) override;
8569 void handleUnexpectedInflightException(AssertionInfo const& info,
8570 std::string const& message,
8571 AssertionReaction& reaction) override;
8572 void handleIncomplete(AssertionInfo const& info) override;
8573 void handleNonExpr(AssertionInfo const& info,
8574 ResultWas::OfType resultType,
8575 AssertionReaction& reaction) override;
8577 bool sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) override;
8579 void sectionEnded(SectionEndInfo const& endInfo) override;
8580 void sectionEndedEarly(SectionEndInfo const& endInfo) override;
8582 auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
8583 -> IGeneratorTracker& override;
8585 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8586 void benchmarkPreparing(std::string const& name) override;
8587 void benchmarkStarting(BenchmarkInfo const& info) override;
8588 void benchmarkEnded(BenchmarkStats<> const& stats) override;
8589 void benchmarkFailed(std::string const& error) override;
8590 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8592 void pushScopedMessage(MessageInfo const& message) override;
8593 void popScopedMessage(MessageInfo const& message) override;
8595 void emplaceUnscopedMessage(MessageBuilder const& builder) override;
8597 std::string getCurrentTestName() const override;
8599 const AssertionResult* getLastResult() const override;
8601 void exceptionEarlyReported() override;
8603 void handleFatalErrorCondition(StringRef message) override;
8605 bool lastAssertionPassed() override;
8607 void assertionPassed() override;
8610 // !TBD We need to do this another way!
8611 bool aborting() const final;
8614 void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr);
8615 void invokeActiveTestCase();
8617 void resetAssertionInfo();
8618 bool testForMissingAssertions(Counts& assertions);
8620 void assertionEnded(AssertionResult const& result);
8621 void reportExpr(AssertionInfo const& info,
8622 ResultWas::OfType resultType,
8623 ITransientExpression const* expr,
8626 void populateReaction(AssertionReaction& reaction);
8629 void handleUnfinishedSections();
8631 TestRunInfo m_runInfo;
8632 IMutableContext& m_context;
8633 TestCase const* m_activeTestCase = nullptr;
8634 ITracker* m_testCaseTracker = nullptr;
8635 Option<AssertionResult> m_lastResult;
8637 IConfigPtr m_config;
8639 IStreamingReporterPtr m_reporter;
8640 std::vector<MessageInfo> m_messages;
8641 std::vector<ScopedMessage>
8642 m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8643 AssertionInfo m_lastAssertionInfo;
8644 std::vector<SectionEndInfo> m_unfinishedSections;
8645 std::vector<ITracker*> m_activeSections;
8646 TrackerContext m_trackerContext;
8647 FatalConditionHandler m_fatalConditionhandler;
8648 bool m_lastAssertionPassed = false;
8649 bool m_shouldReportUnexpected = true;
8650 bool m_includeSuccessfulResults;
8653 void seedRng(IConfig const& config);
8654 unsigned int rngSeed();
8655 } // end namespace Catch
8657 // end catch_run_context.h
8661 auto operator<<(std::ostream& os, ITransientExpression const& expr) -> std::ostream& {
8662 expr.streamReconstructedExpression(os);
8667 LazyExpression::LazyExpression(bool isNegated) : m_isNegated(isNegated) {}
8669 LazyExpression::LazyExpression(LazyExpression const& other) : m_isNegated(other.m_isNegated) {}
8671 LazyExpression::operator bool() const { return m_transientExpression != nullptr; }
8673 auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& {
8674 if (lazyExpr.m_isNegated)
8678 if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
8679 os << "(" << *lazyExpr.m_transientExpression << ")";
8681 os << *lazyExpr.m_transientExpression;
8683 os << "{** error - unchecked empty expression requested **}";
8688 AssertionHandler::AssertionHandler(StringRef const& macroName,
8689 SourceLineInfo const& lineInfo,
8690 StringRef capturedExpression,
8691 ResultDisposition::Flags resultDisposition) :
8692 m_assertionInfo{macroName, lineInfo, capturedExpression, resultDisposition},
8693 m_resultCapture(getResultCapture()) {}
8695 void AssertionHandler::handleExpr(ITransientExpression const& expr) {
8696 m_resultCapture.handleExpr(m_assertionInfo, expr, m_reaction);
8698 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8699 m_resultCapture.handleMessage(m_assertionInfo, resultType, message, m_reaction);
8702 auto AssertionHandler::allowThrows() const -> bool {
8703 return getCurrentContext().getConfig()->allowThrows();
8706 void AssertionHandler::complete() {
8708 if (m_reaction.shouldDebugBreak) {
8710 // If you find your debugger stopping you here then go one level up
8711 // on the call-stack for the code that caused it (typically a failed
8714 // (To go back to the test and change execution, jump over the
8716 CATCH_BREAK_INTO_DEBUGGER();
8718 if (m_reaction.shouldThrow) {
8719 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8720 throw Catch::TestFailureException();
8722 CATCH_ERROR("Test failure requires aborting test!");
8726 void AssertionHandler::setCompleted() { m_completed = true; }
8728 void AssertionHandler::handleUnexpectedInflightException() {
8729 m_resultCapture.handleUnexpectedInflightException(
8730 m_assertionInfo, Catch::translateActiveException(), m_reaction);
8733 void AssertionHandler::handleExceptionThrownAsExpected() {
8734 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8736 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8737 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8740 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8741 m_resultCapture.handleUnexpectedExceptionNotThrown(m_assertionInfo, m_reaction);
8744 void AssertionHandler::handleThrowingCallSkipped() {
8745 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8748 // This is the overload that takes a string and infers the Equals matcher
8749 // from it The more general overload, that takes any string matcher, is in
8750 // catch_capture_matchers.cpp
8751 void handleExceptionMatchExpr(AssertionHandler& handler,
8752 std::string const& str,
8753 StringRef const& matcherString) {
8754 handleExceptionMatchExpr(handler, Matchers::Equals(str), matcherString);
8757 } // namespace Catch
8758 // end catch_assertionhandler.cpp
8759 // start catch_assertionresult.cpp
8762 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType,
8763 LazyExpression const& _lazyExpression) :
8764 lazyExpression(_lazyExpression), resultType(_resultType) {}
8766 std::string AssertionResultData::reconstructExpression() const {
8768 if (reconstructedExpression.empty()) {
8769 if (lazyExpression) {
8770 ReusableStringStream rss;
8771 rss << lazyExpression;
8772 reconstructedExpression = rss.str();
8775 return reconstructedExpression;
8778 AssertionResult::AssertionResult(AssertionInfo const& info, AssertionResultData const& data) :
8779 m_info(info), m_resultData(data) {}
8781 // Result was a success
8782 bool AssertionResult::succeeded() const { return Catch::isOk(m_resultData.resultType); }
8784 // Result was a success, or failure is suppressed
8785 bool AssertionResult::isOk() const {
8786 return Catch::isOk(m_resultData.resultType) ||
8787 shouldSuppressFailure(m_info.resultDisposition);
8790 ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; }
8792 bool AssertionResult::hasExpression() const { return !m_info.capturedExpression.empty(); }
8794 bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); }
8796 std::string AssertionResult::getExpression() const {
8797 // Possibly overallocating by 3 characters should be basically free
8799 expr.reserve(m_info.capturedExpression.size() + 3);
8800 if (isFalseTest(m_info.resultDisposition)) {
8803 expr += m_info.capturedExpression;
8804 if (isFalseTest(m_info.resultDisposition)) {
8810 std::string AssertionResult::getExpressionInMacro() const {
8812 if (m_info.macroName.empty())
8813 expr = static_cast<std::string>(m_info.capturedExpression);
8815 expr.reserve(m_info.macroName.size() + m_info.capturedExpression.size() + 4);
8816 expr += m_info.macroName;
8818 expr += m_info.capturedExpression;
8824 bool AssertionResult::hasExpandedExpression() const {
8825 return hasExpression() && getExpandedExpression() != getExpression();
8828 std::string AssertionResult::getExpandedExpression() const {
8829 std::string expr = m_resultData.reconstructExpression();
8830 return expr.empty() ? getExpression() : expr;
8833 std::string AssertionResult::getMessage() const { return m_resultData.message; }
8834 SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; }
8836 StringRef AssertionResult::getTestMacroName() const { return m_info.macroName; }
8838 } // end namespace Catch
8839 // end catch_assertionresult.cpp
8840 // start catch_capture_matchers.cpp
8844 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8846 // This is the general overload that takes a any string matcher
8847 // There is another overload, in catch_assertionhandler.h/.cpp, that only
8848 // takes a string and infers the Equals matcher (so the header does not
8849 // mention matchers)
8850 void handleExceptionMatchExpr(AssertionHandler& handler,
8851 StringMatcher const& matcher,
8852 StringRef const& matcherString) {
8853 std::string exceptionMessage = Catch::translateActiveException();
8854 MatchExpr<std::string, StringMatcher const&> expr(exceptionMessage, matcher, matcherString);
8855 handler.handleExpr(expr);
8858 } // namespace Catch
8859 // end catch_capture_matchers.cpp
8860 // start catch_commandline.cpp
8862 // start catch_commandline.h
8864 // start catch_clara.h
8866 // Use Catch's value for console width (store Clara's off to the side, if
8868 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8869 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8870 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8872 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1
8875 #pragma clang diagnostic push
8876 #pragma clang diagnostic ignored "-Wweak-vtables"
8877 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8878 #pragma clang diagnostic ignored "-Wshadow"
8882 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8884 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8885 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8887 // See https://github.com/philsquared/Clara for more details
8891 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8892 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8895 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8896 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8899 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8900 #ifdef __has_include
8901 #if __has_include(<optional>) && __cplusplus >= 201703L
8903 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8908 // ----------- #included from clara_textflow.hpp -----------
8912 // A single-header library for wrapping and laying out basic text, by Phil Nash
8914 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8915 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8917 // This project is hosted at https://github.com/philsquared/textflowcpp
8924 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8925 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8930 namespace TextFlow {
8932 inline auto isWhitespace(char c) -> bool {
8933 static std::string chars = " \t\n\r";
8934 return chars.find(c) != std::string::npos;
8936 inline auto isBreakableBefore(char c) -> bool {
8937 static std::string chars = "[({<|";
8938 return chars.find(c) != std::string::npos;
8940 inline auto isBreakableAfter(char c) -> bool {
8941 static std::string chars = "])}>.,:;*+-=&/\\";
8942 return chars.find(c) != std::string::npos;
8948 std::vector<std::string> m_strings;
8949 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8950 size_t m_indent = 0;
8951 size_t m_initialIndent = std::string::npos;
8957 Column const& m_column;
8958 size_t m_stringIndex = 0;
8963 bool m_suffix = false;
8965 iterator(Column const& column, size_t stringIndex) :
8966 m_column(column), m_stringIndex(stringIndex) {}
8968 auto line() const -> std::string const& {
8969 return m_column.m_strings[m_stringIndex];
8972 auto isBoundary(size_t at) const -> bool {
8974 assert(at <= line().size());
8976 return at == line().size() ||
8977 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8978 isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]);
8982 assert(m_stringIndex < m_column.m_strings.size());
8985 auto width = m_column.m_width - indent();
8987 if (line()[m_pos] == '\n') {
8990 while (m_end < line().size() && line()[m_end] != '\n')
8993 if (m_end < m_pos + width) {
8994 m_len = m_end - m_pos;
8997 while (len > 0 && !isBoundary(m_pos + len))
8999 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
9011 auto indent() const -> size_t {
9012 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent
9013 : std::string::npos;
9014 return initial == std::string::npos ? m_column.m_indent : initial;
9017 auto addIndentAndSuffix(std::string const& plain) const -> std::string {
9018 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
9022 using difference_type = std::ptrdiff_t;
9023 using value_type = std::string;
9024 using pointer = value_type*;
9025 using reference = value_type&;
9026 using iterator_category = std::forward_iterator_tag;
9028 explicit iterator(Column const& column) : m_column(column) {
9029 assert(m_column.m_width > m_column.m_indent);
9030 assert(m_column.m_initialIndent == std::string::npos ||
9031 m_column.m_width > m_column.m_initialIndent);
9034 m_stringIndex++; // Empty string
9037 auto operator*() const -> std::string {
9038 assert(m_stringIndex < m_column.m_strings.size());
9039 assert(m_pos <= m_end);
9040 return addIndentAndSuffix(line().substr(m_pos, m_len));
9043 auto operator++() -> iterator& {
9045 if (m_pos < line().size() && line()[m_pos] == '\n')
9048 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
9051 if (m_pos == line().size()) {
9055 if (m_stringIndex < m_column.m_strings.size())
9059 auto operator++(int) -> iterator {
9060 iterator prev(*this);
9065 auto operator==(iterator const& other) const -> bool {
9066 return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex &&
9067 &m_column == &other.m_column;
9069 auto operator!=(iterator const& other) const -> bool {
9070 return !operator==(other);
9073 using const_iterator = iterator;
9075 explicit Column(std::string const& text) { m_strings.push_back(text); }
9077 auto width(size_t newWidth) -> Column& {
9078 assert(newWidth > 0);
9082 auto indent(size_t newIndent) -> Column& {
9083 m_indent = newIndent;
9086 auto initialIndent(size_t newIndent) -> Column& {
9087 m_initialIndent = newIndent;
9091 auto width() const -> size_t { return m_width; }
9092 auto begin() const -> iterator { return iterator(*this); }
9093 auto end() const -> iterator { return {*this, m_strings.size()}; }
9095 inline friend std::ostream& operator<<(std::ostream& os, Column const& col) {
9097 for (auto line : col) {
9107 auto operator+(Column const& other) -> Columns;
9109 auto toString() const -> std::string {
9110 std::ostringstream oss;
9116 class Spacer : public Column {
9119 explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); }
9123 std::vector<Column> m_columns;
9130 std::vector<Column> const& m_columns;
9131 std::vector<Column::iterator> m_iterators;
9132 size_t m_activeIterators;
9134 iterator(Columns const& columns, EndTag) :
9135 m_columns(columns.m_columns), m_activeIterators(0) {
9136 m_iterators.reserve(m_columns.size());
9138 for (auto const& col : m_columns)
9139 m_iterators.push_back(col.end());
9143 using difference_type = std::ptrdiff_t;
9144 using value_type = std::string;
9145 using pointer = value_type*;
9146 using reference = value_type&;
9147 using iterator_category = std::forward_iterator_tag;
9149 explicit iterator(Columns const& columns) :
9150 m_columns(columns.m_columns), m_activeIterators(m_columns.size()) {
9151 m_iterators.reserve(m_columns.size());
9153 for (auto const& col : m_columns)
9154 m_iterators.push_back(col.begin());
9157 auto operator==(iterator const& other) const -> bool {
9158 return m_iterators == other.m_iterators;
9160 auto operator!=(iterator const& other) const -> bool {
9161 return m_iterators != other.m_iterators;
9163 auto operator*() const -> std::string {
9164 std::string row, padding;
9166 for (size_t i = 0; i < m_columns.size(); ++i) {
9167 auto width = m_columns[i].width();
9168 if (m_iterators[i] != m_columns[i].end()) {
9169 std::string col = *m_iterators[i];
9170 row += padding + col;
9171 if (col.size() < width)
9172 padding = std::string(width - col.size(), ' ');
9176 padding += std::string(width, ' ');
9181 auto operator++() -> iterator& {
9182 for (size_t i = 0; i < m_columns.size(); ++i) {
9183 if (m_iterators[i] != m_columns[i].end())
9188 auto operator++(int) -> iterator {
9189 iterator prev(*this);
9194 using const_iterator = iterator;
9196 auto begin() const -> iterator { return iterator(*this); }
9197 auto end() const -> iterator { return {*this, iterator::EndTag()}; }
9199 auto operator+=(Column const& col) -> Columns& {
9200 m_columns.push_back(col);
9203 auto operator+(Column const& col) -> Columns {
9204 Columns combined = *this;
9209 inline friend std::ostream& operator<<(std::ostream& os, Columns const& cols) {
9212 for (auto line : cols) {
9222 auto toString() const -> std::string {
9223 std::ostringstream oss;
9229 inline auto Column::operator+(Column const& other) -> Columns {
9235 } // namespace TextFlow
9237 } // namespace clara
9238 } // namespace Catch
9240 // ----------- end of #include from clara_textflow.hpp -----------
9241 // ........... back in clara.hpp
9247 #include <algorithm>
9249 #if !defined(CATCH_PLATFORM_WINDOWS) && \
9250 (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER))
9251 #define CATCH_PLATFORM_WINDOWS
9258 // Traits for extracting arg and return type of lambdas (for single
9259 // argument lambdas)
9260 template <typename L>
9261 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype(&L::operator())> {};
9263 template <typename ClassT, typename ReturnT, typename... Args>
9264 struct UnaryLambdaTraits<ReturnT (ClassT::*)(Args...) const> {
9265 static const bool isValid = false;
9268 template <typename ClassT, typename ReturnT, typename ArgT>
9269 struct UnaryLambdaTraits<ReturnT (ClassT::*)(ArgT) const> {
9270 static const bool isValid = true;
9272 typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
9273 using ReturnType = ReturnT;
9278 // Transport for raw args (copied from main args, or supplied via
9279 // init list for testing)
9282 std::string m_exeName;
9283 std::vector<std::string> m_args;
9286 Args(int argc, char const* const* argv) :
9287 m_exeName(argv[0]), m_args(argv + 1, argv + argc) {}
9289 Args(std::initializer_list<std::string> args) :
9290 m_exeName(*args.begin()), m_args(args.begin() + 1, args.end()) {}
9292 auto exeName() const -> std::string { return m_exeName; }
9295 // Wraps a token coming from a token stream. These may not directly
9296 // correspond to strings as a single string may encode an option +
9297 // its argument if the : or = form is used
9298 enum class TokenType { Option, Argument };
9304 inline auto isOptPrefix(char c) -> bool {
9306 #ifdef CATCH_PLATFORM_WINDOWS
9312 // Abstracts iterators into args as a stream of tokens, with option
9313 // arguments uniformly handled
9315 using Iterator = std::vector<std::string>::const_iterator;
9318 std::vector<Token> m_tokenBuffer;
9321 m_tokenBuffer.resize(0);
9323 // Skip any empty strings
9324 while (it != itEnd && it->empty())
9328 auto const& next = *it;
9329 if (isOptPrefix(next[0])) {
9330 auto delimiterPos = next.find_first_of(" :=");
9331 if (delimiterPos != std::string::npos) {
9332 m_tokenBuffer.push_back(
9333 {TokenType::Option, next.substr(0, delimiterPos)});
9334 m_tokenBuffer.push_back(
9335 {TokenType::Argument, next.substr(delimiterPos + 1)});
9337 if (next[1] != '-' && next.size() > 2) {
9338 std::string opt = "- ";
9339 for (size_t i = 1; i < next.size(); ++i) {
9341 m_tokenBuffer.push_back({TokenType::Option, opt});
9344 m_tokenBuffer.push_back({TokenType::Option, next});
9348 m_tokenBuffer.push_back({TokenType::Argument, next});
9354 explicit TokenStream(Args const& args) :
9355 TokenStream(args.m_args.begin(), args.m_args.end()) {}
9357 TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); }
9359 explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; }
9361 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
9363 auto operator*() const -> Token {
9364 assert(!m_tokenBuffer.empty());
9365 return m_tokenBuffer.front();
9368 auto operator->() const -> Token const* {
9369 assert(!m_tokenBuffer.empty());
9370 return &m_tokenBuffer.front();
9373 auto operator++() -> TokenStream& {
9374 if (m_tokenBuffer.size() >= 2) {
9375 m_tokenBuffer.erase(m_tokenBuffer.begin());
9387 enum Type { Ok, LogicError, RuntimeError };
9390 ResultBase(Type type) : m_type(type) {}
9391 virtual ~ResultBase() = default;
9393 virtual void enforceOk() const = 0;
9398 template <typename T> class ResultValueBase : public ResultBase {
9400 auto value() const -> T const& {
9406 ResultValueBase(Type type) : ResultBase(type) {}
9408 ResultValueBase(ResultValueBase const& other) : ResultBase(other) {
9409 if (m_type == ResultBase::Ok)
9410 new (&m_value) T(other.m_value);
9413 ResultValueBase(Type, T const& value) : ResultBase(Ok) { new (&m_value) T(value); }
9415 auto operator=(ResultValueBase const& other) -> ResultValueBase& {
9416 if (m_type == ResultBase::Ok)
9418 ResultBase::operator=(other);
9419 if (m_type == ResultBase::Ok)
9420 new (&m_value) T(other.m_value);
9424 ~ResultValueBase() override {
9434 template <> class ResultValueBase<void> : public ResultBase {
9436 using ResultBase::ResultBase;
9439 template <typename T = void> class BasicResult : public ResultValueBase<T> {
9441 template <typename U>
9442 explicit BasicResult(BasicResult<U> const& other) :
9443 ResultValueBase<T>(other.type()), m_errorMessage(other.errorMessage()) {
9444 assert(type() != ResultBase::Ok);
9447 template <typename U> static auto ok(U const& value) -> BasicResult {
9448 return {ResultBase::Ok, value};
9450 static auto ok() -> BasicResult { return {ResultBase::Ok}; }
9451 static auto logicError(std::string const& message) -> BasicResult {
9452 return {ResultBase::LogicError, message};
9454 static auto runtimeError(std::string const& message) -> BasicResult {
9455 return {ResultBase::RuntimeError, message};
9458 explicit operator bool() const { return m_type == ResultBase::Ok; }
9459 auto type() const -> ResultBase::Type { return m_type; }
9460 auto errorMessage() const -> std::string { return m_errorMessage; }
9463 void enforceOk() const override {
9465 // Errors shouldn't reach this point, but if they do
9466 // the actual error message will be in m_errorMessage
9467 assert(m_type != ResultBase::LogicError);
9468 assert(m_type != ResultBase::RuntimeError);
9469 if (m_type != ResultBase::Ok)
9473 std::string m_errorMessage; // Only populated if resultType is an error
9475 BasicResult(ResultBase::Type type, std::string const& message) :
9476 ResultValueBase<T>(type), m_errorMessage(message) {
9477 assert(m_type != ResultBase::Ok);
9480 using ResultValueBase<T>::ResultValueBase;
9481 using ResultBase::m_type;
9484 enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame };
9488 ParseState(ParseResultType type, TokenStream const& remainingTokens) :
9489 m_type(type), m_remainingTokens(remainingTokens) {}
9491 auto type() const -> ParseResultType { return m_type; }
9492 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9495 ParseResultType m_type;
9496 TokenStream m_remainingTokens;
9499 using Result = BasicResult<void>;
9500 using ParserResult = BasicResult<ParseResultType>;
9501 using InternalParseResult = BasicResult<ParseState>;
9503 struct HelpColumns {
9508 template <typename T>
9509 inline auto convertInto(std::string const& source, T& target) -> ParserResult {
9510 std::stringstream ss;
9514 return ParserResult::runtimeError("Unable to convert '" + source +
9515 "' to destination type");
9517 return ParserResult::ok(ParseResultType::Matched);
9519 inline auto convertInto(std::string const& source, std::string& target)
9522 return ParserResult::ok(ParseResultType::Matched);
9524 inline auto convertInto(std::string const& source, bool& target) -> ParserResult {
9525 std::string srcLC = source;
9526 std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(), [](unsigned char c) {
9527 return static_cast<char>(std::tolower(c));
9529 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" ||
9532 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" ||
9536 return ParserResult::runtimeError(
9537 "Expected a boolean value but did not recognise: '" + source + "'");
9538 return ParserResult::ok(ParseResultType::Matched);
9540 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9541 template <typename T>
9542 inline auto convertInto(std::string const& source,
9543 CLARA_CONFIG_OPTIONAL_TYPE<T>& target) -> ParserResult {
9545 auto result = convertInto(source, temp);
9547 target = std::move(temp);
9550 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9552 struct NonCopyable {
9553 NonCopyable() = default;
9554 NonCopyable(NonCopyable const&) = delete;
9555 NonCopyable(NonCopyable&&) = delete;
9556 NonCopyable& operator=(NonCopyable const&) = delete;
9557 NonCopyable& operator=(NonCopyable&&) = delete;
9560 struct BoundRef : NonCopyable {
9561 virtual ~BoundRef() = default;
9562 virtual auto isContainer() const -> bool { return false; }
9563 virtual auto isFlag() const -> bool { return false; }
9565 struct BoundValueRefBase : BoundRef {
9566 virtual auto setValue(std::string const& arg) -> ParserResult = 0;
9568 struct BoundFlagRefBase : BoundRef {
9569 virtual auto setFlag(bool flag) -> ParserResult = 0;
9570 virtual auto isFlag() const -> bool { return true; }
9573 template <typename T> struct BoundValueRef : BoundValueRefBase {
9576 explicit BoundValueRef(T& ref) : m_ref(ref) {}
9578 auto setValue(std::string const& arg) -> ParserResult override {
9579 return convertInto(arg, m_ref);
9583 template <typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9584 std::vector<T>& m_ref;
9586 explicit BoundValueRef(std::vector<T>& ref) : m_ref(ref) {}
9588 auto isContainer() const -> bool override { return true; }
9590 auto setValue(std::string const& arg) -> ParserResult override {
9592 auto result = convertInto(arg, temp);
9594 m_ref.push_back(temp);
9599 struct BoundFlagRef : BoundFlagRefBase {
9602 explicit BoundFlagRef(bool& ref) : m_ref(ref) {}
9604 auto setFlag(bool flag) -> ParserResult override {
9606 return ParserResult::ok(ParseResultType::Matched);
9610 template <typename ReturnType> struct LambdaInvoker {
9611 static_assert(std::is_same<ReturnType, ParserResult>::value,
9612 "Lambda must return void or clara::ParserResult");
9614 template <typename L, typename ArgType>
9615 static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult {
9620 template <> struct LambdaInvoker<void> {
9621 template <typename L, typename ArgType>
9622 static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult {
9624 return ParserResult::ok(ParseResultType::Matched);
9628 template <typename ArgType, typename L>
9629 inline auto invokeLambda(L const& lambda, std::string const& arg) -> ParserResult {
9631 auto result = convertInto(arg, temp);
9632 return !result ? result
9633 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(
9637 template <typename L> struct BoundLambda : BoundValueRefBase {
9640 static_assert(UnaryLambdaTraits<L>::isValid,
9641 "Supplied lambda must take exactly one argument");
9642 explicit BoundLambda(L const& lambda) : m_lambda(lambda) {}
9644 auto setValue(std::string const& arg) -> ParserResult override {
9645 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(m_lambda, arg);
9649 template <typename L> struct BoundFlagLambda : BoundFlagRefBase {
9652 static_assert(UnaryLambdaTraits<L>::isValid,
9653 "Supplied lambda must take exactly one argument");
9654 static_assert(std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value,
9655 "flags must be boolean");
9657 explicit BoundFlagLambda(L const& lambda) : m_lambda(lambda) {}
9659 auto setFlag(bool flag) -> ParserResult override {
9660 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(
9665 enum class Optionality { Optional, Required };
9671 virtual ~ParserBase() = default;
9672 virtual auto validate() const -> Result { return Result::ok(); }
9673 virtual auto parse(std::string const& exeName, TokenStream const& tokens) const
9674 -> InternalParseResult = 0;
9675 virtual auto cardinality() const -> size_t { return 1; }
9677 auto parse(Args const& args) const -> InternalParseResult {
9678 return parse(args.exeName(), TokenStream(args));
9682 template <typename DerivedT> class ComposableParserImpl : public ParserBase {
9684 template <typename T> auto operator|(T const& other) const -> Parser;
9686 template <typename T> auto operator+(T const& other) const -> Parser;
9689 // Common code and state for Args and Opts
9690 template <typename DerivedT>
9691 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9693 Optionality m_optionality = Optionality::Optional;
9694 std::shared_ptr<BoundRef> m_ref;
9696 std::string m_description;
9698 explicit ParserRefImpl(std::shared_ptr<BoundRef> const& ref) : m_ref(ref) {}
9701 template <typename T>
9702 ParserRefImpl(T& ref, std::string const& hint) :
9703 m_ref(std::make_shared<BoundValueRef<T>>(ref)), m_hint(hint) {}
9705 template <typename LambdaT>
9706 ParserRefImpl(LambdaT const& ref, std::string const& hint) :
9707 m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)), m_hint(hint) {}
9709 auto operator()(std::string const& description) -> DerivedT& {
9710 m_description = description;
9711 return static_cast<DerivedT&>(*this);
9714 auto optional() -> DerivedT& {
9715 m_optionality = Optionality::Optional;
9716 return static_cast<DerivedT&>(*this);
9719 auto required() -> DerivedT& {
9720 m_optionality = Optionality::Required;
9721 return static_cast<DerivedT&>(*this);
9724 auto isOptional() const -> bool { return m_optionality == Optionality::Optional; }
9726 auto cardinality() const -> size_t override {
9727 if (m_ref->isContainer())
9733 auto hint() const -> std::string { return m_hint; }
9736 class ExeName : public ComposableParserImpl<ExeName> {
9737 std::shared_ptr<std::string> m_name;
9738 std::shared_ptr<BoundValueRefBase> m_ref;
9740 template <typename LambdaT>
9741 static auto makeRef(LambdaT const& lambda) -> std::shared_ptr<BoundValueRefBase> {
9742 return std::make_shared<BoundLambda<LambdaT>>(lambda);
9746 ExeName() : m_name(std::make_shared<std::string>("<executable>")) {}
9748 explicit ExeName(std::string& ref) : ExeName() {
9749 m_ref = std::make_shared<BoundValueRef<std::string>>(ref);
9752 template <typename LambdaT> explicit ExeName(LambdaT const& lambda) : ExeName() {
9753 m_ref = std::make_shared<BoundLambda<LambdaT>>(lambda);
9756 // The exe name is not parsed out of the normal tokens, but is
9757 // handled specially
9758 auto parse(std::string const&, TokenStream const& tokens) const
9759 -> InternalParseResult override {
9760 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
9763 auto name() const -> std::string { return *m_name; }
9764 auto set(std::string const& newName) -> ParserResult {
9766 auto lastSlash = newName.find_last_of("\\/");
9768 (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1);
9772 return m_ref->setValue(filename);
9774 return ParserResult::ok(ParseResultType::Matched);
9778 class Arg : public ParserRefImpl<Arg> {
9780 using ParserRefImpl::ParserRefImpl;
9782 auto parse(std::string const&, TokenStream const& tokens) const
9783 -> InternalParseResult override {
9784 auto validationResult = validate();
9785 if (!validationResult)
9786 return InternalParseResult(validationResult);
9788 auto remainingTokens = tokens;
9789 auto const& token = *remainingTokens;
9790 if (token.type != TokenType::Argument)
9791 return InternalParseResult::ok(
9792 ParseState(ParseResultType::NoMatch, remainingTokens));
9794 assert(!m_ref->isFlag());
9795 auto valueRef = static_cast<detail::BoundValueRefBase*>(m_ref.get());
9797 auto result = valueRef->setValue(remainingTokens->token);
9799 return InternalParseResult(result);
9801 return InternalParseResult::ok(
9802 ParseState(ParseResultType::Matched, ++remainingTokens));
9806 inline auto normaliseOpt(std::string const& optName) -> std::string {
9807 #ifdef CATCH_PLATFORM_WINDOWS
9808 if (optName[0] == '/')
9809 return "-" + optName.substr(1);
9815 class Opt : public ParserRefImpl<Opt> {
9817 std::vector<std::string> m_optNames;
9820 template <typename LambdaT>
9821 explicit Opt(LambdaT const& ref) :
9822 ParserRefImpl(std::make_shared<BoundFlagLambda<LambdaT>>(ref)) {}
9824 explicit Opt(bool& ref) : ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {}
9826 template <typename LambdaT>
9827 Opt(LambdaT const& ref, std::string const& hint) : ParserRefImpl(ref, hint) {}
9829 template <typename T>
9830 Opt(T& ref, std::string const& hint) : ParserRefImpl(ref, hint) {}
9832 auto operator[](std::string const& optName) -> Opt& {
9833 m_optNames.push_back(optName);
9837 auto getHelpColumns() const -> std::vector<HelpColumns> {
9838 std::ostringstream oss;
9840 for (auto const& opt : m_optNames) {
9847 if (!m_hint.empty())
9848 oss << " <" << m_hint << ">";
9849 return {{oss.str(), m_description}};
9852 auto isMatch(std::string const& optToken) const -> bool {
9853 auto normalisedToken = normaliseOpt(optToken);
9854 for (auto const& name : m_optNames) {
9855 if (normaliseOpt(name) == normalisedToken)
9861 using ParserBase::parse;
9863 auto parse(std::string const&, TokenStream const& tokens) const
9864 -> InternalParseResult override {
9865 auto validationResult = validate();
9866 if (!validationResult)
9867 return InternalParseResult(validationResult);
9869 auto remainingTokens = tokens;
9870 if (remainingTokens && remainingTokens->type == TokenType::Option) {
9871 auto const& token = *remainingTokens;
9872 if (isMatch(token.token)) {
9873 if (m_ref->isFlag()) {
9874 auto flagRef = static_cast<detail::BoundFlagRefBase*>(m_ref.get());
9875 auto result = flagRef->setFlag(true);
9877 return InternalParseResult(result);
9878 if (result.value() == ParseResultType::ShortCircuitAll)
9879 return InternalParseResult::ok(
9880 ParseState(result.value(), remainingTokens));
9883 static_cast<detail::BoundValueRefBase*>(m_ref.get());
9885 if (!remainingTokens)
9886 return InternalParseResult::runtimeError(
9887 "Expected argument following " + token.token);
9888 auto const& argToken = *remainingTokens;
9889 if (argToken.type != TokenType::Argument)
9890 return InternalParseResult::runtimeError(
9891 "Expected argument following " + token.token);
9892 auto result = valueRef->setValue(argToken.token);
9894 return InternalParseResult(result);
9895 if (result.value() == ParseResultType::ShortCircuitAll)
9896 return InternalParseResult::ok(
9897 ParseState(result.value(), remainingTokens));
9899 return InternalParseResult::ok(
9900 ParseState(ParseResultType::Matched, ++remainingTokens));
9903 return InternalParseResult::ok(
9904 ParseState(ParseResultType::NoMatch, remainingTokens));
9907 auto validate() const -> Result override {
9908 if (m_optNames.empty())
9909 return Result::logicError("No options supplied to Opt");
9910 for (auto const& name : m_optNames) {
9912 return Result::logicError("Option name cannot be empty");
9913 #ifdef CATCH_PLATFORM_WINDOWS
9914 if (name[0] != '-' && name[0] != '/')
9915 return Result::logicError("Option name must begin with '-' or '/'");
9918 return Result::logicError("Option name must begin with '-'");
9921 return ParserRefImpl::validate();
9926 Help(bool& showHelpFlag) :
9927 Opt([&](bool flag) {
9928 showHelpFlag = flag;
9929 return ParserResult::ok(ParseResultType::ShortCircuitAll);
9931 static_cast<Opt&> (*this)("display usage information")["-?"]["-h"]["--help"]
9936 struct Parser : ParserBase {
9938 mutable ExeName m_exeName;
9939 std::vector<Opt> m_options;
9940 std::vector<Arg> m_args;
9942 auto operator|=(ExeName const& exeName) -> Parser& {
9943 m_exeName = exeName;
9947 auto operator|=(Arg const& arg) -> Parser& {
9948 m_args.push_back(arg);
9952 auto operator|=(Opt const& opt) -> Parser& {
9953 m_options.push_back(opt);
9957 auto operator|=(Parser const& other) -> Parser& {
9959 m_options.end(), other.m_options.begin(), other.m_options.end());
9960 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9964 template <typename T> auto operator|(T const& other) const -> Parser {
9965 return Parser(*this) |= other;
9968 // Forward deprecated interface with '+' instead of '|'
9969 template <typename T> auto operator+=(T const& other) -> Parser& {
9970 return operator|=(other);
9972 template <typename T> auto operator+(T const& other) const -> Parser {
9973 return operator|(other);
9976 auto getHelpColumns() const -> std::vector<HelpColumns> {
9977 std::vector<HelpColumns> cols;
9978 for (auto const& o : m_options) {
9979 auto childCols = o.getHelpColumns();
9980 cols.insert(cols.end(), childCols.begin(), childCols.end());
9985 void writeToStream(std::ostream& os) const {
9986 if (!m_exeName.name().empty()) {
9988 << " " << m_exeName.name() << " ";
9989 bool required = true, first = true;
9990 for (auto const& arg : m_args) {
9995 if (arg.isOptional() && required) {
9999 os << "<" << arg.hint() << ">";
10000 if (arg.cardinality() == 0)
10005 if (!m_options.empty())
10007 os << "\n\nwhere options are:" << std::endl;
10010 auto rows = getHelpColumns();
10011 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
10012 size_t optWidth = 0;
10013 for (auto const& cols : rows)
10014 optWidth = (std::max)(optWidth, cols.left.size() + 2);
10016 optWidth = (std::min)(optWidth, consoleWidth / 2);
10018 for (auto const& cols : rows) {
10019 auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) +
10020 TextFlow::Spacer(4) +
10021 TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth);
10022 os << row << std::endl;
10026 friend auto operator<<(std::ostream& os, Parser const& parser) -> std::ostream& {
10027 parser.writeToStream(os);
10031 auto validate() const -> Result override {
10032 for (auto const& opt : m_options) {
10033 auto result = opt.validate();
10037 for (auto const& arg : m_args) {
10038 auto result = arg.validate();
10042 return Result::ok();
10045 using ParserBase::parse;
10047 auto parse(std::string const& exeName, TokenStream const& tokens) const
10048 -> InternalParseResult override {
10050 struct ParserInfo {
10051 ParserBase const* parser = nullptr;
10054 const size_t totalParsers = m_options.size() + m_args.size();
10055 assert(totalParsers < 512);
10056 // ParserInfo parseInfos[totalParsers]; // <-- this is what
10057 // we really want to do
10058 ParserInfo parseInfos[512];
10062 for (auto const& opt : m_options)
10063 parseInfos[i++].parser = &opt;
10064 for (auto const& arg : m_args)
10065 parseInfos[i++].parser = &arg;
10068 m_exeName.set(exeName);
10071 InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
10072 while (result.value().remainingTokens()) {
10073 bool tokenParsed = false;
10075 for (size_t i = 0; i < totalParsers; ++i) {
10076 auto& parseInfo = parseInfos[i];
10077 if (parseInfo.parser->cardinality() == 0 ||
10078 parseInfo.count < parseInfo.parser->cardinality()) {
10079 result = parseInfo.parser->parse(exeName,
10080 result.value().remainingTokens());
10083 if (result.value().type() != ParseResultType::NoMatch) {
10084 tokenParsed = true;
10091 if (result.value().type() == ParseResultType::ShortCircuitAll)
10094 return InternalParseResult::runtimeError(
10095 "Unrecognised token: " + result.value().remainingTokens()->token);
10097 // !TBD Check missing required options
10102 template <typename DerivedT>
10103 template <typename T>
10104 auto ComposableParserImpl<DerivedT>::operator|(T const& other) const -> Parser {
10105 return Parser() | static_cast<DerivedT const&>(*this) | other;
10107 } // namespace detail
10109 // A Combined parser
10110 using detail::Parser;
10112 // A parser for options
10115 // A parser for arguments
10118 // Wrapper for argc, argv from main()
10119 using detail::Args;
10121 // Specifies the name of the executable
10122 using detail::ExeName;
10124 // Convenience wrapper for option parser that specifies the help option
10125 using detail::Help;
10127 // enum of result types from a parse
10128 using detail::ParseResultType;
10130 // Result type for parser operation
10131 using detail::ParserResult;
10133 } // namespace clara
10134 } // namespace Catch
10138 #pragma clang diagnostic pop
10141 // Restore Clara's value for console width, if present
10142 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10143 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10144 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10147 // end catch_clara.h
10150 clara::Parser makeCommandLineParser(ConfigData& config);
10152 } // end namespace Catch
10154 // end catch_commandline.h
10160 clara::Parser makeCommandLineParser(ConfigData& config) {
10162 using namespace clara;
10164 auto const setWarning = [&](std::string const& warning) {
10165 auto warningSet = [&]() {
10166 if (warning == "NoAssertions")
10167 return WarnAbout::NoAssertions;
10169 if (warning == "NoTests")
10170 return WarnAbout::NoTests;
10172 return WarnAbout::Nothing;
10175 if (warningSet == WarnAbout::Nothing)
10176 return ParserResult::runtimeError("Unrecognised warning: '" + warning + "'");
10177 config.warnings = static_cast<WarnAbout::What>(config.warnings | warningSet);
10178 return ParserResult::ok(ParseResultType::Matched);
10180 auto const loadTestNamesFromFile = [&](std::string const& filename) {
10181 std::ifstream f(filename.c_str());
10183 return ParserResult::runtimeError("Unable to load input file: '" + filename + "'");
10186 while (std::getline(f, line)) {
10188 if (!line.empty() && !startsWith(line, '#')) {
10189 if (!startsWith(line, '"'))
10190 line = '"' + line + '"';
10191 config.testsOrTags.push_back(line);
10192 config.testsOrTags.emplace_back(",");
10195 // Remove comma in the end
10196 if (!config.testsOrTags.empty())
10197 config.testsOrTags.erase(config.testsOrTags.end() - 1);
10199 return ParserResult::ok(ParseResultType::Matched);
10201 auto const setTestOrder = [&](std::string const& order) {
10202 if (startsWith("declared", order))
10203 config.runOrder = RunTests::InDeclarationOrder;
10204 else if (startsWith("lexical", order))
10205 config.runOrder = RunTests::InLexicographicalOrder;
10206 else if (startsWith("random", order))
10207 config.runOrder = RunTests::InRandomOrder;
10209 return clara::ParserResult::runtimeError("Unrecognised ordering: '" + order + "'");
10210 return ParserResult::ok(ParseResultType::Matched);
10212 auto const setRngSeed = [&](std::string const& seed) {
10213 if (seed != "time")
10214 return clara::detail::convertInto(seed, config.rngSeed);
10215 config.rngSeed = static_cast<unsigned int>(std::time(nullptr));
10216 return ParserResult::ok(ParseResultType::Matched);
10218 auto const setColourUsage = [&](std::string const& useColour) {
10219 auto mode = toLower(useColour);
10222 config.useColour = UseColour::Yes;
10223 else if (mode == "no")
10224 config.useColour = UseColour::No;
10225 else if (mode == "auto")
10226 config.useColour = UseColour::Auto;
10228 return ParserResult::runtimeError("colour mode must be one of: auto, yes or no. '" +
10229 useColour + "' not recognised");
10230 return ParserResult::ok(ParseResultType::Matched);
10232 auto const setWaitForKeypress = [&](std::string const& keypress) {
10233 auto keypressLc = toLower(keypress);
10234 if (keypressLc == "never")
10235 config.waitForKeypress = WaitForKeypress::Never;
10236 else if (keypressLc == "start")
10237 config.waitForKeypress = WaitForKeypress::BeforeStart;
10238 else if (keypressLc == "exit")
10239 config.waitForKeypress = WaitForKeypress::BeforeExit;
10240 else if (keypressLc == "both")
10241 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
10243 return ParserResult::runtimeError(
10244 "keypress argument must be one of: never, start, exit or "
10246 keypress + "' not recognised");
10247 return ParserResult::ok(ParseResultType::Matched);
10249 auto const setVerbosity = [&](std::string const& verbosity) {
10250 auto lcVerbosity = toLower(verbosity);
10251 if (lcVerbosity == "quiet")
10252 config.verbosity = Verbosity::Quiet;
10253 else if (lcVerbosity == "normal")
10254 config.verbosity = Verbosity::Normal;
10255 else if (lcVerbosity == "high")
10256 config.verbosity = Verbosity::High;
10258 return ParserResult::runtimeError("Unrecognised verbosity, '" + verbosity + "'");
10259 return ParserResult::ok(ParseResultType::Matched);
10261 auto const setReporter = [&](std::string const& reporter) {
10262 IReporterRegistry::FactoryMap const& factories =
10263 getRegistryHub().getReporterRegistry().getFactories();
10265 auto lcReporter = toLower(reporter);
10266 auto result = factories.find(lcReporter);
10268 if (factories.end() != result)
10269 config.reporterName = lcReporter;
10271 return ParserResult::runtimeError("Unrecognized reporter, '" + reporter +
10272 "'. Check available with --list-reporters");
10273 return ParserResult::ok(ParseResultType::Matched);
10277 ExeName(config.processName) | Help(config.showHelp) |
10278 Opt(config.listTests)["-l"]["--list-tests"]("list all/matching test cases") |
10279 Opt(config.listTags)["-t"]["--list-tags"]("list all/matching tags") |
10280 Opt(config.showSuccessfulTests)["-s"]["--success"](
10281 "include successful tests in output") |
10282 Opt(config.shouldDebugBreak)["-b"]["--break"]("break into debugger on failure") |
10283 Opt(config.noThrow)["-e"]["--nothrow"]("skip exception tests") |
10284 Opt(config.showInvisibles)["-i"]["--invisibles"]("show invisibles (tabs, newlines)") |
10285 Opt(config.outputFilename, "filename")["-o"]["--out"]("output filename") |
10286 Opt(setReporter, "name")["-r"]["--reporter"]("reporter to use (defaults to console)") |
10287 Opt(config.name, "name")["-n"]["--name"]("suite name") |
10288 Opt([&](bool) { config.abortAfter = 1; })["-a"]["--abort"]("abort at first failure") |
10289 Opt([&](int x) { config.abortAfter = x; },
10290 "no. failures")["-x"]["--abortx"]("abort after x failures") |
10291 Opt(setWarning, "warning name")["-w"]["--warn"]("enable warnings") |
10294 config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never;
10296 "yes|no")["-d"]["--durations"]("show test durations") |
10297 Opt(config.minDuration, "seconds")["-D"]["--min-duration"](
10298 "show test durations for tests taking at least the given "
10299 "number of seconds") |
10300 Opt(loadTestNamesFromFile,
10301 "filename")["-f"]["--input-file"]("load test names to run from a file") |
10302 Opt(config.filenamesAsTags)["-#"]["--filenames-as-tags"](
10303 "adds a tag for the filename") |
10304 Opt(config.sectionsToRun, "section name")["-c"]["--section"]("specify section to run") |
10305 Opt(setVerbosity, "quiet|normal|high")["-v"]["--verbosity"]("set output verbosity") |
10306 Opt(config.listTestNamesOnly)["--list-test-names-only"](
10307 "list all/matching test cases names only") |
10308 Opt(config.listReporters)["--list-reporters"]("list all reporters") |
10309 Opt(setTestOrder, "decl|lex|rand")["--order"]("test case order (defaults to decl)") |
10311 "'time'|number")["--rng-seed"]("set a specific seed for random numbers") |
10312 Opt(setColourUsage, "yes|no")["--use-colour"]("should output be colourised") |
10313 Opt(config.libIdentify)["--libidentify"](
10314 "report name and version according to libidentify standard") |
10315 Opt(setWaitForKeypress, "never|start|exit|both")["--wait-for-keypress"](
10316 "waits for a keypress before exiting") |
10317 Opt(config.benchmarkSamples,
10318 "samples")["--benchmark-samples"]("number of samples to collect (default: 100)") |
10319 Opt(config.benchmarkResamples, "resamples")["--benchmark-resamples"](
10320 "number of resamples for the bootstrap (default: 100000)") |
10321 Opt(config.benchmarkConfidenceInterval,
10322 "confidence interval")["--benchmark-confidence-interval"](
10323 "confidence interval for the bootstrap (between 0 and 1, "
10324 "default: 0.95)") |
10325 Opt(config.benchmarkNoAnalysis)["--benchmark-no-analysis"](
10326 "perform only measurements; do not perform any analysis") |
10327 Opt(config.benchmarkWarmupTime, "benchmarkWarmupTime")["--benchmark-warmup-time"](
10328 "amount of time in milliseconds spent on warming up each test "
10329 "(default: 100)") |
10330 Arg(config.testsOrTags, "test name|pattern|tags")("which test or tests to use");
10335 } // end namespace Catch
10336 // end catch_commandline.cpp
10337 // start catch_common.cpp
10344 bool SourceLineInfo::operator==(SourceLineInfo const& other) const noexcept {
10345 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
10347 bool SourceLineInfo::operator<(SourceLineInfo const& other) const noexcept {
10348 // We can assume that the same file will usually have the same pointer.
10349 // Thus, if the pointers are the same, there is no point in calling the
10351 return line < other.line ||
10352 (line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
10355 std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info) {
10357 os << info.file << '(' << info.line << ')';
10359 os << info.file << ':' << info.line;
10364 std::string StreamEndStop::operator+() const { return std::string(); }
10366 NonCopyable::NonCopyable() = default;
10367 NonCopyable::~NonCopyable() = default;
10369 } // namespace Catch
10370 // end catch_common.cpp
10371 // start catch_config.cpp
10375 Config::Config(ConfigData const& data) : m_data(data), m_stream(openStream()) {
10376 // We need to trim filter specs to avoid trouble with superfluous
10377 // whitespace (esp. important for bdd macros, as those are manually
10378 // aligned with whitespace).
10380 for (auto& elem : m_data.testsOrTags) {
10383 for (auto& elem : m_data.sectionsToRun) {
10387 TestSpecParser parser(ITagAliasRegistry::get());
10388 if (!m_data.testsOrTags.empty()) {
10389 m_hasTestFilters = true;
10390 for (auto const& testOrTags : m_data.testsOrTags) {
10391 parser.parse(testOrTags);
10394 m_testSpec = parser.testSpec();
10397 std::string const& Config::getFilename() const { return m_data.outputFilename; }
10399 bool Config::listTests() const { return m_data.listTests; }
10400 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
10401 bool Config::listTags() const { return m_data.listTags; }
10402 bool Config::listReporters() const { return m_data.listReporters; }
10404 std::string Config::getProcessName() const { return m_data.processName; }
10405 std::string const& Config::getReporterName() const { return m_data.reporterName; }
10407 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
10408 std::vector<std::string> const& Config::getSectionsToRun() const {
10409 return m_data.sectionsToRun;
10412 TestSpec const& Config::testSpec() const { return m_testSpec; }
10413 bool Config::hasTestFilters() const { return m_hasTestFilters; }
10415 bool Config::showHelp() const { return m_data.showHelp; }
10417 // IConfig interface
10418 bool Config::allowThrows() const { return !m_data.noThrow; }
10419 std::ostream& Config::stream() const { return m_stream->stream(); }
10420 std::string Config::name() const {
10421 return m_data.name.empty() ? m_data.processName : m_data.name;
10423 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
10424 bool Config::warnAboutMissingAssertions() const {
10425 return !!(m_data.warnings & WarnAbout::NoAssertions);
10427 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
10428 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
10429 double Config::minDuration() const { return m_data.minDuration; }
10430 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
10431 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
10432 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
10433 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
10434 int Config::abortAfter() const { return m_data.abortAfter; }
10435 bool Config::showInvisibles() const { return m_data.showInvisibles; }
10436 Verbosity Config::verbosity() const { return m_data.verbosity; }
10438 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
10439 int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
10440 double Config::benchmarkConfidenceInterval() const {
10441 return m_data.benchmarkConfidenceInterval;
10443 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
10444 std::chrono::milliseconds Config::benchmarkWarmupTime() const {
10445 return std::chrono::milliseconds(m_data.benchmarkWarmupTime);
10448 IStream const* Config::openStream() { return Catch::makeStream(m_data.outputFilename); }
10450 } // end namespace Catch
10451 // end catch_config.cpp
10452 // start catch_console_colour.cpp
10454 #if defined(__clang__)
10455 #pragma clang diagnostic push
10456 #pragma clang diagnostic ignored "-Wexit-time-destructors"
10459 // start catch_errno_guard.h
10472 } // namespace Catch
10474 // end catch_errno_guard.h
10475 // start catch_windows_h_proxy.h
10477 #if defined(CATCH_PLATFORM_WINDOWS)
10479 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10480 #define CATCH_DEFINED_NOMINMAX
10483 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10484 #define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10485 #define WIN32_LEAN_AND_MEAN
10489 #include <AfxWin.h>
10491 #include <windows.h>
10494 #ifdef CATCH_DEFINED_NOMINMAX
10497 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10498 #undef WIN32_LEAN_AND_MEAN
10501 #endif // defined(CATCH_PLATFORM_WINDOWS)
10503 // end catch_windows_h_proxy.h
10509 struct IColourImpl {
10510 virtual ~IColourImpl() = default;
10511 virtual void use(Colour::Code _colourCode) = 0;
10514 struct NoColourImpl : IColourImpl {
10515 void use(Colour::Code) override {}
10517 static IColourImpl* instance() {
10518 static NoColourImpl s_instance;
10519 return &s_instance;
10524 } // namespace Catch
10526 #if !defined(CATCH_CONFIG_COLOUR_NONE) && !defined(CATCH_CONFIG_COLOUR_WINDOWS) && \
10527 !defined(CATCH_CONFIG_COLOUR_ANSI)
10528 #ifdef CATCH_PLATFORM_WINDOWS
10529 #define CATCH_CONFIG_COLOUR_WINDOWS
10531 #define CATCH_CONFIG_COLOUR_ANSI
10535 #if defined(CATCH_CONFIG_COLOUR_WINDOWS) /////////////////////////////////////////
10540 class Win32ColourImpl : public IColourImpl {
10542 Win32ColourImpl() : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)) {
10543 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10544 GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo);
10545 originalForegroundAttributes =
10546 csbiInfo.wAttributes &
10547 ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
10548 originalBackgroundAttributes =
10549 csbiInfo.wAttributes &
10550 ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
10553 void use(Colour::Code _colourCode) override {
10554 switch (_colourCode) {
10556 return setTextAttribute(originalForegroundAttributes);
10557 case Colour::White:
10558 return setTextAttribute(FOREGROUND_GREEN | FOREGROUND_RED |
10561 return setTextAttribute(FOREGROUND_RED);
10562 case Colour::Green:
10563 return setTextAttribute(FOREGROUND_GREEN);
10565 return setTextAttribute(FOREGROUND_BLUE);
10567 return setTextAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN);
10568 case Colour::Yellow:
10569 return setTextAttribute(FOREGROUND_RED | FOREGROUND_GREEN);
10571 return setTextAttribute(0);
10573 case Colour::LightGrey:
10574 return setTextAttribute(FOREGROUND_INTENSITY);
10575 case Colour::BrightRed:
10576 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED);
10577 case Colour::BrightGreen:
10578 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN);
10579 case Colour::BrightWhite:
10580 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN |
10581 FOREGROUND_RED | FOREGROUND_BLUE);
10582 case Colour::BrightYellow:
10583 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED |
10586 case Colour::Bright:
10587 CATCH_INTERNAL_ERROR("not a colour");
10590 CATCH_ERROR("Unknown colour requested");
10595 void setTextAttribute(WORD _textAttribute) {
10596 SetConsoleTextAttribute(stdoutHandle,
10597 _textAttribute | originalBackgroundAttributes);
10599 HANDLE stdoutHandle;
10600 WORD originalForegroundAttributes;
10601 WORD originalBackgroundAttributes;
10604 IColourImpl* platformColourInstance() {
10605 static Win32ColourImpl s_instance;
10607 IConfigPtr config = getCurrentContext().getConfig();
10608 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10609 if (colourMode == UseColour::Auto)
10610 colourMode = UseColour::Yes;
10611 return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance();
10615 } // end namespace Catch
10617 #elif defined(CATCH_CONFIG_COLOUR_ANSI) //////////////////////////////////////
10619 #include <unistd.h>
10624 // use POSIX/ ANSI console terminal codes
10625 // Thanks to Adam Strzelecki for original contribution
10626 // (http://github.com/nanoant)
10627 // https://github.com/philsquared/Catch/pull/131
10628 class PosixColourImpl : public IColourImpl {
10630 void use(Colour::Code _colourCode) override {
10631 switch (_colourCode) {
10633 case Colour::White:
10634 return setColour("[0m");
10636 return setColour("[0;31m");
10637 case Colour::Green:
10638 return setColour("[0;32m");
10640 return setColour("[0;34m");
10642 return setColour("[0;36m");
10643 case Colour::Yellow:
10644 return setColour("[0;33m");
10646 return setColour("[1;30m");
10648 case Colour::LightGrey:
10649 return setColour("[0;37m");
10650 case Colour::BrightRed:
10651 return setColour("[1;31m");
10652 case Colour::BrightGreen:
10653 return setColour("[1;32m");
10654 case Colour::BrightWhite:
10655 return setColour("[1;37m");
10656 case Colour::BrightYellow:
10657 return setColour("[1;33m");
10659 case Colour::Bright:
10660 CATCH_INTERNAL_ERROR("not a colour");
10662 CATCH_INTERNAL_ERROR("Unknown colour requested");
10665 static IColourImpl* instance() {
10666 static PosixColourImpl s_instance;
10667 return &s_instance;
10671 void setColour(const char* _escapeCode) {
10672 getCurrentContext().getConfig()->stream() << '\033' << _escapeCode;
10676 bool useColourOnPlatform() {
10678 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10679 !isDebuggerActive() &&
10681 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10682 isatty(STDOUT_FILENO)
10688 IColourImpl* platformColourInstance() {
10690 IConfigPtr config = getCurrentContext().getConfig();
10691 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10692 if (colourMode == UseColour::Auto)
10693 colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No;
10694 return colourMode == UseColour::Yes ? PosixColourImpl::instance()
10695 : NoColourImpl::instance();
10699 } // end namespace Catch
10701 #else // not Windows or ANSI ///////////////////////////////////////////////
10705 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10707 } // end namespace Catch
10709 #endif // Windows/ ANSI/ None
10713 Colour::Colour(Code _colourCode) { use(_colourCode); }
10714 Colour::Colour(Colour&& other) noexcept {
10715 m_moved = other.m_moved;
10716 other.m_moved = true;
10718 Colour& Colour::operator=(Colour&& other) noexcept {
10719 m_moved = other.m_moved;
10720 other.m_moved = true;
10724 Colour::~Colour() {
10729 void Colour::use(Code _colourCode) {
10730 static IColourImpl* impl = platformColourInstance();
10731 // Strictly speaking, this cannot possibly happen.
10732 // However, under some conditions it does happen (see #1626),
10733 // and this change is small enough that we can let practicality
10734 // triumph over purity in this case.
10735 if (impl != nullptr) {
10736 impl->use(_colourCode);
10740 std::ostream& operator<<(std::ostream& os, Colour const&) { return os; }
10742 } // end namespace Catch
10744 #if defined(__clang__)
10745 #pragma clang diagnostic pop
10748 // end catch_console_colour.cpp
10749 // start catch_context.cpp
10753 class Context : public IMutableContext, NonCopyable {
10755 public: // IContext
10756 IResultCapture* getResultCapture() override { return m_resultCapture; }
10757 IRunner* getRunner() override { return m_runner; }
10759 IConfigPtr const& getConfig() const override { return m_config; }
10761 ~Context() override;
10763 public: // IMutableContext
10764 void setResultCapture(IResultCapture* resultCapture) override {
10765 m_resultCapture = resultCapture;
10767 void setRunner(IRunner* runner) override { m_runner = runner; }
10768 void setConfig(IConfigPtr const& config) override { m_config = config; }
10770 friend IMutableContext& getCurrentMutableContext();
10773 IConfigPtr m_config;
10774 IRunner* m_runner = nullptr;
10775 IResultCapture* m_resultCapture = nullptr;
10778 IMutableContext* IMutableContext::currentContext = nullptr;
10780 void IMutableContext::createContext() { currentContext = new Context(); }
10782 void cleanUpContext() {
10783 delete IMutableContext::currentContext;
10784 IMutableContext::currentContext = nullptr;
10786 IContext::~IContext() = default;
10787 IMutableContext::~IMutableContext() = default;
10788 Context::~Context() = default;
10790 SimplePcg32& rng() {
10791 static SimplePcg32 s_rng;
10795 } // namespace Catch
10796 // end catch_context.cpp
10797 // start catch_debug_console.cpp
10799 // start catch_debug_console.h
10804 void writeToDebugConsole(std::string const& text);
10807 // end catch_debug_console.h
10808 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10809 #include <android/log.h>
10812 void writeToDebugConsole(std::string const& text) {
10813 __android_log_write(ANDROID_LOG_DEBUG, "Catch", text.c_str());
10815 } // namespace Catch
10817 #elif defined(CATCH_PLATFORM_WINDOWS)
10820 void writeToDebugConsole(std::string const& text) { ::OutputDebugStringA(text.c_str()); }
10821 } // namespace Catch
10826 void writeToDebugConsole(std::string const& text) {
10827 // !TBD: Need a version for Mac/ XCode and other IDEs
10828 Catch::cout() << text;
10830 } // namespace Catch
10833 // end catch_debug_console.cpp
10834 // start catch_debugger.cpp
10836 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10839 #include <sys/types.h>
10840 #include <unistd.h>
10844 #ifdef __apple_build_version__
10845 // These headers will only compile with AppleClang (XCode)
10846 // For other compilers (Clang, GCC, ... ) we need to exclude them
10847 #include <sys/sysctl.h>
10851 #ifdef __apple_build_version__
10852 // The following function is taken directly from the following technical
10853 // note: https://developer.apple.com/library/archive/qa/qa1361/_index.html
10855 // Returns true if the current process is being debugged (either
10856 // running under the debugger or has a debugger attached post facto).
10857 bool isDebuggerActive() {
10859 struct kinfo_proc info;
10862 // Initialize the flags so that, if sysctl fails for some bizarre
10863 // reason, we get a predictable result.
10865 info.kp_proc.p_flag = 0;
10867 // Initialize mib, which tells sysctl the info we want, in this case
10868 // we're looking for information about a specific process ID.
10871 mib[1] = KERN_PROC;
10872 mib[2] = KERN_PROC_PID;
10877 size = sizeof(info);
10878 if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0) {
10879 Catch::cerr() << "\n** Call to sysctl failed - unable to determine "
10880 "if debugger is active **\n"
10885 // We're being debugged if the P_TRACED flag is set.
10887 return ((info.kp_proc.p_flag & P_TRACED) != 0);
10890 bool isDebuggerActive() {
10891 // We need to find another way to determine this for non-appleclang
10892 // compilers on macOS
10896 } // namespace Catch
10898 #elif defined(CATCH_PLATFORM_LINUX)
10903 // The standard POSIX way of detecting a debugger is to attempt to
10904 // ptrace() the process, but this needs to be done from a child and not
10905 // this process itself to still allow attaching to this process later
10906 // if wanted, so is rather heavy. Under Linux we have the PID of the
10907 // "debugger" (which doesn't need to be gdb, of course, it could also
10908 // be strace, for example) in /proc/$PID/status, so just get it from
10910 bool isDebuggerActive() {
10911 // Libstdc++ has a bug, where std::ifstream sets errno to 0
10912 // This way our users can properly assert over errno values
10914 std::ifstream in("/proc/self/status");
10915 for (std::string line; std::getline(in, line);) {
10916 static const int PREFIX_LEN = 11;
10917 if (line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) {
10918 // We're traced if the PID is not 0 and no other PID starts
10919 // with 0 digit, so it's enough to check for just a single
10921 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10927 } // namespace Catch
10928 #elif defined(_MSC_VER)
10929 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10931 bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
10932 } // namespace Catch
10933 #elif defined(__MINGW32__)
10934 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10936 bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
10937 } // namespace Catch
10940 bool isDebuggerActive() { return false; }
10941 } // namespace Catch
10943 // end catch_debugger.cpp
10944 // start catch_decomposer.cpp
10948 ITransientExpression::~ITransientExpression() = default;
10950 void formatReconstructedExpression(std::ostream& os,
10951 std::string const& lhs,
10953 std::string const& rhs) {
10954 if (lhs.size() + rhs.size() < 40 && lhs.find('\n') == std::string::npos &&
10955 rhs.find('\n') == std::string::npos)
10956 os << lhs << " " << op << " " << rhs;
10958 os << lhs << "\n" << op << "\n" << rhs;
10960 } // namespace Catch
10961 // end catch_decomposer.cpp
10962 // start catch_enforce.cpp
10964 #include <stdexcept>
10967 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && \
10968 !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10969 [[noreturn]] void throw_exception(std::exception const& e) {
10970 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10971 << "The message was: " << e.what() << '\n';
10976 [[noreturn]] void throw_logic_error(std::string const& msg) {
10977 throw_exception(std::logic_error(msg));
10980 [[noreturn]] void throw_domain_error(std::string const& msg) {
10981 throw_exception(std::domain_error(msg));
10984 [[noreturn]] void throw_runtime_error(std::string const& msg) {
10985 throw_exception(std::runtime_error(msg));
10988 } // namespace Catch
10989 // end catch_enforce.cpp
10990 // start catch_enum_values_registry.cpp
10991 // start catch_enum_values_registry.h
11000 std::unique_ptr<EnumInfo>
11001 makeEnumInfo(StringRef enumName, StringRef allValueNames, std::vector<int> const& values);
11003 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
11005 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
11007 EnumInfo const& registerEnum(StringRef enumName,
11008 StringRef allEnums,
11009 std::vector<int> const& values) override;
11012 std::vector<StringRef> parseEnums(StringRef enums);
11014 } // namespace Detail
11016 } // namespace Catch
11018 // end catch_enum_values_registry.h
11025 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
11030 // Extracts the actual name part of an enum instance
11031 // In other words, it returns the Blue part of
11032 // Bikeshed::Colour::Blue
11033 StringRef extractInstanceName(StringRef enumInstance) {
11034 // Find last occurrence of ":"
11035 size_t name_start = enumInstance.size();
11036 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
11039 return enumInstance.substr(name_start, enumInstance.size() - name_start);
11043 std::vector<StringRef> parseEnums(StringRef enums) {
11044 auto enumValues = splitStringRef(enums, ',');
11045 std::vector<StringRef> parsed;
11046 parsed.reserve(enumValues.size());
11047 for (auto const& enumValue : enumValues) {
11048 parsed.push_back(trim(extractInstanceName(enumValue)));
11053 EnumInfo::~EnumInfo() {}
11055 StringRef EnumInfo::lookup(int value) const {
11056 for (auto const& valueToName : m_values) {
11057 if (valueToName.first == value)
11058 return valueToName.second;
11060 return "{** unexpected enum value **}"_sr;
11063 std::unique_ptr<EnumInfo>
11064 makeEnumInfo(StringRef enumName, StringRef allValueNames, std::vector<int> const& values) {
11065 std::unique_ptr<EnumInfo> enumInfo(new EnumInfo);
11066 enumInfo->m_name = enumName;
11067 enumInfo->m_values.reserve(values.size());
11069 const auto valueNames = Catch::Detail::parseEnums(allValueNames);
11070 assert(valueNames.size() == values.size());
11072 for (auto value : values)
11073 enumInfo->m_values.emplace_back(value, valueNames[i++]);
11078 EnumInfo const& EnumValuesRegistry::registerEnum(StringRef enumName,
11079 StringRef allValueNames,
11080 std::vector<int> const& values) {
11081 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
11082 return *m_enumInfos.back();
11085 } // namespace Detail
11086 } // namespace Catch
11088 // end catch_enum_values_registry.cpp
11089 // start catch_errno_guard.cpp
11094 ErrnoGuard::ErrnoGuard() : m_oldErrno(errno) {}
11095 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
11096 } // namespace Catch
11097 // end catch_errno_guard.cpp
11098 // start catch_exception_translator_registry.cpp
11100 // start catch_exception_translator_registry.h
11108 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
11110 ~ExceptionTranslatorRegistry();
11111 virtual void registerTranslator(const IExceptionTranslator* translator);
11112 std::string translateActiveException() const override;
11113 std::string tryTranslators() const;
11116 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
11118 } // namespace Catch
11120 // end catch_exception_translator_registry.h
11122 #import "Foundation/Foundation.h"
11127 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {}
11129 void ExceptionTranslatorRegistry::registerTranslator(const IExceptionTranslator* translator) {
11130 m_translators.push_back(std::unique_ptr<const IExceptionTranslator>(translator));
11133 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
11134 std::string ExceptionTranslatorRegistry::translateActiveException() const {
11137 // In Objective-C try objective-c exceptions first
11140 return tryTranslators();
11141 } @catch (NSException* exception)
11143 return Catch::Detail::stringify([exception description]);
11146 // Compiling a mixed mode project with MSVC means that CLR
11147 // exceptions will be caught in (...) as well. However, these
11148 // do not fill-in std::current_exception and thus lead to crash
11149 // when attempting rethrow.
11150 // /EHa switch also causes structured exceptions to be caught
11151 // here, but they fill-in current_exception properly, so
11152 // at worst the output should be a little weird, instead of
11153 // causing a crash.
11154 if (std::current_exception() == nullptr) {
11155 return "Non C++ exception. Possibly a CLR exception.";
11157 return tryTranslators();
11159 } catch (TestFailureException&) {
11160 std::rethrow_exception(std::current_exception());
11161 } catch (std::exception& ex) {
11163 } catch (std::string& msg) {
11165 } catch (const char* msg) {
11168 return "Unknown exception";
11172 std::string ExceptionTranslatorRegistry::tryTranslators() const {
11173 if (m_translators.empty()) {
11174 std::rethrow_exception(std::current_exception());
11176 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
11180 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
11181 std::string ExceptionTranslatorRegistry::translateActiveException() const {
11182 CATCH_INTERNAL_ERROR("Attempted to translate active exception under "
11183 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
11186 std::string ExceptionTranslatorRegistry::tryTranslators() const {
11187 CATCH_INTERNAL_ERROR("Attempted to use exception translators under "
11188 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
11192 } // namespace Catch
11193 // end catch_exception_translator_registry.cpp
11194 // start catch_fatal_condition.cpp
11196 #include <algorithm>
11198 #if !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
11202 // If neither SEH nor signal handling is required, the handler impls
11203 // do not have to do anything, and can be empty.
11204 void FatalConditionHandler::engage_platform() {}
11205 void FatalConditionHandler::disengage_platform() {}
11206 FatalConditionHandler::FatalConditionHandler() = default;
11207 FatalConditionHandler::~FatalConditionHandler() = default;
11209 } // end namespace Catch
11211 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
11213 #if defined(CATCH_CONFIG_WINDOWS_SEH) && defined(CATCH_CONFIG_POSIX_SIGNALS)
11215 "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
11216 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
11218 #if defined(CATCH_CONFIG_WINDOWS_SEH) || defined(CATCH_CONFIG_POSIX_SIGNALS)
11221 //! Signals fatal error message to the run context
11222 void reportFatal(char const* const message) {
11223 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition(message);
11226 //! Minimal size Catch2 needs for its own fatal error handling.
11227 //! Picked anecdotally, so it might not be sufficient on all
11228 //! platforms, and for all configurations.
11229 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
11230 } // end unnamed namespace
11232 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
11234 #if defined(CATCH_CONFIG_WINDOWS_SEH)
11238 struct SignalDefs {
11243 // There is no 1-1 mapping between signals and windows exceptions.
11244 // Windows can easily distinguish between SO and SigSegV,
11245 // but SigInt, SigTerm, etc are handled differently.
11246 static SignalDefs signalDefs[] = {
11247 {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal"},
11248 {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"},
11249 {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal"},
11250 {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"},
11253 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
11254 for (auto const& def : signalDefs) {
11255 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
11256 reportFatal(def.name);
11259 // If its not an exception we care about, pass it along.
11260 // This stops us from eating debugger breaks etc.
11261 return EXCEPTION_CONTINUE_SEARCH;
11264 // Since we do not support multiple instantiations, we put these
11265 // into global variables and rely on cleaning them up in outlined
11266 // constructors/destructors
11267 static PVOID exceptionHandlerHandle = nullptr;
11269 // For MSVC, we reserve part of the stack memory for handling
11270 // memory overflow structured exception.
11271 FatalConditionHandler::FatalConditionHandler() {
11272 ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
11273 if (!SetThreadStackGuarantee(&guaranteeSize)) {
11274 // We do not want to fully error out, because needing
11275 // the stack reserve should be rare enough anyway.
11276 Catch::cerr() << "Failed to reserve piece of stack."
11277 << " Stack overflows will not be reported successfully.";
11281 // We do not attempt to unset the stack guarantee, because
11282 // Windows does not support lowering the stack size guarantee.
11283 FatalConditionHandler::~FatalConditionHandler() = default;
11285 void FatalConditionHandler::engage_platform() {
11286 // Register as first handler in current chain
11287 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
11288 if (!exceptionHandlerHandle) {
11289 CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
11293 void FatalConditionHandler::disengage_platform() {
11294 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
11295 CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
11297 exceptionHandlerHandle = nullptr;
11300 } // end namespace Catch
11302 #endif // CATCH_CONFIG_WINDOWS_SEH
11304 #if defined(CATCH_CONFIG_POSIX_SIGNALS)
11306 #include <signal.h>
11310 struct SignalDefs {
11315 static SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"},
11316 {SIGILL, "SIGILL - Illegal instruction signal"},
11317 {SIGFPE, "SIGFPE - Floating point error signal"},
11318 {SIGSEGV, "SIGSEGV - Segmentation violation signal"},
11319 {SIGTERM, "SIGTERM - Termination request signal"},
11320 {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}};
11322 // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
11323 // which is zero initialization, but not explicit. We want to avoid
11325 #if defined(__GNUC__)
11326 #pragma GCC diagnostic push
11327 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
11330 static char* altStackMem = nullptr;
11331 static std::size_t altStackSize = 0;
11332 static stack_t oldSigStack{};
11333 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
11335 static void restorePreviousSignalHandlers() {
11336 // We set signal handlers back to the previous ones. Hopefully
11337 // nobody overwrote them in the meantime, and doesn't expect
11338 // their signal handlers to live past ours given that they
11339 // installed them after ours..
11340 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11341 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
11343 // Return the old stack
11344 sigaltstack(&oldSigStack, nullptr);
11347 static void handleSignal(int sig) {
11348 char const* name = "<unknown signal>";
11349 for (auto const& def : signalDefs) {
11350 if (sig == def.id) {
11355 // We need to restore previous signal handlers and let them do
11356 // their thing, so that the users can have the debugger break
11357 // when a signal is raised, and so on.
11358 restorePreviousSignalHandlers();
11363 FatalConditionHandler::FatalConditionHandler() {
11364 assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
11365 if (altStackSize == 0) {
11366 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
11368 altStackMem = new char[altStackSize]();
11371 FatalConditionHandler::~FatalConditionHandler() {
11372 delete[] altStackMem;
11373 // We signal that another instance can be constructed by zeroing
11374 // out the pointer.
11375 altStackMem = nullptr;
11378 void FatalConditionHandler::engage_platform() {
11380 sigStack.ss_sp = altStackMem;
11381 sigStack.ss_size = altStackSize;
11382 sigStack.ss_flags = 0;
11383 sigaltstack(&sigStack, &oldSigStack);
11384 struct sigaction sa = {};
11386 sa.sa_handler = handleSignal;
11387 sa.sa_flags = SA_ONSTACK;
11388 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11389 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
11393 #if defined(__GNUC__)
11394 #pragma GCC diagnostic pop
11397 void FatalConditionHandler::disengage_platform() { restorePreviousSignalHandlers(); }
11399 } // end namespace Catch
11401 #endif // CATCH_CONFIG_POSIX_SIGNALS
11402 // end catch_fatal_condition.cpp
11403 // start catch_generators.cpp
11410 IGeneratorTracker::~IGeneratorTracker() {}
11412 const char* GeneratorException::what() const noexcept { return m_msg; }
11414 namespace Generators {
11416 GeneratorUntypedBase::~GeneratorUntypedBase() {}
11418 auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
11419 -> IGeneratorTracker& {
11420 return getResultCapture().acquireGeneratorTracker(generatorName, lineInfo);
11423 } // namespace Generators
11424 } // namespace Catch
11425 // end catch_generators.cpp
11426 // start catch_interfaces_capture.cpp
11429 IResultCapture::~IResultCapture() = default;
11431 // end catch_interfaces_capture.cpp
11432 // start catch_interfaces_config.cpp
11435 IConfig::~IConfig() = default;
11437 // end catch_interfaces_config.cpp
11438 // start catch_interfaces_exception.cpp
11441 IExceptionTranslator::~IExceptionTranslator() = default;
11442 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
11443 } // namespace Catch
11444 // end catch_interfaces_exception.cpp
11445 // start catch_interfaces_registry_hub.cpp
11448 IRegistryHub::~IRegistryHub() = default;
11449 IMutableRegistryHub::~IMutableRegistryHub() = default;
11450 } // namespace Catch
11451 // end catch_interfaces_registry_hub.cpp
11452 // start catch_interfaces_reporter.cpp
11454 // start catch_reporter_listening.h
11458 class ListeningReporter : public IStreamingReporter {
11459 using Reporters = std::vector<IStreamingReporterPtr>;
11460 Reporters m_listeners;
11461 IStreamingReporterPtr m_reporter = nullptr;
11462 ReporterPreferences m_preferences;
11465 ListeningReporter();
11467 void addListener(IStreamingReporterPtr&& listener);
11468 void addReporter(IStreamingReporterPtr&& reporter);
11470 public: // IStreamingReporter
11471 ReporterPreferences getPreferences() const override;
11473 void noMatchingTestCases(std::string const& spec) override;
11475 void reportInvalidArguments(std::string const& arg) override;
11477 static std::set<Verbosity> getSupportedVerbosities();
11479 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11480 void benchmarkPreparing(std::string const& name) override;
11481 void benchmarkStarting(BenchmarkInfo const& benchmarkInfo) override;
11482 void benchmarkEnded(BenchmarkStats<> const& benchmarkStats) override;
11483 void benchmarkFailed(std::string const&) override;
11484 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11486 void testRunStarting(TestRunInfo const& testRunInfo) override;
11487 void testGroupStarting(GroupInfo const& groupInfo) override;
11488 void testCaseStarting(TestCaseInfo const& testInfo) override;
11489 void sectionStarting(SectionInfo const& sectionInfo) override;
11490 void assertionStarting(AssertionInfo const& assertionInfo) override;
11492 // The return value indicates if the messages buffer should be cleared:
11493 bool assertionEnded(AssertionStats const& assertionStats) override;
11494 void sectionEnded(SectionStats const& sectionStats) override;
11495 void testCaseEnded(TestCaseStats const& testCaseStats) override;
11496 void testGroupEnded(TestGroupStats const& testGroupStats) override;
11497 void testRunEnded(TestRunStats const& testRunStats) override;
11499 void skipTest(TestCaseInfo const& testInfo) override;
11500 bool isMulti() const override;
11503 } // end namespace Catch
11505 // end catch_reporter_listening.h
11508 ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig) :
11509 m_stream(&_fullConfig->stream()), m_fullConfig(_fullConfig) {}
11511 ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream) :
11512 m_stream(&_stream), m_fullConfig(_fullConfig) {}
11514 std::ostream& ReporterConfig::stream() const { return *m_stream; }
11515 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11517 TestRunInfo::TestRunInfo(std::string const& _name) : name(_name) {}
11519 GroupInfo::GroupInfo(std::string const& _name,
11520 std::size_t _groupIndex,
11521 std::size_t _groupsCount) :
11522 name(_name), groupIndex(_groupIndex), groupsCounts(_groupsCount) {}
11524 AssertionStats::AssertionStats(AssertionResult const& _assertionResult,
11525 std::vector<MessageInfo> const& _infoMessages,
11526 Totals const& _totals) :
11527 assertionResult(_assertionResult), infoMessages(_infoMessages), totals(_totals) {
11528 assertionResult.m_resultData.lazyExpression.m_transientExpression =
11529 _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11531 if (assertionResult.hasMessage()) {
11532 // Copy message into messages list.
11533 // !TBD This should have been done earlier, somewhere
11534 MessageBuilder builder(assertionResult.getTestMacroName(),
11535 assertionResult.getSourceInfo(),
11536 assertionResult.getResultType());
11537 builder << assertionResult.getMessage();
11538 builder.m_info.message = builder.m_stream.str();
11540 infoMessages.push_back(builder.m_info);
11544 AssertionStats::~AssertionStats() = default;
11546 SectionStats::SectionStats(SectionInfo const& _sectionInfo,
11547 Counts const& _assertions,
11548 double _durationInSeconds,
11549 bool _missingAssertions) :
11550 sectionInfo(_sectionInfo),
11551 assertions(_assertions),
11552 durationInSeconds(_durationInSeconds),
11553 missingAssertions(_missingAssertions) {}
11555 SectionStats::~SectionStats() = default;
11557 TestCaseStats::TestCaseStats(TestCaseInfo const& _testInfo,
11558 Totals const& _totals,
11559 std::string const& _stdOut,
11560 std::string const& _stdErr,
11562 testInfo(_testInfo),
11566 aborting(_aborting) {}
11568 TestCaseStats::~TestCaseStats() = default;
11570 TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo,
11571 Totals const& _totals,
11573 groupInfo(_groupInfo), totals(_totals), aborting(_aborting) {}
11575 TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo) :
11576 groupInfo(_groupInfo), aborting(false) {}
11578 TestGroupStats::~TestGroupStats() = default;
11580 TestRunStats::TestRunStats(TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting) :
11581 runInfo(_runInfo), totals(_totals), aborting(_aborting) {}
11583 TestRunStats::~TestRunStats() = default;
11585 void IStreamingReporter::fatalErrorEncountered(StringRef) {}
11586 bool IStreamingReporter::isMulti() const { return false; }
11588 IReporterFactory::~IReporterFactory() = default;
11589 IReporterRegistry::~IReporterRegistry() = default;
11591 } // end namespace Catch
11592 // end catch_interfaces_reporter.cpp
11593 // start catch_interfaces_runner.cpp
11596 IRunner::~IRunner() = default;
11598 // end catch_interfaces_runner.cpp
11599 // start catch_interfaces_testcase.cpp
11602 ITestInvoker::~ITestInvoker() = default;
11603 ITestCaseRegistry::~ITestCaseRegistry() = default;
11604 } // namespace Catch
11605 // end catch_interfaces_testcase.cpp
11606 // start catch_leak_detector.cpp
11608 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11609 #include <crtdbg.h>
11613 LeakDetector::LeakDetector() {
11614 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11615 flag |= _CRTDBG_LEAK_CHECK_DF;
11616 flag |= _CRTDBG_ALLOC_MEM_DF;
11617 _CrtSetDbgFlag(flag);
11618 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11619 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11620 // Change this to leaking allocation's number to break there
11621 _CrtSetBreakAlloc(-1);
11623 } // namespace Catch
11627 Catch::LeakDetector::LeakDetector() {}
11631 Catch::LeakDetector::~LeakDetector() { Catch::cleanUp(); }
11632 // end catch_leak_detector.cpp
11633 // start catch_list.cpp
11635 // start catch_list.h
11641 std::size_t listTests(Config const& config);
11643 std::size_t listTestsNamesOnly(Config const& config);
11646 void add(std::string const& spelling);
11647 std::string all() const;
11649 std::set<std::string> spellings;
11650 std::size_t count = 0;
11653 std::size_t listTags(Config const& config);
11655 std::size_t listReporters();
11657 Option<std::size_t> list(std::shared_ptr<Config> const& config);
11659 } // end namespace Catch
11661 // end catch_list.h
11662 // start catch_text.h
11665 using namespace clara::TextFlow;
11668 // end catch_text.h
11670 #include <algorithm>
11675 std::size_t listTests(Config const& config) {
11676 TestSpec const& testSpec = config.testSpec();
11677 if (config.hasTestFilters())
11678 Catch::cout() << "Matching test cases:\n";
11680 Catch::cout() << "All available test cases:\n";
11683 auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
11684 for (auto const& testCaseInfo : matchedTestCases) {
11685 Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None;
11686 Colour colourGuard(colour);
11688 Catch::cout() << Column(testCaseInfo.name).initialIndent(2).indent(4) << "\n";
11689 if (config.verbosity() >= Verbosity::High) {
11690 Catch::cout() << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4)
11692 std::string description = testCaseInfo.description;
11693 if (description.empty())
11694 description = "(NO DESCRIPTION)";
11695 Catch::cout() << Column(description).indent(4) << std::endl;
11697 if (!testCaseInfo.tags.empty())
11698 Catch::cout() << Column(testCaseInfo.tagsAsString()).indent(6) << "\n";
11701 if (!config.hasTestFilters())
11702 Catch::cout() << pluralise(matchedTestCases.size(), "test case") << '\n' << std::endl;
11704 Catch::cout() << pluralise(matchedTestCases.size(), "matching test case") << '\n'
11706 return matchedTestCases.size();
11709 std::size_t listTestsNamesOnly(Config const& config) {
11710 TestSpec const& testSpec = config.testSpec();
11711 std::size_t matchedTests = 0;
11712 std::vector<TestCase> matchedTestCases =
11713 filterTests(getAllTestCasesSorted(config), testSpec, config);
11714 for (auto const& testCaseInfo : matchedTestCases) {
11716 if (startsWith(testCaseInfo.name, '#'))
11717 Catch::cout() << '"' << testCaseInfo.name << '"';
11719 Catch::cout() << testCaseInfo.name;
11720 if (config.verbosity() >= Verbosity::High)
11721 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11722 Catch::cout() << std::endl;
11724 return matchedTests;
11727 void TagInfo::add(std::string const& spelling) {
11729 spellings.insert(spelling);
11732 std::string TagInfo::all() const {
11734 for (auto const& spelling : spellings) {
11735 // Add 2 for the brackes
11736 size += spelling.size() + 2;
11741 for (auto const& spelling : spellings) {
11749 std::size_t listTags(Config const& config) {
11750 TestSpec const& testSpec = config.testSpec();
11751 if (config.hasTestFilters())
11752 Catch::cout() << "Tags for matching test cases:\n";
11754 Catch::cout() << "All available tags:\n";
11757 std::map<std::string, TagInfo> tagCounts;
11759 std::vector<TestCase> matchedTestCases =
11760 filterTests(getAllTestCasesSorted(config), testSpec, config);
11761 for (auto const& testCase : matchedTestCases) {
11762 for (auto const& tagName : testCase.getTestCaseInfo().tags) {
11763 std::string lcaseTagName = toLower(tagName);
11764 auto countIt = tagCounts.find(lcaseTagName);
11765 if (countIt == tagCounts.end())
11766 countIt = tagCounts.insert(std::make_pair(lcaseTagName, TagInfo())).first;
11767 countIt->second.add(tagName);
11771 for (auto const& tagCount : tagCounts) {
11772 ReusableStringStream rss;
11773 rss << " " << std::setw(2) << tagCount.second.count << " ";
11774 auto str = rss.str();
11775 auto wrapper = Column(tagCount.second.all())
11777 .indent(str.size())
11778 .width(CATCH_CONFIG_CONSOLE_WIDTH - 10);
11779 Catch::cout() << str << wrapper << '\n';
11781 Catch::cout() << pluralise(tagCounts.size(), "tag") << '\n' << std::endl;
11782 return tagCounts.size();
11785 std::size_t listReporters() {
11786 Catch::cout() << "Available reporters:\n";
11787 IReporterRegistry::FactoryMap const& factories =
11788 getRegistryHub().getReporterRegistry().getFactories();
11789 std::size_t maxNameLen = 0;
11790 for (auto const& factoryKvp : factories)
11791 maxNameLen = (std::max)(maxNameLen, factoryKvp.first.size());
11793 for (auto const& factoryKvp : factories) {
11794 Catch::cout() << Column(factoryKvp.first + ":").indent(2).width(5 + maxNameLen) +
11795 Column(factoryKvp.second->getDescription())
11798 .width(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)
11801 Catch::cout() << std::endl;
11802 return factories.size();
11805 Option<std::size_t> list(std::shared_ptr<Config> const& config) {
11806 Option<std::size_t> listedCount;
11807 getCurrentMutableContext().setConfig(config);
11808 if (config->listTests())
11809 listedCount = listedCount.valueOr(0) + listTests(*config);
11810 if (config->listTestNamesOnly())
11811 listedCount = listedCount.valueOr(0) + listTestsNamesOnly(*config);
11812 if (config->listTags())
11813 listedCount = listedCount.valueOr(0) + listTags(*config);
11814 if (config->listReporters())
11815 listedCount = listedCount.valueOr(0) + listReporters();
11816 return listedCount;
11819 } // end namespace Catch
11820 // end catch_list.cpp
11821 // start catch_matchers.cpp
11824 namespace Matchers {
11827 std::string MatcherUntypedBase::toString() const {
11828 if (m_cachedToString.empty())
11829 m_cachedToString = describe();
11830 return m_cachedToString;
11833 MatcherUntypedBase::~MatcherUntypedBase() = default;
11835 } // namespace Impl
11836 } // namespace Matchers
11838 using namespace Matchers;
11839 using Matchers::Impl::MatcherBase;
11841 } // namespace Catch
11842 // end catch_matchers.cpp
11843 // start catch_matchers_exception.cpp
11846 namespace Matchers {
11847 namespace Exception {
11849 bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11850 return ex.what() == m_message;
11853 std::string ExceptionMessageMatcher::describe() const {
11854 return "exception message matches \"" + m_message + "\"";
11857 } // namespace Exception
11858 Exception::ExceptionMessageMatcher Message(std::string const& message) {
11859 return Exception::ExceptionMessageMatcher(message);
11862 // namespace Exception
11863 } // namespace Matchers
11864 } // namespace Catch
11865 // end catch_matchers_exception.cpp
11866 // start catch_matchers_floating.cpp
11868 // start catch_polyfills.hpp
11871 bool isnan(float f);
11872 bool isnan(double d);
11873 } // namespace Catch
11875 // end catch_polyfills.hpp
11876 // start catch_to_string.hpp
11881 template <typename T> std::string to_string(T const& t) {
11882 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11883 return std::to_string(t);
11885 ReusableStringStream rss;
11890 } // end namespace Catch
11892 // end catch_to_string.hpp
11893 #include <algorithm>
11899 #include <type_traits>
11906 int32_t convert(float f) {
11907 static_assert(sizeof(float) == sizeof(int32_t),
11908 "Important ULP matcher assumption violated");
11910 std::memcpy(&i, &f, sizeof(f));
11914 int64_t convert(double d) {
11915 static_assert(sizeof(double) == sizeof(int64_t),
11916 "Important ULP matcher assumption violated");
11918 std::memcpy(&i, &d, sizeof(d));
11922 template <typename FP> bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11923 // Comparison with NaN should always be false.
11924 // This way we can rule it out before getting into the ugly details
11925 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11929 auto lc = convert(lhs);
11930 auto rc = convert(rhs);
11932 if ((lc < 0) != (rc < 0)) {
11933 // Potentially we can have +0 and -0
11937 // static cast as a workaround for IBM XLC
11938 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11939 return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11942 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11944 float nextafter(float x, float y) { return ::nextafterf(x, y); }
11946 double nextafter(double x, double y) { return ::nextafter(x, y); }
11948 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11950 template <typename FP> FP step(FP start, FP direction, uint64_t steps) {
11951 for (uint64_t i = 0; i < steps; ++i) {
11952 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11953 start = Catch::nextafter(start, direction);
11955 start = std::nextafter(start, direction);
11961 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11962 // But without the subtraction to allow for INFINITY in comparison
11963 bool marginComparison(double lhs, double rhs, double margin) {
11964 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11967 template <typename FloatingPoint> void write(std::ostream& out, FloatingPoint num) {
11968 out << std::scientific
11969 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) << num;
11972 } // end anonymous namespace
11974 namespace Matchers {
11975 namespace Floating {
11977 enum class FloatingPointKind : uint8_t { Float, Double };
11979 WithinAbsMatcher::WithinAbsMatcher(double target, double margin) :
11980 m_target{target}, m_margin{margin} {
11981 CATCH_ENFORCE(margin >= 0,
11982 "Invalid margin: " << margin << '.'
11983 << " Margin has to be non-negative.");
11986 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11987 // But without the subtraction to allow for INFINITY in comparison
11988 bool WithinAbsMatcher::match(double const& matchee) const {
11989 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11992 std::string WithinAbsMatcher::describe() const {
11993 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " +
11994 ::Catch::Detail::stringify(m_target);
11997 WithinUlpsMatcher::WithinUlpsMatcher(double target,
11999 FloatingPointKind baseType) :
12000 m_target{target}, m_ulps{ulps}, m_type{baseType} {
12001 CATCH_ENFORCE(m_type == FloatingPointKind::Double ||
12002 m_ulps < (std::numeric_limits<uint32_t>::max)(),
12003 "Provided ULP is impossibly large for a float comparison.");
12006 #if defined(__clang__)
12007 #pragma clang diagnostic push
12008 // Clang <3.5 reports on the default branch in the switch below
12009 #pragma clang diagnostic ignored "-Wunreachable-code"
12012 bool WithinUlpsMatcher::match(double const& matchee) const {
12014 case FloatingPointKind::Float:
12015 return almostEqualUlps<float>(
12016 static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
12017 case FloatingPointKind::Double:
12018 return almostEqualUlps<double>(matchee, m_target, m_ulps);
12020 CATCH_INTERNAL_ERROR("Unknown FloatingPointKind value");
12024 #if defined(__clang__)
12025 #pragma clang diagnostic pop
12028 std::string WithinUlpsMatcher::describe() const {
12029 std::stringstream ret;
12031 ret << "is within " << m_ulps << " ULPs of ";
12033 if (m_type == FloatingPointKind::Float) {
12034 write(ret, static_cast<float>(m_target));
12037 write(ret, m_target);
12041 if (m_type == FloatingPointKind::Double) {
12042 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
12044 write(ret, step(m_target, static_cast<double>(INFINITY), m_ulps));
12046 // We have to cast INFINITY to float because of MinGW, see
12050 step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
12053 step(static_cast<float>(m_target), static_cast<float>(INFINITY), m_ulps));
12060 WithinRelMatcher::WithinRelMatcher(double target, double epsilon) :
12061 m_target(target), m_epsilon(epsilon) {
12062 CATCH_ENFORCE(m_epsilon >= 0.,
12063 "Relative comparison with epsilon < 0 does not "
12065 CATCH_ENFORCE(m_epsilon < 1.,
12066 "Relative comparison with epsilon >= 1 does not "
12070 bool WithinRelMatcher::match(double const& matchee) const {
12071 const auto relMargin =
12072 m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
12073 return marginComparison(matchee, m_target, std::isinf(relMargin) ? 0 : relMargin);
12076 std::string WithinRelMatcher::describe() const {
12077 Catch::ReusableStringStream sstr;
12078 sstr << "and " << m_target << " are within " << m_epsilon * 100.
12079 << "% of each other";
12083 } // namespace Floating
12085 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
12086 return Floating::WithinUlpsMatcher(
12087 target, maxUlpDiff, Floating::FloatingPointKind::Double);
12090 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
12091 return Floating::WithinUlpsMatcher(
12092 target, maxUlpDiff, Floating::FloatingPointKind::Float);
12095 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
12096 return Floating::WithinAbsMatcher(target, margin);
12099 Floating::WithinRelMatcher WithinRel(double target, double eps) {
12100 return Floating::WithinRelMatcher(target, eps);
12103 Floating::WithinRelMatcher WithinRel(double target) {
12104 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
12107 Floating::WithinRelMatcher WithinRel(float target, float eps) {
12108 return Floating::WithinRelMatcher(target, eps);
12111 Floating::WithinRelMatcher WithinRel(float target) {
12112 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
12115 } // namespace Matchers
12116 } // namespace Catch
12117 // end catch_matchers_floating.cpp
12118 // start catch_matchers_generic.cpp
12120 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
12121 if (desc.empty()) {
12122 return "matches undescribed predicate";
12124 return "matches predicate: \"" + desc + '"';
12127 // end catch_matchers_generic.cpp
12128 // start catch_matchers_string.cpp
12133 namespace Matchers {
12135 namespace StdString {
12137 CasedString::CasedString(std::string const& str,
12138 CaseSensitive::Choice caseSensitivity) :
12139 m_caseSensitivity(caseSensitivity), m_str(adjustString(str)) {}
12140 std::string CasedString::adjustString(std::string const& str) const {
12141 return m_caseSensitivity == CaseSensitive::No ? toLower(str) : str;
12143 std::string CasedString::caseSensitivitySuffix() const {
12144 return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)"
12148 StringMatcherBase::StringMatcherBase(std::string const& operation,
12149 CasedString const& comparator) :
12150 m_comparator(comparator), m_operation(operation) {}
12152 std::string StringMatcherBase::describe() const {
12153 std::string description;
12154 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
12155 m_comparator.caseSensitivitySuffix().size());
12156 description += m_operation;
12157 description += ": \"";
12158 description += m_comparator.m_str;
12159 description += "\"";
12160 description += m_comparator.caseSensitivitySuffix();
12161 return description;
12164 EqualsMatcher::EqualsMatcher(CasedString const& comparator) :
12165 StringMatcherBase("equals", comparator) {}
12167 bool EqualsMatcher::match(std::string const& source) const {
12168 return m_comparator.adjustString(source) == m_comparator.m_str;
12171 ContainsMatcher::ContainsMatcher(CasedString const& comparator) :
12172 StringMatcherBase("contains", comparator) {}
12174 bool ContainsMatcher::match(std::string const& source) const {
12175 return contains(m_comparator.adjustString(source), m_comparator.m_str);
12178 StartsWithMatcher::StartsWithMatcher(CasedString const& comparator) :
12179 StringMatcherBase("starts with", comparator) {}
12181 bool StartsWithMatcher::match(std::string const& source) const {
12182 return startsWith(m_comparator.adjustString(source), m_comparator.m_str);
12185 EndsWithMatcher::EndsWithMatcher(CasedString const& comparator) :
12186 StringMatcherBase("ends with", comparator) {}
12188 bool EndsWithMatcher::match(std::string const& source) const {
12189 return endsWith(m_comparator.adjustString(source), m_comparator.m_str);
12192 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity) :
12193 m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
12195 bool RegexMatcher::match(std::string const& matchee) const {
12196 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax
12198 if (m_caseSensitivity == CaseSensitive::Choice::No) {
12199 flags |= std::regex::icase;
12201 auto reg = std::regex(m_regex, flags);
12202 return std::regex_match(matchee, reg);
12205 std::string RegexMatcher::describe() const {
12206 return "matches " + ::Catch::Detail::stringify(m_regex) +
12207 ((m_caseSensitivity == CaseSensitive::Choice::Yes) ? " case sensitively"
12208 : " case insensitively");
12211 } // namespace StdString
12213 StdString::EqualsMatcher Equals(std::string const& str,
12214 CaseSensitive::Choice caseSensitivity) {
12215 return StdString::EqualsMatcher(StdString::CasedString(str, caseSensitivity));
12217 StdString::ContainsMatcher Contains(std::string const& str,
12218 CaseSensitive::Choice caseSensitivity) {
12219 return StdString::ContainsMatcher(StdString::CasedString(str, caseSensitivity));
12221 StdString::EndsWithMatcher EndsWith(std::string const& str,
12222 CaseSensitive::Choice caseSensitivity) {
12223 return StdString::EndsWithMatcher(StdString::CasedString(str, caseSensitivity));
12225 StdString::StartsWithMatcher StartsWith(std::string const& str,
12226 CaseSensitive::Choice caseSensitivity) {
12227 return StdString::StartsWithMatcher(StdString::CasedString(str, caseSensitivity));
12230 StdString::RegexMatcher Matches(std::string const& regex,
12231 CaseSensitive::Choice caseSensitivity) {
12232 return StdString::RegexMatcher(regex, caseSensitivity);
12235 } // namespace Matchers
12236 } // namespace Catch
12237 // end catch_matchers_string.cpp
12238 // start catch_message.cpp
12240 // start catch_uncaught_exceptions.h
12243 bool uncaught_exceptions();
12244 } // end namespace Catch
12246 // end catch_uncaught_exceptions.h
12252 MessageInfo::MessageInfo(StringRef const& _macroName,
12253 SourceLineInfo const& _lineInfo,
12254 ResultWas::OfType _type) :
12255 macroName(_macroName), lineInfo(_lineInfo), type(_type), sequence(++globalCount) {}
12257 bool MessageInfo::operator==(MessageInfo const& other) const {
12258 return sequence == other.sequence;
12261 bool MessageInfo::operator<(MessageInfo const& other) const {
12262 return sequence < other.sequence;
12265 // This may need protecting if threading support is added
12266 unsigned int MessageInfo::globalCount = 0;
12268 ////////////////////////////////////////////////////////////////////////////
12270 Catch::MessageBuilder::MessageBuilder(StringRef const& macroName,
12271 SourceLineInfo const& lineInfo,
12272 ResultWas::OfType type) :
12273 m_info(macroName, lineInfo, type) {}
12275 ////////////////////////////////////////////////////////////////////////////
12277 ScopedMessage::ScopedMessage(MessageBuilder const& builder) :
12278 m_info(builder.m_info), m_moved() {
12279 m_info.message = builder.m_stream.str();
12280 getResultCapture().pushScopedMessage(m_info);
12283 ScopedMessage::ScopedMessage(ScopedMessage&& old) : m_info(old.m_info), m_moved() {
12284 old.m_moved = true;
12287 ScopedMessage::~ScopedMessage() {
12288 if (!uncaught_exceptions() && !m_moved) {
12289 getResultCapture().popScopedMessage(m_info);
12293 Capturer::Capturer(StringRef macroName,
12294 SourceLineInfo const& lineInfo,
12295 ResultWas::OfType resultType,
12297 auto trimmed = [&](size_t start, size_t end) {
12298 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
12301 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
12304 return names.substr(start, end - start + 1);
12306 auto skipq = [&](size_t start, char quote) {
12307 for (auto i = start + 1; i < names.size(); ++i) {
12308 if (names[i] == quote)
12310 if (names[i] == '\\')
12313 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
12317 std::stack<char> openings;
12318 for (size_t pos = 0; pos < names.size(); ++pos) {
12319 char c = names[pos];
12324 // It is basically impossible to disambiguate between
12325 // comparison and start of template args in this context
12337 pos = skipq(pos, c);
12340 if (start != pos && openings.empty()) {
12341 m_messages.emplace_back(macroName, lineInfo, resultType);
12342 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
12343 m_messages.back().message += " := ";
12348 assert(openings.empty() && "Mismatched openings");
12349 m_messages.emplace_back(macroName, lineInfo, resultType);
12350 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
12351 m_messages.back().message += " := ";
12353 Capturer::~Capturer() {
12354 if (!uncaught_exceptions()) {
12355 assert(m_captured == m_messages.size());
12356 for (size_t i = 0; i < m_captured; ++i)
12357 m_resultCapture.popScopedMessage(m_messages[i]);
12361 void Capturer::captureValue(size_t index, std::string const& value) {
12362 assert(index < m_messages.size());
12363 m_messages[index].message += value;
12364 m_resultCapture.pushScopedMessage(m_messages[index]);
12368 } // end namespace Catch
12369 // end catch_message.cpp
12370 // start catch_output_redirect.cpp
12372 // start catch_output_redirect.h
12373 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12374 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12382 class RedirectedStream {
12383 std::ostream& m_originalStream;
12384 std::ostream& m_redirectionStream;
12385 std::streambuf* m_prevBuf;
12388 RedirectedStream(std::ostream& originalStream, std::ostream& redirectionStream);
12389 ~RedirectedStream();
12392 class RedirectedStdOut {
12393 ReusableStringStream m_rss;
12394 RedirectedStream m_cout;
12397 RedirectedStdOut();
12398 auto str() const -> std::string;
12401 // StdErr has two constituent streams in C++, std::cerr and std::clog
12402 // This means that we need to redirect 2 streams into 1 to keep proper
12404 class RedirectedStdErr {
12405 ReusableStringStream m_rss;
12406 RedirectedStream m_cerr;
12407 RedirectedStream m_clog;
12410 RedirectedStdErr();
12411 auto str() const -> std::string;
12414 class RedirectedStreams {
12416 RedirectedStreams(RedirectedStreams const&) = delete;
12417 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
12418 RedirectedStreams(RedirectedStreams&&) = delete;
12419 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
12421 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
12422 ~RedirectedStreams();
12425 std::string& m_redirectedCout;
12426 std::string& m_redirectedCerr;
12427 RedirectedStdOut m_redirectedStdOut;
12428 RedirectedStdErr m_redirectedStdErr;
12431 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12433 // Windows's implementation of std::tmpfile is terrible (it tries
12434 // to create a file inside system folder, thus requiring elevated
12435 // privileges for the binary), so we have to use tmpnam(_s) and
12436 // create the file ourselves there.
12439 TempFile(TempFile const&) = delete;
12440 TempFile& operator=(TempFile const&) = delete;
12441 TempFile(TempFile&&) = delete;
12442 TempFile& operator=(TempFile&&) = delete;
12447 std::FILE* getFile();
12448 std::string getContents();
12451 std::FILE* m_file = nullptr;
12452 #if defined(_MSC_VER)
12453 char m_buffer[L_tmpnam] = {0};
12457 class OutputRedirect {
12459 OutputRedirect(OutputRedirect const&) = delete;
12460 OutputRedirect& operator=(OutputRedirect const&) = delete;
12461 OutputRedirect(OutputRedirect&&) = delete;
12462 OutputRedirect& operator=(OutputRedirect&&) = delete;
12464 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12468 int m_originalStdout = -1;
12469 int m_originalStderr = -1;
12470 TempFile m_stdoutFile;
12471 TempFile m_stderrFile;
12472 std::string& m_stdoutDest;
12473 std::string& m_stderrDest;
12478 } // end namespace Catch
12480 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12481 // end catch_output_redirect.h
12486 #include <stdexcept>
12488 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12489 #if defined(_MSC_VER)
12490 #include <io.h> //_dup and _dup2
12493 #define fileno _fileno
12495 #include <unistd.h> // dup and dup2
12501 RedirectedStream::RedirectedStream(std::ostream& originalStream,
12502 std::ostream& redirectionStream) :
12503 m_originalStream(originalStream),
12504 m_redirectionStream(redirectionStream),
12505 m_prevBuf(m_originalStream.rdbuf()) {
12506 m_originalStream.rdbuf(m_redirectionStream.rdbuf());
12509 RedirectedStream::~RedirectedStream() { m_originalStream.rdbuf(m_prevBuf); }
12511 RedirectedStdOut::RedirectedStdOut() : m_cout(Catch::cout(), m_rss.get()) {}
12512 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12514 RedirectedStdErr::RedirectedStdErr() :
12515 m_cerr(Catch::cerr(), m_rss.get()), m_clog(Catch::clog(), m_rss.get()) {}
12516 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12518 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr) :
12519 m_redirectedCout(redirectedCout), m_redirectedCerr(redirectedCerr) {}
12521 RedirectedStreams::~RedirectedStreams() {
12522 m_redirectedCout += m_redirectedStdOut.str();
12523 m_redirectedCerr += m_redirectedStdErr.str();
12526 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12528 #if defined(_MSC_VER)
12529 TempFile::TempFile() {
12530 if (tmpnam_s(m_buffer)) {
12531 CATCH_RUNTIME_ERROR("Could not get a temp filename");
12533 if (fopen_s(&m_file, m_buffer, "w+")) {
12535 if (strerror_s(buffer, errno)) {
12536 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12538 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer
12539 << "' because: " << buffer);
12543 TempFile::TempFile() {
12544 m_file = std::tmpfile();
12546 CATCH_RUNTIME_ERROR("Could not create a temp file.");
12552 TempFile::~TempFile() {
12553 // TBD: What to do about errors here?
12554 std::fclose(m_file);
12555 // We manually create the file on Windows only, on Linux
12556 // it will be autodeleted
12557 #if defined(_MSC_VER)
12558 std::remove(m_buffer);
12562 FILE* TempFile::getFile() { return m_file; }
12564 std::string TempFile::getContents() {
12565 std::stringstream sstr;
12566 char buffer[100] = {};
12567 std::rewind(m_file);
12568 while (std::fgets(buffer, sizeof(buffer), m_file)) {
12574 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12575 m_originalStdout(dup(1)),
12576 m_originalStderr(dup(2)),
12577 m_stdoutDest(stdout_dest),
12578 m_stderrDest(stderr_dest) {
12579 dup2(fileno(m_stdoutFile.getFile()), 1);
12580 dup2(fileno(m_stderrFile.getFile()), 2);
12583 OutputRedirect::~OutputRedirect() {
12584 Catch::cout() << std::flush;
12586 // Since we support overriding these streams, we flush cerr
12587 // even though std::cerr is unbuffered
12588 Catch::cerr() << std::flush;
12589 Catch::clog() << std::flush;
12592 dup2(m_originalStdout, 1);
12593 dup2(m_originalStderr, 2);
12595 m_stdoutDest += m_stdoutFile.getContents();
12596 m_stderrDest += m_stderrFile.getContents();
12599 #endif // CATCH_CONFIG_NEW_CAPTURE
12601 } // namespace Catch
12603 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12604 #if defined(_MSC_VER)
12610 // end catch_output_redirect.cpp
12611 // start catch_polyfills.cpp
12617 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12618 bool isnan(float f) { return std::isnan(f); }
12619 bool isnan(double d) { return std::isnan(d); }
12621 // For now we only use this for embarcadero
12622 bool isnan(float f) { return std::_isnan(f); }
12623 bool isnan(double d) { return std::_isnan(d); }
12626 } // end namespace Catch
12627 // end catch_polyfills.cpp
12628 // start catch_random_number_generator.cpp
12634 #if defined(_MSC_VER)
12635 #pragma warning(push)
12636 #pragma warning(disable : 4146) // we negate uint32 during the rotate
12638 // Safe rotr implementation thanks to John Regehr
12639 uint32_t rotate_right(uint32_t val, uint32_t count) {
12640 const uint32_t mask = 31;
12642 return (val >> count) | (val << (-count & mask));
12645 #if defined(_MSC_VER)
12646 #pragma warning(pop)
12651 SimplePcg32::SimplePcg32(result_type seed_) { seed(seed_); }
12653 void SimplePcg32::seed(result_type seed_) {
12660 void SimplePcg32::discard(uint64_t skip) {
12661 // We could implement this to run in O(log n) steps, but this
12662 // should suffice for our use case.
12663 for (uint64_t s = 0; s < skip; ++s) {
12664 static_cast<void>((*this)());
12668 SimplePcg32::result_type SimplePcg32::operator()() {
12669 // prepare the output value
12670 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12671 const auto output = rotate_right(xorshifted, m_state >> 59u);
12674 m_state = m_state * 6364136223846793005ULL + s_inc;
12679 bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12680 return lhs.m_state == rhs.m_state;
12683 bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12684 return lhs.m_state != rhs.m_state;
12686 } // namespace Catch
12687 // end catch_random_number_generator.cpp
12688 // start catch_registry_hub.cpp
12690 // start catch_test_case_registry_impl.h
12694 #include <algorithm>
12702 std::vector<TestCase> sortTests(IConfig const& config,
12703 std::vector<TestCase> const& unsortedTestCases);
12705 bool isThrowSafe(TestCase const& testCase, IConfig const& config);
12706 bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config);
12708 void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions);
12710 std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases,
12711 TestSpec const& testSpec,
12712 IConfig const& config);
12713 std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config);
12715 class TestRegistry : public ITestCaseRegistry {
12717 virtual ~TestRegistry() = default;
12719 virtual void registerTest(TestCase const& testCase);
12721 std::vector<TestCase> const& getAllTests() const override;
12722 std::vector<TestCase> const& getAllTestsSorted(IConfig const& config) const override;
12725 std::vector<TestCase> m_functions;
12726 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12727 mutable std::vector<TestCase> m_sortedFunctions;
12728 std::size_t m_unnamedCount = 0;
12729 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12732 ///////////////////////////////////////////////////////////////////////////
12734 class TestInvokerAsFunction : public ITestInvoker {
12735 void (*m_testAsFunction)();
12738 TestInvokerAsFunction(void (*testAsFunction)()) noexcept;
12740 void invoke() const override;
12743 std::string extractClassName(StringRef const& classOrQualifiedMethodName);
12745 ///////////////////////////////////////////////////////////////////////////
12747 } // end namespace Catch
12749 // end catch_test_case_registry_impl.h
12750 // start catch_reporter_registry.h
12756 class ReporterRegistry : public IReporterRegistry {
12759 ~ReporterRegistry() override;
12761 IStreamingReporterPtr create(std::string const& name,
12762 IConfigPtr const& config) const override;
12764 void registerReporter(std::string const& name, IReporterFactoryPtr const& factory);
12765 void registerListener(IReporterFactoryPtr const& factory);
12767 FactoryMap const& getFactories() const override;
12768 Listeners const& getListeners() const override;
12771 FactoryMap m_factories;
12772 Listeners m_listeners;
12774 } // namespace Catch
12776 // end catch_reporter_registry.h
12777 // start catch_tag_alias_registry.h
12779 // start catch_tag_alias.h
12786 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12789 SourceLineInfo lineInfo;
12792 } // end namespace Catch
12794 // end catch_tag_alias.h
12799 class TagAliasRegistry : public ITagAliasRegistry {
12801 ~TagAliasRegistry() override;
12802 TagAlias const* find(std::string const& alias) const override;
12803 std::string expandAliases(std::string const& unexpandedTestSpec) const override;
12804 void add(std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo);
12807 std::map<std::string, TagAlias> m_registry;
12810 } // end namespace Catch
12812 // end catch_tag_alias_registry.h
12813 // start catch_startup_exception_registry.h
12816 #include <exception>
12820 class StartupExceptionRegistry {
12821 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12823 void add(std::exception_ptr const& exception) noexcept;
12824 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12827 std::vector<std::exception_ptr> m_exceptions;
12831 } // end namespace Catch
12833 // end catch_startup_exception_registry.h
12834 // start catch_singletons.hpp
12838 struct ISingleton {
12839 virtual ~ISingleton();
12842 void addSingleton(ISingleton* singleton);
12843 void cleanupSingletons();
12845 template <typename SingletonImplT,
12846 typename InterfaceT = SingletonImplT,
12847 typename MutableInterfaceT = InterfaceT>
12848 class Singleton : SingletonImplT, public ISingleton {
12850 static auto getInternal() -> Singleton* {
12851 static Singleton* s_instance = nullptr;
12853 s_instance = new Singleton;
12854 addSingleton(s_instance);
12860 static auto get() -> InterfaceT const& { return *getInternal(); }
12861 static auto getMutable() -> MutableInterfaceT& { return *getInternal(); }
12864 } // namespace Catch
12866 // end catch_singletons.hpp
12871 class RegistryHub : public IRegistryHub, public IMutableRegistryHub, private NonCopyable {
12873 public: // IRegistryHub
12874 RegistryHub() = default;
12875 IReporterRegistry const& getReporterRegistry() const override {
12876 return m_reporterRegistry;
12878 ITestCaseRegistry const& getTestCaseRegistry() const override {
12879 return m_testCaseRegistry;
12881 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12882 return m_exceptionTranslatorRegistry;
12884 ITagAliasRegistry const& getTagAliasRegistry() const override {
12885 return m_tagAliasRegistry;
12887 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12888 return m_exceptionRegistry;
12891 public: // IMutableRegistryHub
12892 void registerReporter(std::string const& name,
12893 IReporterFactoryPtr const& factory) override {
12894 m_reporterRegistry.registerReporter(name, factory);
12896 void registerListener(IReporterFactoryPtr const& factory) override {
12897 m_reporterRegistry.registerListener(factory);
12899 void registerTest(TestCase const& testInfo) override {
12900 m_testCaseRegistry.registerTest(testInfo);
12902 void registerTranslator(const IExceptionTranslator* translator) override {
12903 m_exceptionTranslatorRegistry.registerTranslator(translator);
12905 void registerTagAlias(std::string const& alias,
12906 std::string const& tag,
12907 SourceLineInfo const& lineInfo) override {
12908 m_tagAliasRegistry.add(alias, tag, lineInfo);
12910 void registerStartupException() noexcept override {
12911 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12912 m_exceptionRegistry.add(std::current_exception());
12914 CATCH_INTERNAL_ERROR("Attempted to register active exception "
12915 "under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12918 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12919 return m_enumValuesRegistry;
12923 TestRegistry m_testCaseRegistry;
12924 ReporterRegistry m_reporterRegistry;
12925 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12926 TagAliasRegistry m_tagAliasRegistry;
12927 StartupExceptionRegistry m_exceptionRegistry;
12928 Detail::EnumValuesRegistry m_enumValuesRegistry;
12932 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12934 IRegistryHub const& getRegistryHub() { return RegistryHubSingleton::get(); }
12935 IMutableRegistryHub& getMutableRegistryHub() { return RegistryHubSingleton::getMutable(); }
12937 cleanupSingletons();
12940 std::string translateActiveException() {
12941 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12944 } // end namespace Catch
12945 // end catch_registry_hub.cpp
12946 // start catch_reporter_registry.cpp
12950 ReporterRegistry::~ReporterRegistry() = default;
12952 IStreamingReporterPtr ReporterRegistry::create(std::string const& name,
12953 IConfigPtr const& config) const {
12954 auto it = m_factories.find(name);
12955 if (it == m_factories.end())
12957 return it->second->create(ReporterConfig(config));
12960 void ReporterRegistry::registerReporter(std::string const& name,
12961 IReporterFactoryPtr const& factory) {
12962 m_factories.emplace(name, factory);
12964 void ReporterRegistry::registerListener(IReporterFactoryPtr const& factory) {
12965 m_listeners.push_back(factory);
12968 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12969 return m_factories;
12971 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12972 return m_listeners;
12975 } // namespace Catch
12976 // end catch_reporter_registry.cpp
12977 // start catch_result_type.cpp
12981 bool isOk(ResultWas::OfType resultType) { return (resultType & ResultWas::FailureBit) == 0; }
12982 bool isJustInfo(int flags) { return flags == ResultWas::Info; }
12984 ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs) {
12985 return static_cast<ResultDisposition::Flags>(static_cast<int>(lhs) | static_cast<int>(rhs));
12988 bool shouldContinueOnFailure(int flags) {
12989 return (flags & ResultDisposition::ContinueOnFailure) != 0;
12991 bool shouldSuppressFailure(int flags) { return (flags & ResultDisposition::SuppressFail) != 0; }
12993 } // end namespace Catch
12994 // end catch_result_type.cpp
12995 // start catch_run_context.cpp
12998 #include <algorithm>
13003 namespace Generators {
13004 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
13005 GeneratorBasePtr m_generator;
13007 GeneratorTracker(TestCaseTracking::NameAndLocation const& nameAndLocation,
13008 TrackerContext& ctx,
13009 ITracker* parent) :
13010 TrackerBase(nameAndLocation, ctx, parent) {}
13011 ~GeneratorTracker();
13013 static GeneratorTracker&
13014 acquire(TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation) {
13015 std::shared_ptr<GeneratorTracker> tracker;
13017 ITracker& currentTracker = ctx.currentTracker();
13018 // Under specific circumstances, the generator we want
13019 // to acquire is also the current tracker. If this is
13020 // the case, we have to avoid looking through current
13021 // tracker's children, and instead return the current
13023 // A case where this check is important is e.g.
13024 // for (int i = 0; i < 5; ++i) {
13025 // int n = GENERATE(1, 2);
13028 // without it, the code above creates 5 nested generators.
13029 if (currentTracker.nameAndLocation() == nameAndLocation) {
13030 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
13031 assert(thisTracker);
13032 assert(thisTracker->isGeneratorTracker());
13033 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
13034 } else if (TestCaseTracking::ITrackerPtr childTracker =
13035 currentTracker.findChild(nameAndLocation)) {
13036 assert(childTracker);
13037 assert(childTracker->isGeneratorTracker());
13038 tracker = std::static_pointer_cast<GeneratorTracker>(childTracker);
13041 std::make_shared<GeneratorTracker>(nameAndLocation, ctx, ¤tTracker);
13042 currentTracker.addChild(tracker);
13045 if (!tracker->isComplete()) {
13052 // TrackerBase interface
13053 bool isGeneratorTracker() const override { return true; }
13054 auto hasGenerator() const -> bool override { return !!m_generator; }
13055 void close() override {
13056 TrackerBase::close();
13057 // If a generator has a child (it is followed by a section)
13058 // and none of its children have started, then we must wait
13059 // until later to start consuming its values.
13060 // This catches cases where `GENERATE` is placed between two
13062 // **The check for m_children.empty cannot be removed**.
13063 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
13064 const bool should_wait_for_child = [&]() {
13065 // No children -> nobody to wait for
13066 if (m_children.empty()) {
13069 // If at least one child started executing, don't wait
13070 if (std::find_if(m_children.begin(),
13072 [](TestCaseTracking::ITrackerPtr tracker) {
13073 return tracker->hasStarted();
13074 }) != m_children.end())
13079 // No children have started. We need to check if they _can_
13080 // start, and thus we should wait for them, or they cannot
13081 // start (due to filters), and we shouldn't wait for them
13082 auto* parent = m_parent;
13083 // This is safe: there is always at least one section
13084 // tracker in a test case tracking tree
13085 while (!parent->isSectionTracker()) {
13086 parent = &(parent->parent());
13088 assert(parent && "Missing root (test case) level section");
13090 auto const& parentSection = static_cast<SectionTracker&>(*parent);
13091 auto const& filters = parentSection.getFilters();
13092 // No filters -> no restrictions on running sections
13093 if (filters.empty()) {
13097 for (auto const& child : m_children) {
13098 if (child->isSectionTracker() &&
13099 std::find(filters.begin(),
13101 static_cast<SectionTracker&>(*child).trimmedName()) !=
13110 // This check is a bit tricky, because m_generator->next()
13111 // has a side-effect, where it consumes generator's current
13112 // value, but we do not want to invoke the side-effect if
13113 // this generator is still waiting for any child to start.
13114 if (should_wait_for_child ||
13115 (m_runState == CompletedSuccessfully && m_generator->next())) {
13116 m_children.clear();
13117 m_runState = Executing;
13121 // IGeneratorTracker interface
13122 auto getGenerator() const -> GeneratorBasePtr const& override { return m_generator; }
13123 void setGenerator(GeneratorBasePtr&& generator) override {
13124 m_generator = std::move(generator);
13127 GeneratorTracker::~GeneratorTracker() {}
13128 } // namespace Generators
13130 RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter) :
13131 m_runInfo(_config->name()),
13132 m_context(getCurrentMutableContext()),
13134 m_reporter(std::move(reporter)),
13135 m_lastAssertionInfo{
13136 StringRef(), SourceLineInfo("", 0), StringRef(), ResultDisposition::Normal},
13137 m_includeSuccessfulResults(m_config->includeSuccessfulResults() ||
13138 m_reporter->getPreferences().shouldReportAllAssertions) {
13139 m_context.setRunner(this);
13140 m_context.setConfig(m_config);
13141 m_context.setResultCapture(this);
13142 m_reporter->testRunStarting(m_runInfo);
13145 RunContext::~RunContext() {
13146 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
13149 void RunContext::testGroupStarting(std::string const& testSpec,
13150 std::size_t groupIndex,
13151 std::size_t groupsCount) {
13152 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
13155 void RunContext::testGroupEnded(std::string const& testSpec,
13156 Totals const& totals,
13157 std::size_t groupIndex,
13158 std::size_t groupsCount) {
13159 m_reporter->testGroupEnded(
13160 TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
13163 Totals RunContext::runTest(TestCase const& testCase) {
13164 Totals prevTotals = m_totals;
13166 std::string redirectedCout;
13167 std::string redirectedCerr;
13169 auto const& testInfo = testCase.getTestCaseInfo();
13171 m_reporter->testCaseStarting(testInfo);
13173 m_activeTestCase = &testCase;
13175 ITracker& rootTracker = m_trackerContext.startRun();
13176 assert(rootTracker.isSectionTracker());
13177 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
13179 m_trackerContext.startCycle();
13180 m_testCaseTracker = &SectionTracker::acquire(
13182 TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
13183 runCurrentTest(redirectedCout, redirectedCerr);
13184 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
13186 Totals deltaTotals = m_totals.delta(prevTotals);
13187 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
13188 deltaTotals.assertions.failed++;
13189 deltaTotals.testCases.passed--;
13190 deltaTotals.testCases.failed++;
13192 m_totals.testCases += deltaTotals.testCases;
13193 m_reporter->testCaseEnded(
13194 TestCaseStats(testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting()));
13196 m_activeTestCase = nullptr;
13197 m_testCaseTracker = nullptr;
13199 return deltaTotals;
13202 IConfigPtr RunContext::config() const { return m_config; }
13204 IStreamingReporter& RunContext::reporter() const { return *m_reporter; }
13206 void RunContext::assertionEnded(AssertionResult const& result) {
13207 if (result.getResultType() == ResultWas::Ok) {
13208 m_totals.assertions.passed++;
13209 m_lastAssertionPassed = true;
13210 } else if (!result.isOk()) {
13211 m_lastAssertionPassed = false;
13212 if (m_activeTestCase->getTestCaseInfo().okToFail())
13213 m_totals.assertions.failedButOk++;
13215 m_totals.assertions.failed++;
13217 m_lastAssertionPassed = true;
13220 // We have no use for the return value (whether messages should be
13221 // cleared), because messages were made scoped and should be let to
13222 // clear themselves out.
13223 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
13225 if (result.getResultType() != ResultWas::Warning)
13226 m_messageScopes.clear();
13228 // Reset working state
13229 resetAssertionInfo();
13230 m_lastResult = result;
13232 void RunContext::resetAssertionInfo() {
13233 m_lastAssertionInfo.macroName = StringRef();
13234 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
13237 bool RunContext::sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) {
13238 ITracker& sectionTracker = SectionTracker::acquire(
13240 TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
13241 if (!sectionTracker.isOpen())
13243 m_activeSections.push_back(§ionTracker);
13245 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
13247 m_reporter->sectionStarting(sectionInfo);
13249 assertions = m_totals.assertions;
13253 auto RunContext::acquireGeneratorTracker(StringRef generatorName,
13254 SourceLineInfo const& lineInfo) -> IGeneratorTracker& {
13255 using namespace Generators;
13256 GeneratorTracker& tracker = GeneratorTracker::acquire(
13258 TestCaseTracking::NameAndLocation(static_cast<std::string>(generatorName), lineInfo));
13259 m_lastAssertionInfo.lineInfo = lineInfo;
13263 bool RunContext::testForMissingAssertions(Counts& assertions) {
13264 if (assertions.total() != 0)
13266 if (!m_config->warnAboutMissingAssertions())
13268 if (m_trackerContext.currentTracker().hasChildren())
13270 m_totals.assertions.failed++;
13271 assertions.failed++;
13275 void RunContext::sectionEnded(SectionEndInfo const& endInfo) {
13276 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
13277 bool missingAssertions = testForMissingAssertions(assertions);
13279 if (!m_activeSections.empty()) {
13280 m_activeSections.back()->close();
13281 m_activeSections.pop_back();
13284 m_reporter->sectionEnded(SectionStats(
13285 endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
13286 m_messages.clear();
13287 m_messageScopes.clear();
13290 void RunContext::sectionEndedEarly(SectionEndInfo const& endInfo) {
13291 if (m_unfinishedSections.empty())
13292 m_activeSections.back()->fail();
13294 m_activeSections.back()->close();
13295 m_activeSections.pop_back();
13297 m_unfinishedSections.push_back(endInfo);
13300 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
13301 void RunContext::benchmarkPreparing(std::string const& name) {
13302 m_reporter->benchmarkPreparing(name);
13304 void RunContext::benchmarkStarting(BenchmarkInfo const& info) {
13305 m_reporter->benchmarkStarting(info);
13307 void RunContext::benchmarkEnded(BenchmarkStats<> const& stats) {
13308 m_reporter->benchmarkEnded(stats);
13310 void RunContext::benchmarkFailed(std::string const& error) {
13311 m_reporter->benchmarkFailed(error);
13313 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
13315 void RunContext::pushScopedMessage(MessageInfo const& message) {
13316 m_messages.push_back(message);
13319 void RunContext::popScopedMessage(MessageInfo const& message) {
13320 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message),
13324 void RunContext::emplaceUnscopedMessage(MessageBuilder const& builder) {
13325 m_messageScopes.emplace_back(builder);
13328 std::string RunContext::getCurrentTestName() const {
13329 return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string();
13332 const AssertionResult* RunContext::getLastResult() const { return &(*m_lastResult); }
13334 void RunContext::exceptionEarlyReported() { m_shouldReportUnexpected = false; }
13336 void RunContext::handleFatalErrorCondition(StringRef message) {
13337 // First notify reporter that bad things happened
13338 m_reporter->fatalErrorEncountered(message);
13340 // Don't rebuild the result -- the stringification itself can cause more
13341 // fatal errors Instead, fake a result data.
13342 AssertionResultData tempResult(ResultWas::FatalErrorCondition, {false});
13343 tempResult.message = static_cast<std::string>(message);
13344 AssertionResult result(m_lastAssertionInfo, tempResult);
13346 assertionEnded(result);
13348 handleUnfinishedSections();
13350 // Recreate section for test case (as we will lose the one that was in
13352 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
13353 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13356 assertions.failed = 1;
13357 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
13358 m_reporter->sectionEnded(testCaseSectionStats);
13360 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
13362 Totals deltaTotals;
13363 deltaTotals.testCases.failed = 1;
13364 deltaTotals.assertions.failed = 1;
13365 m_reporter->testCaseEnded(
13366 TestCaseStats(testInfo, deltaTotals, std::string(), std::string(), false));
13367 m_totals.testCases.failed++;
13368 testGroupEnded(std::string(), m_totals, 1, 1);
13369 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
13372 bool RunContext::lastAssertionPassed() { return m_lastAssertionPassed; }
13374 void RunContext::assertionPassed() {
13375 m_lastAssertionPassed = true;
13376 ++m_totals.assertions.passed;
13377 resetAssertionInfo();
13378 m_messageScopes.clear();
13381 bool RunContext::aborting() const {
13382 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
13385 void RunContext::runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr) {
13386 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
13387 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13388 m_reporter->sectionStarting(testCaseSection);
13389 Counts prevAssertions = m_totals.assertions;
13390 double duration = 0;
13391 m_shouldReportUnexpected = true;
13392 m_lastAssertionInfo = {
13393 "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal};
13395 seedRng(*m_config);
13399 if (m_reporter->getPreferences().shouldRedirectStdOut) {
13400 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
13401 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
13404 invokeActiveTestCase();
13406 OutputRedirect r(redirectedCout, redirectedCerr);
13408 invokeActiveTestCase();
13412 invokeActiveTestCase();
13414 duration = timer.getElapsedSeconds();
13416 CATCH_CATCH_ANON(TestFailureException&) {
13417 // This just means the test was aborted due to failure
13420 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under
13421 // REQUIRE assertions are reported without translation at the point
13423 if (m_shouldReportUnexpected) {
13424 AssertionReaction dummyReaction;
13425 handleUnexpectedInflightException(
13426 m_lastAssertionInfo, translateActiveException(), dummyReaction);
13429 Counts assertions = m_totals.assertions - prevAssertions;
13430 bool missingAssertions = testForMissingAssertions(assertions);
13432 m_testCaseTracker->close();
13433 handleUnfinishedSections();
13434 m_messages.clear();
13435 m_messageScopes.clear();
13437 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13438 m_reporter->sectionEnded(testCaseSectionStats);
13441 void RunContext::invokeActiveTestCase() {
13442 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13443 m_activeTestCase->invoke();
13446 void RunContext::handleUnfinishedSections() {
13447 // If sections ended prematurely due to an exception we stored their
13448 // infos here so we can tear them down outside the unwind process.
13449 for (auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend();
13453 m_unfinishedSections.clear();
13456 void RunContext::handleExpr(AssertionInfo const& info,
13457 ITransientExpression const& expr,
13458 AssertionReaction& reaction) {
13459 m_reporter->assertionStarting(info);
13461 bool negated = isFalseTest(info.resultDisposition);
13462 bool result = expr.getResult() != negated;
13465 if (!m_includeSuccessfulResults) {
13468 reportExpr(info, ResultWas::Ok, &expr, negated);
13471 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated);
13472 populateReaction(reaction);
13475 void RunContext::reportExpr(AssertionInfo const& info,
13476 ResultWas::OfType resultType,
13477 ITransientExpression const* expr,
13480 m_lastAssertionInfo = info;
13481 AssertionResultData data(resultType, LazyExpression(negated));
13483 AssertionResult assertionResult{info, data};
13484 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13486 assertionEnded(assertionResult);
13489 void RunContext::handleMessage(AssertionInfo const& info,
13490 ResultWas::OfType resultType,
13491 StringRef const& message,
13492 AssertionReaction& reaction) {
13493 m_reporter->assertionStarting(info);
13495 m_lastAssertionInfo = info;
13497 AssertionResultData data(resultType, LazyExpression(false));
13498 data.message = static_cast<std::string>(message);
13499 AssertionResult assertionResult{m_lastAssertionInfo, data};
13500 assertionEnded(assertionResult);
13501 if (!assertionResult.isOk())
13502 populateReaction(reaction);
13504 void RunContext::handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
13505 AssertionReaction& reaction) {
13506 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13509 void RunContext::handleUnexpectedInflightException(AssertionInfo const& info,
13510 std::string const& message,
13511 AssertionReaction& reaction) {
13512 m_lastAssertionInfo = info;
13514 AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13515 data.message = message;
13516 AssertionResult assertionResult{info, data};
13517 assertionEnded(assertionResult);
13518 populateReaction(reaction);
13521 void RunContext::populateReaction(AssertionReaction& reaction) {
13522 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13523 reaction.shouldThrow =
13524 aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13527 void RunContext::handleIncomplete(AssertionInfo const& info) {
13528 m_lastAssertionInfo = info;
13530 AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13531 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13532 AssertionResult assertionResult{info, data};
13533 assertionEnded(assertionResult);
13535 void RunContext::handleNonExpr(AssertionInfo const& info,
13536 ResultWas::OfType resultType,
13537 AssertionReaction& reaction) {
13538 m_lastAssertionInfo = info;
13540 AssertionResultData data(resultType, LazyExpression(false));
13541 AssertionResult assertionResult{info, data};
13542 assertionEnded(assertionResult);
13544 if (!assertionResult.isOk())
13545 populateReaction(reaction);
13548 IResultCapture& getResultCapture() {
13549 if (auto* capture = getCurrentContext().getResultCapture())
13552 CATCH_INTERNAL_ERROR("No result capture instance");
13555 void seedRng(IConfig const& config) {
13556 if (config.rngSeed() != 0) {
13557 std::srand(config.rngSeed());
13558 rng().seed(config.rngSeed());
13562 unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); }
13564 } // namespace Catch
13565 // end catch_run_context.cpp
13566 // start catch_section.cpp
13570 Section::Section(SectionInfo const& info) :
13571 m_info(info), m_sectionIncluded(getResultCapture().sectionStarted(m_info, m_assertions)) {
13575 Section::~Section() {
13576 if (m_sectionIncluded) {
13577 SectionEndInfo endInfo{m_info, m_assertions, m_timer.getElapsedSeconds()};
13578 if (uncaught_exceptions())
13579 getResultCapture().sectionEndedEarly(endInfo);
13581 getResultCapture().sectionEnded(endInfo);
13585 // This indicates whether the section should be executed or not
13586 Section::operator bool() const { return m_sectionIncluded; }
13588 } // end namespace Catch
13589 // end catch_section.cpp
13590 // start catch_section_info.cpp
13594 SectionInfo::SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name) :
13595 name(_name), lineInfo(_lineInfo) {}
13597 } // end namespace Catch
13598 // end catch_section_info.cpp
13599 // start catch_session.cpp
13601 // start catch_session.h
13607 class Session : NonCopyable {
13610 ~Session() override;
13612 void showHelp() const;
13613 void libIdentify();
13615 int applyCommandLine(int argc, char const* const* argv);
13616 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13617 int applyCommandLine(int argc, wchar_t const* const* argv);
13620 void useConfigData(ConfigData const& configData);
13622 template <typename CharT> int run(int argc, CharT const* const argv[]) {
13623 if (m_startupExceptions)
13625 int returnCode = applyCommandLine(argc, argv);
13626 if (returnCode == 0)
13627 returnCode = run();
13633 clara::Parser const& cli() const;
13634 void cli(clara::Parser const& newParser);
13635 ConfigData& configData();
13641 clara::Parser m_cli;
13642 ConfigData m_configData;
13643 std::shared_ptr<Config> m_config;
13644 bool m_startupExceptions = false;
13647 } // end namespace Catch
13649 // end catch_session.h
13650 // start catch_version.h
13656 // Versioning information
13658 Version(Version const&) = delete;
13659 Version& operator=(Version const&) = delete;
13660 Version(unsigned int _majorVersion,
13661 unsigned int _minorVersion,
13662 unsigned int _patchNumber,
13663 char const* const _branchName,
13664 unsigned int _buildNumber);
13666 unsigned int const majorVersion;
13667 unsigned int const minorVersion;
13668 unsigned int const patchNumber;
13670 // buildNumber is only used if branchName is not null
13671 char const* const branchName;
13672 unsigned int const buildNumber;
13674 friend std::ostream& operator<<(std::ostream& os, Version const& version);
13677 Version const& libraryVersion();
13678 } // namespace Catch
13680 // end catch_version.h
13684 #include <iterator>
13689 const int MaxExitCode = 255;
13691 IStreamingReporterPtr createReporter(std::string const& reporterName,
13692 IConfigPtr const& config) {
13694 Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13695 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13700 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13701 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13702 return createReporter(config->getReporterName(), config);
13705 // On older platforms, returning std::unique_ptr<ListeningReporter>
13706 // when the return type is std::unique_ptr<IStreamingReporter>
13707 // doesn't compile without a std::move call. However, this causes
13708 // a warning on newer platforms. Thus, we have to work around
13709 // it a bit and downcast the pointer manually.
13710 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13711 auto& multi = static_cast<ListeningReporter&>(*ret);
13712 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13713 for (auto const& listener : listeners) {
13714 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13716 multi.addReporter(createReporter(config->getReporterName(), config));
13722 explicit TestGroup(std::shared_ptr<Config> const& config) :
13723 m_config{config}, m_context{config, makeReporter(config)} {
13724 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13725 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13726 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13728 if (m_matches.empty() && invalidArgs.empty()) {
13729 for (auto const& test : allTestCases)
13730 if (!test.isHidden())
13731 m_tests.emplace(&test);
13733 for (auto const& match : m_matches)
13734 m_tests.insert(match.tests.begin(), match.tests.end());
13739 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13741 m_context.testGroupStarting(m_config->name(), 1, 1);
13742 for (auto const& testCase : m_tests) {
13743 if (!m_context.aborting())
13744 totals += m_context.runTest(*testCase);
13746 m_context.reporter().skipTest(*testCase);
13749 for (auto const& match : m_matches) {
13750 if (match.tests.empty()) {
13751 m_context.reporter().noMatchingTestCases(match.name);
13756 if (!invalidArgs.empty()) {
13757 for (auto const& invalidArg : invalidArgs)
13758 m_context.reporter().reportInvalidArguments(invalidArg);
13761 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13766 using Tests = std::set<TestCase const*>;
13768 std::shared_ptr<Config> m_config;
13769 RunContext m_context;
13771 TestSpec::Matches m_matches;
13774 void applyFilenamesAsTags(Catch::IConfig const& config) {
13775 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13776 for (auto& testCase : tests) {
13777 auto tags = testCase.tags;
13779 std::string filename = testCase.lineInfo.file;
13780 auto lastSlash = filename.find_last_of("\\/");
13781 if (lastSlash != std::string::npos) {
13782 filename.erase(0, lastSlash);
13786 auto lastDot = filename.find_last_of('.');
13787 if (lastDot != std::string::npos) {
13788 filename.erase(lastDot);
13791 tags.push_back(std::move(filename));
13792 setTags(testCase, tags);
13798 Session::Session() {
13799 static bool alreadyInstantiated = false;
13800 if (alreadyInstantiated) {
13802 CATCH_INTERNAL_ERROR("Only one instance of Catch::Session can ever be used");
13804 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13807 // There cannot be exceptions at startup in no-exception mode.
13808 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13809 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13810 if (!exceptions.empty()) {
13812 getCurrentMutableContext().setConfig(m_config);
13814 m_startupExceptions = true;
13815 Colour colourGuard(Colour::Red);
13816 Catch::cerr() << "Errors occurred during startup!" << '\n';
13817 // iterate over all exceptions and notify user
13818 for (const auto& ex_ptr : exceptions) {
13820 std::rethrow_exception(ex_ptr);
13821 } catch (std::exception const& ex) {
13822 Catch::cerr() << Column(ex.what()).indent(2) << '\n';
13828 alreadyInstantiated = true;
13829 m_cli = makeCommandLineParser(m_configData);
13831 Session::~Session() { Catch::cleanUp(); }
13833 void Session::showHelp() const {
13834 Catch::cout() << "\nCatch v" << libraryVersion() << "\n"
13835 << m_cli << std::endl
13836 << "For more detailed usage please see the project docs\n"
13839 void Session::libIdentify() {
13840 Catch::cout() << std::left << std::setw(16) << "description: "
13841 << "A Catch2 test executable\n"
13842 << std::left << std::setw(16) << "category: "
13843 << "testframework\n"
13844 << std::left << std::setw(16) << "framework: "
13846 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13849 int Session::applyCommandLine(int argc, char const* const* argv) {
13850 if (m_startupExceptions)
13853 auto result = m_cli.parse(clara::Args(argc, argv));
13856 getCurrentMutableContext().setConfig(m_config);
13857 Catch::cerr() << Colour(Colour::Red) << "\nError(s) in input:\n"
13858 << Column(result.errorMessage()).indent(2) << "\n\n";
13859 Catch::cerr() << "Run with -? for usage\n" << std::endl;
13860 return MaxExitCode;
13863 if (m_configData.showHelp)
13865 if (m_configData.libIdentify)
13871 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13872 int Session::applyCommandLine(int argc, wchar_t const* const* argv) {
13874 char** utf8Argv = new char*[argc];
13876 for (int i = 0; i < argc; ++i) {
13878 WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr);
13880 utf8Argv[i] = new char[bufSize];
13882 WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr);
13885 int returnCode = applyCommandLine(argc, utf8Argv);
13887 for (int i = 0; i < argc; ++i)
13888 delete[] utf8Argv[i];
13896 void Session::useConfigData(ConfigData const& configData) {
13897 m_configData = configData;
13901 int Session::run() {
13902 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeStart) != 0) {
13903 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13904 static_cast<void>(std::getchar());
13906 int exitCode = runInternal();
13907 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeExit) != 0) {
13908 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode
13910 static_cast<void>(std::getchar());
13915 clara::Parser const& Session::cli() const { return m_cli; }
13916 void Session::cli(clara::Parser const& newParser) { m_cli = newParser; }
13917 ConfigData& Session::configData() { return m_configData; }
13918 Config& Session::config() {
13920 m_config = std::make_shared<Config>(m_configData);
13924 int Session::runInternal() {
13925 if (m_startupExceptions)
13928 if (m_configData.showHelp || m_configData.libIdentify) {
13933 config(); // Force config to be constructed
13935 seedRng(*m_config);
13937 if (m_configData.filenamesAsTags)
13938 applyFilenamesAsTags(*m_config);
13940 // Handle list request
13941 if (Option<std::size_t> listed = list(m_config))
13942 return static_cast<int>(*listed);
13944 TestGroup tests{m_config};
13945 auto const totals = tests.execute();
13947 if (m_config->warnAboutNoTests() && totals.error == -1)
13950 // Note that on unices only the lower 8 bits are usually used,
13951 // clamping the return value to 255 prevents false negative when
13952 // some multiple of 256 tests has failed
13953 return (std::min)(MaxExitCode,
13954 (std::max)(totals.error, static_cast<int>(totals.assertions.failed)));
13956 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13957 catch (std::exception& ex) {
13958 Catch::cerr() << ex.what() << std::endl;
13959 return MaxExitCode;
13964 } // end namespace Catch
13965 // end catch_session.cpp
13966 // start catch_singletons.cpp
13973 static auto getSingletons() -> std::vector<ISingleton*>*& {
13974 static std::vector<ISingleton*>* g_singletons = nullptr;
13976 g_singletons = new std::vector<ISingleton*>();
13977 return g_singletons;
13981 ISingleton::~ISingleton() {}
13983 void addSingleton(ISingleton* singleton) { getSingletons()->push_back(singleton); }
13984 void cleanupSingletons() {
13985 auto& singletons = getSingletons();
13986 for (auto singleton : *singletons)
13989 singletons = nullptr;
13992 } // namespace Catch
13993 // end catch_singletons.cpp
13994 // start catch_startup_exception_registry.cpp
13996 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13998 void StartupExceptionRegistry::add(std::exception_ptr const& exception) noexcept {
13999 CATCH_TRY { m_exceptions.push_back(exception); }
14001 // If we run out of memory during start-up there's really not a lot
14002 // more we can do about it
14007 std::vector<std::exception_ptr> const&
14008 StartupExceptionRegistry::getExceptions() const noexcept {
14009 return m_exceptions;
14012 } // end namespace Catch
14014 // end catch_startup_exception_registry.cpp
14015 // start catch_stream.cpp
14018 #include <iostream>
14026 Catch::IStream::~IStream() = default;
14030 template <typename WriterF, std::size_t bufferSize = 256>
14031 class StreamBufImpl : public std::streambuf {
14032 char data[bufferSize];
14036 StreamBufImpl() { setp(data, data + sizeof(data)); }
14038 ~StreamBufImpl() noexcept { StreamBufImpl::sync(); }
14041 int overflow(int c) override {
14045 if (pbase() == epptr())
14046 m_writer(std::string(1, static_cast<char>(c)));
14048 sputc(static_cast<char>(c));
14053 int sync() override {
14054 if (pbase() != pptr()) {
14055 m_writer(std::string(
14056 pbase(), static_cast<std::string::size_type>(pptr() - pbase())));
14057 setp(pbase(), epptr());
14063 ///////////////////////////////////////////////////////////////////////////
14065 struct OutputDebugWriter {
14067 void operator()(std::string const& str) { writeToDebugConsole(str); }
14070 ///////////////////////////////////////////////////////////////////////////
14072 class FileStream : public IStream {
14073 mutable std::ofstream m_ofs;
14076 FileStream(StringRef filename) {
14077 m_ofs.open(filename.c_str());
14078 CATCH_ENFORCE(!m_ofs.fail(), "Unable to open file: '" << filename << "'");
14080 ~FileStream() override = default;
14083 std::ostream& stream() const override { return m_ofs; }
14086 ///////////////////////////////////////////////////////////////////////////
14088 class CoutStream : public IStream {
14089 mutable std::ostream m_os;
14092 // Store the streambuf from cout up-front because
14093 // cout may get redirected when running tests
14094 CoutStream() : m_os(Catch::cout().rdbuf()) {}
14095 ~CoutStream() override = default;
14098 std::ostream& stream() const override { return m_os; }
14101 ///////////////////////////////////////////////////////////////////////////
14103 class DebugOutStream : public IStream {
14104 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
14105 mutable std::ostream m_os;
14109 m_streamBuf(new StreamBufImpl<OutputDebugWriter>()), m_os(m_streamBuf.get()) {}
14111 ~DebugOutStream() override = default;
14114 std::ostream& stream() const override { return m_os; }
14118 } // namespace Detail
14120 ///////////////////////////////////////////////////////////////////////////
14122 auto makeStream(StringRef const& filename) -> IStream const* {
14123 if (filename.empty())
14124 return new Detail::CoutStream();
14125 else if (filename[0] == '%') {
14126 if (filename == "%debug")
14127 return new Detail::DebugOutStream();
14129 CATCH_ERROR("Unrecognised stream: '" << filename << "'");
14131 return new Detail::FileStream(filename);
14134 // This class encapsulates the idea of a pool of ostringstreams that can be
14136 struct StringStreams {
14137 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
14138 std::vector<std::size_t> m_unused;
14139 std::ostringstream m_referenceStream; // Used for copy state/ flags from
14141 auto add() -> std::size_t {
14142 if (m_unused.empty()) {
14143 m_streams.push_back(std::unique_ptr<std::ostringstream>(new std::ostringstream));
14144 return m_streams.size() - 1;
14146 auto index = m_unused.back();
14147 m_unused.pop_back();
14152 void release(std::size_t index) {
14153 m_streams[index]->copyfmt(m_referenceStream); // Restore initial flags and other state
14154 m_unused.push_back(index);
14158 ReusableStringStream::ReusableStringStream() :
14159 m_index(Singleton<StringStreams>::getMutable().add()),
14160 m_oss(Singleton<StringStreams>::getMutable().m_streams[m_index].get()) {}
14162 ReusableStringStream::~ReusableStringStream() {
14163 static_cast<std::ostringstream*>(m_oss)->str("");
14165 Singleton<StringStreams>::getMutable().release(m_index);
14168 auto ReusableStringStream::str() const -> std::string {
14169 return static_cast<std::ostringstream*>(m_oss)->str();
14172 ///////////////////////////////////////////////////////////////////////////
14174 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these
14176 std::ostream& cout() { return std::cout; }
14177 std::ostream& cerr() { return std::cerr; }
14178 std::ostream& clog() { return std::clog; }
14180 } // namespace Catch
14181 // end catch_stream.cpp
14182 // start catch_string_manip.cpp
14184 #include <algorithm>
14193 char toLowerCh(char c) {
14194 return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
14198 bool startsWith(std::string const& s, std::string const& prefix) {
14199 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
14201 bool startsWith(std::string const& s, char prefix) { return !s.empty() && s[0] == prefix; }
14202 bool endsWith(std::string const& s, std::string const& suffix) {
14203 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
14205 bool endsWith(std::string const& s, char suffix) {
14206 return !s.empty() && s[s.size() - 1] == suffix;
14208 bool contains(std::string const& s, std::string const& infix) {
14209 return s.find(infix) != std::string::npos;
14211 void toLowerInPlace(std::string& s) {
14212 std::transform(s.begin(), s.end(), s.begin(), toLowerCh);
14214 std::string toLower(std::string const& s) {
14215 std::string lc = s;
14216 toLowerInPlace(lc);
14219 std::string trim(std::string const& str) {
14220 static char const* whitespaceChars = "\n\r\t ";
14221 std::string::size_type start = str.find_first_not_of(whitespaceChars);
14222 std::string::size_type end = str.find_last_not_of(whitespaceChars);
14224 return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
14227 StringRef trim(StringRef ref) {
14228 const auto is_ws = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; };
14229 size_t real_begin = 0;
14230 while (real_begin < ref.size() && is_ws(ref[real_begin])) {
14233 size_t real_end = ref.size();
14234 while (real_end > real_begin && is_ws(ref[real_end - 1])) {
14238 return ref.substr(real_begin, real_end - real_begin);
14242 replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis) {
14243 bool replaced = false;
14244 std::size_t i = str.find(replaceThis);
14245 while (i != std::string::npos) {
14247 str = str.substr(0, i) + withThis + str.substr(i + replaceThis.size());
14248 if (i < str.size() - withThis.size())
14249 i = str.find(replaceThis, i + withThis.size());
14251 i = std::string::npos;
14256 std::vector<StringRef> splitStringRef(StringRef str, char delimiter) {
14257 std::vector<StringRef> subStrings;
14258 std::size_t start = 0;
14259 for (std::size_t pos = 0; pos < str.size(); ++pos) {
14260 if (str[pos] == delimiter) {
14261 if (pos - start > 1)
14262 subStrings.push_back(str.substr(start, pos - start));
14266 if (start < str.size())
14267 subStrings.push_back(str.substr(start, str.size() - start));
14271 pluralise::pluralise(std::size_t count, std::string const& label) :
14272 m_count(count), m_label(label) {}
14274 std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser) {
14275 os << pluraliser.m_count << ' ' << pluraliser.m_label;
14276 if (pluraliser.m_count != 1)
14281 } // namespace Catch
14282 // end catch_string_manip.cpp
14283 // start catch_stringref.cpp
14285 #include <algorithm>
14291 StringRef::StringRef(char const* rawChars) noexcept :
14292 StringRef(rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars))) {}
14294 auto StringRef::c_str() const -> char const* {
14295 CATCH_ENFORCE(isNullTerminated(),
14296 "Called StringRef::c_str() on a non-null-terminated instance");
14299 auto StringRef::data() const noexcept -> char const* { return m_start; }
14301 auto StringRef::substr(size_type start, size_type size) const noexcept -> StringRef {
14302 if (start < m_size) {
14303 return StringRef(m_start + start, (std::min)(m_size - start, size));
14305 return StringRef();
14308 auto StringRef::operator==(StringRef const& other) const noexcept -> bool {
14309 return m_size == other.m_size && (std::memcmp(m_start, other.m_start, m_size) == 0);
14312 auto operator<<(std::ostream& os, StringRef const& str) -> std::ostream& {
14313 return os.write(str.data(), str.size());
14316 auto operator+=(std::string& lhs, StringRef const& rhs) -> std::string& {
14317 lhs.append(rhs.data(), rhs.size());
14321 } // namespace Catch
14322 // end catch_stringref.cpp
14323 // start catch_tag_alias.cpp
14326 TagAlias::TagAlias(std::string const& _tag, SourceLineInfo _lineInfo) :
14327 tag(_tag), lineInfo(_lineInfo) {}
14328 } // namespace Catch
14329 // end catch_tag_alias.cpp
14330 // start catch_tag_alias_autoregistrar.cpp
14334 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias,
14336 SourceLineInfo const& lineInfo) {
14337 CATCH_TRY { getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); }
14339 // Do not throw when constructing global objects, instead register
14340 // the exception to be processed later
14341 getMutableRegistryHub().registerStartupException();
14345 } // namespace Catch
14346 // end catch_tag_alias_autoregistrar.cpp
14347 // start catch_tag_alias_registry.cpp
14353 TagAliasRegistry::~TagAliasRegistry() {}
14355 TagAlias const* TagAliasRegistry::find(std::string const& alias) const {
14356 auto it = m_registry.find(alias);
14357 if (it != m_registry.end())
14358 return &(it->second);
14363 std::string TagAliasRegistry::expandAliases(std::string const& unexpandedTestSpec) const {
14364 std::string expandedTestSpec = unexpandedTestSpec;
14365 for (auto const& registryKvp : m_registry) {
14366 std::size_t pos = expandedTestSpec.find(registryKvp.first);
14367 if (pos != std::string::npos) {
14368 expandedTestSpec = expandedTestSpec.substr(0, pos) + registryKvp.second.tag +
14369 expandedTestSpec.substr(pos + registryKvp.first.size());
14372 return expandedTestSpec;
14375 void TagAliasRegistry::add(std::string const& alias,
14376 std::string const& tag,
14377 SourceLineInfo const& lineInfo) {
14378 CATCH_ENFORCE(startsWith(alias, "[@") && endsWith(alias, ']'),
14379 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n"
14382 CATCH_ENFORCE(m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14383 "error: tag alias, '" << alias << "' already registered.\n"
14384 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
14385 << "\tRedefined at: " << lineInfo);
14388 ITagAliasRegistry::~ITagAliasRegistry() {}
14390 ITagAliasRegistry const& ITagAliasRegistry::get() {
14391 return getRegistryHub().getTagAliasRegistry();
14394 } // end namespace Catch
14395 // end catch_tag_alias_registry.cpp
14396 // start catch_test_case_info.cpp
14399 #include <exception>
14400 #include <algorithm>
14406 TestCaseInfo::SpecialProperties parseSpecialTag(std::string const& tag) {
14407 if (startsWith(tag, '.') || tag == "!hide")
14408 return TestCaseInfo::IsHidden;
14409 else if (tag == "!throws")
14410 return TestCaseInfo::Throws;
14411 else if (tag == "!shouldfail")
14412 return TestCaseInfo::ShouldFail;
14413 else if (tag == "!mayfail")
14414 return TestCaseInfo::MayFail;
14415 else if (tag == "!nonportable")
14416 return TestCaseInfo::NonPortable;
14417 else if (tag == "!benchmark")
14418 return static_cast<TestCaseInfo::SpecialProperties>(TestCaseInfo::Benchmark |
14419 TestCaseInfo::IsHidden);
14421 return TestCaseInfo::None;
14423 bool isReservedTag(std::string const& tag) {
14424 return parseSpecialTag(tag) == TestCaseInfo::None && tag.size() > 0 &&
14425 !std::isalnum(static_cast<unsigned char>(tag[0]));
14427 void enforceNotReservedTag(std::string const& tag, SourceLineInfo const& _lineInfo) {
14428 CATCH_ENFORCE(!isReservedTag(tag),
14429 "Tag name: [" << tag << "] is not allowed.\n"
14430 << "Tag names starting with non alphanumeric "
14431 "characters are reserved\n"
14436 TestCase makeTestCase(ITestInvoker* _testCase,
14437 std::string const& _className,
14438 NameAndTags const& nameAndTags,
14439 SourceLineInfo const& _lineInfo) {
14440 bool isHidden = false;
14443 std::vector<std::string> tags;
14444 std::string desc, tag;
14445 bool inTag = false;
14446 for (char c : nameAndTags.tags) {
14454 TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag);
14455 if ((prop & TestCaseInfo::IsHidden) != 0)
14457 else if (prop == TestCaseInfo::None)
14458 enforceNotReservedTag(tag, _lineInfo);
14460 // Merged hide tags like `[.approvals]` should be added as
14461 // `[.][approvals]`. The `[.]` is added at later point, so
14462 // we only strip the prefix
14463 if (startsWith(tag, '.') && tag.size() > 1) {
14466 tags.push_back(tag);
14474 // Add all "hidden" tags to make them behave identically
14475 tags.insert(tags.end(), {".", "!hide"});
14479 static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo);
14480 return TestCase(_testCase, std::move(info));
14483 void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags) {
14484 std::sort(begin(tags), end(tags));
14485 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14486 testCaseInfo.lcaseTags.clear();
14488 for (auto const& tag : tags) {
14489 std::string lcaseTag = toLower(tag);
14490 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>(
14491 testCaseInfo.properties | parseSpecialTag(lcaseTag));
14492 testCaseInfo.lcaseTags.push_back(lcaseTag);
14494 testCaseInfo.tags = std::move(tags);
14497 TestCaseInfo::TestCaseInfo(std::string const& _name,
14498 std::string const& _className,
14499 std::string const& _description,
14500 std::vector<std::string> const& _tags,
14501 SourceLineInfo const& _lineInfo) :
14503 className(_className),
14504 description(_description),
14505 lineInfo(_lineInfo),
14507 setTags(*this, _tags);
14510 bool TestCaseInfo::isHidden() const { return (properties & IsHidden) != 0; }
14511 bool TestCaseInfo::throws() const { return (properties & Throws) != 0; }
14512 bool TestCaseInfo::okToFail() const { return (properties & (ShouldFail | MayFail)) != 0; }
14513 bool TestCaseInfo::expectedToFail() const { return (properties & (ShouldFail)) != 0; }
14515 std::string TestCaseInfo::tagsAsString() const {
14517 // '[' and ']' per tag
14518 std::size_t full_size = 2 * tags.size();
14519 for (const auto& tag : tags) {
14520 full_size += tag.size();
14522 ret.reserve(full_size);
14523 for (const auto& tag : tags) {
14524 ret.push_back('[');
14526 ret.push_back(']');
14532 TestCase::TestCase(ITestInvoker* testCase, TestCaseInfo&& info) :
14533 TestCaseInfo(std::move(info)), test(testCase) {}
14535 TestCase TestCase::withName(std::string const& _newName) const {
14536 TestCase other(*this);
14537 other.name = _newName;
14541 void TestCase::invoke() const { test->invoke(); }
14543 bool TestCase::operator==(TestCase const& other) const {
14544 return test.get() == other.test.get() && name == other.name && className == other.className;
14547 bool TestCase::operator<(TestCase const& other) const { return name < other.name; }
14549 TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; }
14551 } // end namespace Catch
14552 // end catch_test_case_info.cpp
14553 // start catch_test_case_registry_impl.cpp
14555 #include <algorithm>
14561 struct TestHasher {
14562 using hash_t = uint64_t;
14564 explicit TestHasher(hash_t hashSuffix) : m_hashSuffix{hashSuffix} {}
14566 uint32_t operator()(TestCase const& t) const {
14567 // FNV-1a hash with multiplication fold.
14568 const hash_t prime = 1099511628211u;
14569 hash_t hash = 14695981039346656037u;
14570 for (const char c : t.name) {
14574 hash ^= m_hashSuffix;
14576 const uint32_t low{static_cast<uint32_t>(hash)};
14577 const uint32_t high{static_cast<uint32_t>(hash >> 32)};
14582 hash_t m_hashSuffix;
14584 } // end unnamed namespace
14586 std::vector<TestCase> sortTests(IConfig const& config,
14587 std::vector<TestCase> const& unsortedTestCases) {
14588 switch (config.runOrder()) {
14589 case RunTests::InDeclarationOrder:
14590 // already in declaration order
14593 case RunTests::InLexicographicalOrder: {
14594 std::vector<TestCase> sorted = unsortedTestCases;
14595 std::sort(sorted.begin(), sorted.end());
14599 case RunTests::InRandomOrder: {
14601 TestHasher h{config.rngSeed()};
14603 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14604 std::vector<hashedTest> indexed_tests;
14605 indexed_tests.reserve(unsortedTestCases.size());
14607 for (auto const& testCase : unsortedTestCases) {
14608 indexed_tests.emplace_back(h(testCase), &testCase);
14611 std::sort(indexed_tests.begin(),
14612 indexed_tests.end(),
14613 [](hashedTest const& lhs, hashedTest const& rhs) {
14614 if (lhs.first == rhs.first) {
14615 return lhs.second->name < rhs.second->name;
14617 return lhs.first < rhs.first;
14620 std::vector<TestCase> sorted;
14621 sorted.reserve(indexed_tests.size());
14623 for (auto const& hashed : indexed_tests) {
14624 sorted.emplace_back(*hashed.second);
14630 return unsortedTestCases;
14633 bool isThrowSafe(TestCase const& testCase, IConfig const& config) {
14634 return !testCase.throws() || config.allowThrows();
14637 bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config) {
14638 return testSpec.matches(testCase) && isThrowSafe(testCase, config);
14641 void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions) {
14642 std::set<TestCase> seenFunctions;
14643 for (auto const& function : functions) {
14644 auto prev = seenFunctions.insert(function);
14645 CATCH_ENFORCE(prev.second,
14646 "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14647 << "\tFirst seen at "
14648 << prev.first->getTestCaseInfo().lineInfo << "\n"
14649 << "\tRedefined at "
14650 << function.getTestCaseInfo().lineInfo);
14654 std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases,
14655 TestSpec const& testSpec,
14656 IConfig const& config) {
14657 std::vector<TestCase> filtered;
14658 filtered.reserve(testCases.size());
14659 for (auto const& testCase : testCases) {
14660 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14661 (testSpec.hasFilters() && matchTest(testCase, testSpec, config)))
14663 filtered.push_back(testCase);
14668 std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config) {
14669 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config);
14672 void TestRegistry::registerTest(TestCase const& testCase) {
14673 std::string name = testCase.getTestCaseInfo().name;
14674 if (name.empty()) {
14675 ReusableStringStream rss;
14676 rss << "Anonymous test case " << ++m_unnamedCount;
14677 return registerTest(testCase.withName(rss.str()));
14679 m_functions.push_back(testCase);
14682 std::vector<TestCase> const& TestRegistry::getAllTests() const { return m_functions; }
14683 std::vector<TestCase> const& TestRegistry::getAllTestsSorted(IConfig const& config) const {
14684 if (m_sortedFunctions.empty())
14685 enforceNoDuplicateTestCases(m_functions);
14687 if (m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty()) {
14688 m_sortedFunctions = sortTests(config, m_functions);
14689 m_currentSortOrder = config.runOrder();
14691 return m_sortedFunctions;
14694 ///////////////////////////////////////////////////////////////////////////
14695 TestInvokerAsFunction::TestInvokerAsFunction(void (*testAsFunction)()) noexcept :
14696 m_testAsFunction(testAsFunction) {}
14698 void TestInvokerAsFunction::invoke() const { m_testAsFunction(); }
14700 std::string extractClassName(StringRef const& classOrQualifiedMethodName) {
14701 std::string className(classOrQualifiedMethodName);
14702 if (startsWith(className, '&')) {
14703 std::size_t lastColons = className.rfind("::");
14704 std::size_t penultimateColons = className.rfind("::", lastColons - 1);
14705 if (penultimateColons == std::string::npos)
14706 penultimateColons = 1;
14707 className = className.substr(penultimateColons, lastColons - penultimateColons);
14712 } // end namespace Catch
14713 // end catch_test_case_registry_impl.cpp
14714 // start catch_test_case_tracker.cpp
14716 #include <algorithm>
14718 #include <stdexcept>
14722 #if defined(__clang__)
14723 #pragma clang diagnostic push
14724 #pragma clang diagnostic ignored "-Wexit-time-destructors"
14728 namespace TestCaseTracking {
14730 NameAndLocation::NameAndLocation(std::string const& _name,
14731 SourceLineInfo const& _location) :
14732 name(_name), location(_location) {}
14734 ITracker::~ITracker() = default;
14736 ITracker& TrackerContext::startRun() {
14737 m_rootTracker = std::make_shared<SectionTracker>(
14738 NameAndLocation("{root}", CATCH_INTERNAL_LINEINFO), *this, nullptr);
14739 m_currentTracker = nullptr;
14740 m_runState = Executing;
14741 return *m_rootTracker;
14744 void TrackerContext::endRun() {
14745 m_rootTracker.reset();
14746 m_currentTracker = nullptr;
14747 m_runState = NotStarted;
14750 void TrackerContext::startCycle() {
14751 m_currentTracker = m_rootTracker.get();
14752 m_runState = Executing;
14754 void TrackerContext::completeCycle() { m_runState = CompletedCycle; }
14756 bool TrackerContext::completedCycle() const { return m_runState == CompletedCycle; }
14757 ITracker& TrackerContext::currentTracker() { return *m_currentTracker; }
14758 void TrackerContext::setCurrentTracker(ITracker* tracker) { m_currentTracker = tracker; }
14760 TrackerBase::TrackerBase(NameAndLocation const& nameAndLocation,
14761 TrackerContext& ctx,
14762 ITracker* parent) :
14763 ITracker(nameAndLocation), m_ctx(ctx), m_parent(parent) {}
14765 bool TrackerBase::isComplete() const {
14766 return m_runState == CompletedSuccessfully || m_runState == Failed;
14768 bool TrackerBase::isSuccessfullyCompleted() const {
14769 return m_runState == CompletedSuccessfully;
14771 bool TrackerBase::isOpen() const { return m_runState != NotStarted && !isComplete(); }
14772 bool TrackerBase::hasChildren() const { return !m_children.empty(); }
14774 void TrackerBase::addChild(ITrackerPtr const& child) { m_children.push_back(child); }
14776 ITrackerPtr TrackerBase::findChild(NameAndLocation const& nameAndLocation) {
14777 auto it = std::find_if(
14778 m_children.begin(),
14780 [&nameAndLocation](ITrackerPtr const& tracker) {
14781 return tracker->nameAndLocation().location == nameAndLocation.location &&
14782 tracker->nameAndLocation().name == nameAndLocation.name;
14784 return (it != m_children.end()) ? *it : nullptr;
14786 ITracker& TrackerBase::parent() {
14787 assert(m_parent); // Should always be non-null except for root
14791 void TrackerBase::openChild() {
14792 if (m_runState != ExecutingChildren) {
14793 m_runState = ExecutingChildren;
14795 m_parent->openChild();
14799 bool TrackerBase::isSectionTracker() const { return false; }
14800 bool TrackerBase::isGeneratorTracker() const { return false; }
14802 void TrackerBase::open() {
14803 m_runState = Executing;
14806 m_parent->openChild();
14809 void TrackerBase::close() {
14811 // Close any still open children (e.g. generators)
14812 while (&m_ctx.currentTracker() != this)
14813 m_ctx.currentTracker().close();
14815 switch (m_runState) {
14816 case NeedsAnotherRun:
14820 m_runState = CompletedSuccessfully;
14822 case ExecutingChildren:
14823 if (std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t) {
14824 return t->isComplete();
14826 m_runState = CompletedSuccessfully;
14830 case CompletedSuccessfully:
14832 CATCH_INTERNAL_ERROR("Illogical state: " << m_runState);
14835 CATCH_INTERNAL_ERROR("Unknown state: " << m_runState);
14838 m_ctx.completeCycle();
14840 void TrackerBase::fail() {
14841 m_runState = Failed;
14843 m_parent->markAsNeedingAnotherRun();
14845 m_ctx.completeCycle();
14847 void TrackerBase::markAsNeedingAnotherRun() { m_runState = NeedsAnotherRun; }
14849 void TrackerBase::moveToParent() {
14851 m_ctx.setCurrentTracker(m_parent);
14853 void TrackerBase::moveToThis() { m_ctx.setCurrentTracker(this); }
14855 SectionTracker::SectionTracker(NameAndLocation const& nameAndLocation,
14856 TrackerContext& ctx,
14857 ITracker* parent) :
14858 TrackerBase(nameAndLocation, ctx, parent), m_trimmed_name(trim(nameAndLocation.name)) {
14860 while (!parent->isSectionTracker())
14861 parent = &parent->parent();
14863 SectionTracker& parentSection = static_cast<SectionTracker&>(*parent);
14864 addNextFilters(parentSection.m_filters);
14868 bool SectionTracker::isComplete() const {
14869 bool complete = true;
14871 if (m_filters.empty() || m_filters[0] == "" ||
14872 std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end())
14874 complete = TrackerBase::isComplete();
14879 bool SectionTracker::isSectionTracker() const { return true; }
14881 SectionTracker& SectionTracker::acquire(TrackerContext& ctx,
14882 NameAndLocation const& nameAndLocation) {
14883 std::shared_ptr<SectionTracker> section;
14885 ITracker& currentTracker = ctx.currentTracker();
14886 if (ITrackerPtr childTracker = currentTracker.findChild(nameAndLocation)) {
14887 assert(childTracker);
14888 assert(childTracker->isSectionTracker());
14889 section = std::static_pointer_cast<SectionTracker>(childTracker);
14891 section = std::make_shared<SectionTracker>(nameAndLocation, ctx, ¤tTracker);
14892 currentTracker.addChild(section);
14894 if (!ctx.completedCycle())
14895 section->tryOpen();
14899 void SectionTracker::tryOpen() {
14904 void SectionTracker::addInitialFilters(std::vector<std::string> const& filters) {
14905 if (!filters.empty()) {
14906 m_filters.reserve(m_filters.size() + filters.size() + 2);
14907 m_filters.emplace_back(""); // Root - should never be consulted
14908 m_filters.emplace_back(""); // Test Case - not a section filter
14909 m_filters.insert(m_filters.end(), filters.begin(), filters.end());
14912 void SectionTracker::addNextFilters(std::vector<std::string> const& filters) {
14913 if (filters.size() > 1)
14914 m_filters.insert(m_filters.end(), filters.begin() + 1, filters.end());
14917 std::vector<std::string> const& SectionTracker::getFilters() const { return m_filters; }
14919 std::string const& SectionTracker::trimmedName() const { return m_trimmed_name; }
14921 } // namespace TestCaseTracking
14923 using TestCaseTracking::ITracker;
14924 using TestCaseTracking::SectionTracker;
14925 using TestCaseTracking::TrackerContext;
14927 } // namespace Catch
14929 #if defined(__clang__)
14930 #pragma clang diagnostic pop
14932 // end catch_test_case_tracker.cpp
14933 // start catch_test_registry.cpp
14937 auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker* {
14938 return new (std::nothrow) TestInvokerAsFunction(testAsFunction);
14941 NameAndTags::NameAndTags(StringRef const& name_, StringRef const& tags_) noexcept :
14942 name(name_), tags(tags_) {}
14944 AutoReg::AutoReg(ITestInvoker* invoker,
14945 SourceLineInfo const& lineInfo,
14946 StringRef const& classOrMethod,
14947 NameAndTags const& nameAndTags) noexcept {
14949 getMutableRegistryHub().registerTest(
14950 makeTestCase(invoker, extractClassName(classOrMethod), nameAndTags, lineInfo));
14953 // Do not throw when constructing global objects, instead register
14954 // the exception to be processed later
14955 getMutableRegistryHub().registerStartupException();
14959 AutoReg::~AutoReg() = default;
14960 } // namespace Catch
14961 // end catch_test_registry.cpp
14962 // start catch_test_spec.cpp
14964 #include <algorithm>
14971 TestSpec::Pattern::Pattern(std::string const& name) : m_name(name) {}
14973 TestSpec::Pattern::~Pattern() = default;
14975 std::string const& TestSpec::Pattern::name() const { return m_name; }
14977 TestSpec::NamePattern::NamePattern(std::string const& name, std::string const& filterString) :
14978 Pattern(filterString), m_wildcardPattern(toLower(name), CaseSensitive::No) {}
14980 bool TestSpec::NamePattern::matches(TestCaseInfo const& testCase) const {
14981 return m_wildcardPattern.matches(testCase.name);
14984 TestSpec::TagPattern::TagPattern(std::string const& tag, std::string const& filterString) :
14985 Pattern(filterString), m_tag(toLower(tag)) {}
14987 bool TestSpec::TagPattern::matches(TestCaseInfo const& testCase) const {
14988 return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) !=
14989 end(testCase.lcaseTags);
14992 TestSpec::ExcludedPattern::ExcludedPattern(PatternPtr const& underlyingPattern) :
14993 Pattern(underlyingPattern->name()), m_underlyingPattern(underlyingPattern) {}
14995 bool TestSpec::ExcludedPattern::matches(TestCaseInfo const& testCase) const {
14996 return !m_underlyingPattern->matches(testCase);
14999 bool TestSpec::Filter::matches(TestCaseInfo const& testCase) const {
15000 return std::all_of(m_patterns.begin(), m_patterns.end(), [&](PatternPtr const& p) {
15001 return p->matches(testCase);
15005 std::string TestSpec::Filter::name() const {
15007 for (auto const& p : m_patterns)
15012 bool TestSpec::hasFilters() const { return !m_filters.empty(); }
15014 bool TestSpec::matches(TestCaseInfo const& testCase) const {
15015 return std::any_of(m_filters.begin(), m_filters.end(), [&](Filter const& f) {
15016 return f.matches(testCase);
15020 TestSpec::Matches TestSpec::matchesByFilter(std::vector<TestCase> const& testCases,
15021 IConfig const& config) const {
15022 Matches matches(m_filters.size());
15024 m_filters.begin(), m_filters.end(), matches.begin(), [&](Filter const& filter) {
15025 std::vector<TestCase const*> currentMatches;
15026 for (auto const& test : testCases)
15027 if (isThrowSafe(test, config) && filter.matches(test))
15028 currentMatches.emplace_back(&test);
15029 return FilterMatch{filter.name(), currentMatches};
15034 const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const { return (m_invalidArgs); }
15036 } // namespace Catch
15037 // end catch_test_spec.cpp
15038 // start catch_test_spec_parser.cpp
15042 TestSpecParser::TestSpecParser(ITagAliasRegistry const& tagAliases) :
15043 m_tagAliases(&tagAliases) {}
15045 TestSpecParser& TestSpecParser::parse(std::string const& arg) {
15047 m_exclusion = false;
15048 m_arg = m_tagAliases->expandAliases(arg);
15049 m_escapeChars.clear();
15050 m_substring.reserve(m_arg.size());
15051 m_patternName.reserve(m_arg.size());
15052 m_realPatternPos = 0;
15054 for (m_pos = 0; m_pos < m_arg.size(); ++m_pos)
15055 // if visitChar fails
15056 if (!visitChar(m_arg[m_pos])) {
15057 m_testSpec.m_invalidArgs.push_back(arg);
15063 TestSpec TestSpecParser::testSpec() {
15067 bool TestSpecParser::visitChar(char c) {
15068 if ((m_mode != EscapedName) && (c == '\\')) {
15070 addCharToPattern(c);
15072 } else if ((m_mode != EscapedName) && (c == ',')) {
15078 if (processNoneChar(c))
15082 processNameChar(c);
15086 addCharToPattern(c);
15091 if (processOtherChar(c))
15097 if (!isControlChar(c)) {
15098 m_patternName += c;
15099 m_realPatternPos++;
15103 // Two of the processing methods return true to signal the caller to return
15104 // without adding the given character to the current pattern strings
15105 bool TestSpecParser::processNoneChar(char c) {
15110 m_exclusion = true;
15116 startNewMode(QuotedName);
15119 startNewMode(Name);
15123 void TestSpecParser::processNameChar(char c) {
15125 if (m_substring == "exclude:")
15126 m_exclusion = true;
15132 bool TestSpecParser::processOtherChar(char c) {
15133 if (!isControlChar(c))
15139 void TestSpecParser::startNewMode(Mode mode) { m_mode = mode; }
15140 void TestSpecParser::endMode() {
15144 return addNamePattern();
15146 return addTagPattern();
15148 revertBackToLastMode();
15152 return startNewMode(None);
15155 void TestSpecParser::escape() {
15157 m_mode = EscapedName;
15158 m_escapeChars.push_back(m_realPatternPos);
15160 bool TestSpecParser::isControlChar(char c) const {
15173 return c == '[' || c == ']';
15177 void TestSpecParser::addFilter() {
15178 if (!m_currentFilter.m_patterns.empty()) {
15179 m_testSpec.m_filters.push_back(m_currentFilter);
15180 m_currentFilter = TestSpec::Filter();
15184 void TestSpecParser::saveLastMode() { lastMode = m_mode; }
15186 void TestSpecParser::revertBackToLastMode() { m_mode = lastMode; }
15188 bool TestSpecParser::separate() {
15189 if ((m_mode == QuotedName) || (m_mode == Tag)) {
15190 // invalid argument, signal failure to previous scope.
15192 m_pos = m_arg.size();
15193 m_substring.clear();
15194 m_patternName.clear();
15195 m_realPatternPos = 0;
15200 return true; // success
15203 std::string TestSpecParser::preprocessPattern() {
15204 std::string token = m_patternName;
15205 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
15206 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
15207 m_escapeChars.clear();
15208 if (startsWith(token, "exclude:")) {
15209 m_exclusion = true;
15210 token = token.substr(8);
15213 m_patternName.clear();
15214 m_realPatternPos = 0;
15219 void TestSpecParser::addNamePattern() {
15220 auto token = preprocessPattern();
15222 if (!token.empty()) {
15223 TestSpec::PatternPtr pattern =
15224 std::make_shared<TestSpec::NamePattern>(token, m_substring);
15226 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15227 m_currentFilter.m_patterns.push_back(pattern);
15229 m_substring.clear();
15230 m_exclusion = false;
15234 void TestSpecParser::addTagPattern() {
15235 auto token = preprocessPattern();
15237 if (!token.empty()) {
15238 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
15239 // we have to create a separate hide tag and shorten the real one
15240 if (token.size() > 1 && token[0] == '.') {
15241 token.erase(token.begin());
15242 TestSpec::PatternPtr pattern =
15243 std::make_shared<TestSpec::TagPattern>(".", m_substring);
15245 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15247 m_currentFilter.m_patterns.push_back(pattern);
15250 TestSpec::PatternPtr pattern =
15251 std::make_shared<TestSpec::TagPattern>(token, m_substring);
15254 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15256 m_currentFilter.m_patterns.push_back(pattern);
15258 m_substring.clear();
15259 m_exclusion = false;
15263 TestSpec parseTestSpec(std::string const& arg) {
15264 return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec();
15267 } // namespace Catch
15268 // end catch_test_spec_parser.cpp
15269 // start catch_timer.cpp
15273 static const uint64_t nanosecondsInSecond = 1000000000;
15277 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
15278 return std::chrono::duration_cast<std::chrono::nanoseconds>(
15279 std::chrono::high_resolution_clock::now().time_since_epoch())
15284 auto estimateClockResolution() -> uint64_t {
15286 static const uint64_t iterations = 1000000;
15288 auto startTime = getCurrentNanosecondsSinceEpoch();
15290 for (std::size_t i = 0; i < iterations; ++i) {
15293 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
15295 ticks = getCurrentNanosecondsSinceEpoch();
15296 } while (ticks == baseTicks);
15298 auto delta = ticks - baseTicks;
15301 // If we have been calibrating for over 3 seconds -- the clock
15302 // is terrible and we should move on.
15303 // TBD: How to signal that the measured resolution is probably
15305 if (ticks > startTime + 3 * nanosecondsInSecond) {
15306 return sum / (i + 1u);
15310 // We're just taking the mean, here. To do better we could take the
15311 // std. dev and exclude outliers
15312 // - and potentially do more iterations if there's a high variance.
15313 return sum / iterations;
15316 auto getEstimatedClockResolution() -> uint64_t {
15317 static auto s_resolution = estimateClockResolution();
15318 return s_resolution;
15321 void Timer::start() { m_nanoseconds = getCurrentNanosecondsSinceEpoch(); }
15322 auto Timer::getElapsedNanoseconds() const -> uint64_t {
15323 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
15325 auto Timer::getElapsedMicroseconds() const -> uint64_t {
15326 return getElapsedNanoseconds() / 1000;
15328 auto Timer::getElapsedMilliseconds() const -> unsigned int {
15329 return static_cast<unsigned int>(getElapsedMicroseconds() / 1000);
15331 auto Timer::getElapsedSeconds() const -> double { return getElapsedMicroseconds() / 1000000.0; }
15333 } // namespace Catch
15334 // end catch_timer.cpp
15335 // start catch_tostring.cpp
15337 #if defined(__clang__)
15338 #pragma clang diagnostic push
15339 #pragma clang diagnostic ignored "-Wexit-time-destructors"
15340 #pragma clang diagnostic ignored "-Wglobal-constructors"
15343 // Enable specific decls locally
15344 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15345 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15355 const std::string unprintableString = "{?}";
15358 const int hexThreshold = 255;
15360 struct Endianness {
15361 enum Arch { Big, Little };
15363 static Arch which() {
15365 // If the lowest byte we read is non-zero, we can assume
15366 // that little endian format is used.
15367 auto value = *reinterpret_cast<char*>(&one);
15368 return value ? Little : Big;
15373 std::string rawMemoryToString(const void* object, std::size_t size) {
15374 // Reverse order for little endian architectures
15375 int i = 0, end = static_cast<int>(size), inc = 1;
15376 if (Endianness::which() == Endianness::Little) {
15381 unsigned char const* bytes = static_cast<unsigned char const*>(object);
15382 ReusableStringStream rss;
15383 rss << "0x" << std::setfill('0') << std::hex;
15384 for (; i != end; i += inc)
15385 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15388 } // namespace Detail
15390 template <typename T> std::string fpToString(T value, int precision) {
15391 if (Catch::isnan(value)) {
15395 ReusableStringStream rss;
15396 rss << std::setprecision(precision) << std::fixed << value;
15397 std::string d = rss.str();
15398 std::size_t i = d.find_last_not_of('0');
15399 if (i != std::string::npos && i != d.size() - 1) {
15402 d = d.substr(0, i + 1);
15407 //// ======================================================= ////
15409 // Out-of-line defs for full specialization of StringMaker
15411 //// ======================================================= ////
15413 std::string StringMaker<std::string>::convert(const std::string& str) {
15414 if (!getCurrentContext().getConfig()->showInvisibles()) {
15415 return '"' + str + '"';
15418 std::string s("\"");
15419 for (char c : str) {
15436 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15437 std::string StringMaker<std::string_view>::convert(std::string_view str) {
15438 return ::Catch::Detail::stringify(std::string{str});
15442 std::string StringMaker<char const*>::convert(char const* str) {
15444 return ::Catch::Detail::stringify(std::string{str});
15446 return {"{null string}"};
15449 std::string StringMaker<char*>::convert(char* str) {
15451 return ::Catch::Detail::stringify(std::string{str});
15453 return {"{null string}"};
15457 #ifdef CATCH_CONFIG_WCHAR
15458 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15460 s.reserve(wstr.size());
15461 for (auto c : wstr) {
15462 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15464 return ::Catch::Detail::stringify(s);
15467 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15468 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15469 return StringMaker<std::wstring>::convert(std::wstring(str));
15473 std::string StringMaker<wchar_t const*>::convert(wchar_t const* str) {
15475 return ::Catch::Detail::stringify(std::wstring{str});
15477 return {"{null string}"};
15480 std::string StringMaker<wchar_t*>::convert(wchar_t* str) {
15482 return ::Catch::Detail::stringify(std::wstring{str});
15484 return {"{null string}"};
15489 #if defined(CATCH_CONFIG_CPP17_BYTE)
15491 std::string StringMaker<std::byte>::convert(std::byte value) {
15492 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15494 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15496 std::string StringMaker<int>::convert(int value) {
15497 return ::Catch::Detail::stringify(static_cast<long long>(value));
15499 std::string StringMaker<long>::convert(long value) {
15500 return ::Catch::Detail::stringify(static_cast<long long>(value));
15502 std::string StringMaker<long long>::convert(long long value) {
15503 ReusableStringStream rss;
15505 if (value > Detail::hexThreshold) {
15506 rss << " (0x" << std::hex << value << ')';
15511 std::string StringMaker<unsigned int>::convert(unsigned int value) {
15512 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15514 std::string StringMaker<unsigned long>::convert(unsigned long value) {
15515 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15517 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15518 ReusableStringStream rss;
15520 if (value > Detail::hexThreshold) {
15521 rss << " (0x" << std::hex << value << ')';
15526 std::string StringMaker<bool>::convert(bool b) { return b ? "true" : "false"; }
15528 std::string StringMaker<signed char>::convert(signed char value) {
15529 if (value == '\r') {
15531 } else if (value == '\f') {
15533 } else if (value == '\n') {
15535 } else if (value == '\t') {
15537 } else if ('\0' <= value && value < ' ') {
15538 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15540 char chstr[] = "' '";
15545 std::string StringMaker<char>::convert(char c) {
15546 return ::Catch::Detail::stringify(static_cast<signed char>(c));
15548 std::string StringMaker<unsigned char>::convert(unsigned char c) {
15549 return ::Catch::Detail::stringify(static_cast<char>(c));
15552 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) { return "nullptr"; }
15554 int StringMaker<float>::precision = 5;
15556 std::string StringMaker<float>::convert(float value) {
15557 return fpToString(value, precision) + 'f';
15560 int StringMaker<double>::precision = 10;
15562 std::string StringMaker<double>::convert(double value) { return fpToString(value, precision); }
15564 std::string ratio_string<std::atto>::symbol() { return "a"; }
15565 std::string ratio_string<std::femto>::symbol() { return "f"; }
15566 std::string ratio_string<std::pico>::symbol() { return "p"; }
15567 std::string ratio_string<std::nano>::symbol() { return "n"; }
15568 std::string ratio_string<std::micro>::symbol() { return "u"; }
15569 std::string ratio_string<std::milli>::symbol() { return "m"; }
15571 } // end namespace Catch
15573 #if defined(__clang__)
15574 #pragma clang diagnostic pop
15577 // end catch_tostring.cpp
15578 // start catch_totals.cpp
15582 Counts Counts::operator-(Counts const& other) const {
15584 diff.passed = passed - other.passed;
15585 diff.failed = failed - other.failed;
15586 diff.failedButOk = failedButOk - other.failedButOk;
15590 Counts& Counts::operator+=(Counts const& other) {
15591 passed += other.passed;
15592 failed += other.failed;
15593 failedButOk += other.failedButOk;
15597 std::size_t Counts::total() const { return passed + failed + failedButOk; }
15598 bool Counts::allPassed() const { return failed == 0 && failedButOk == 0; }
15599 bool Counts::allOk() const { return failed == 0; }
15601 Totals Totals::operator-(Totals const& other) const {
15603 diff.assertions = assertions - other.assertions;
15604 diff.testCases = testCases - other.testCases;
15608 Totals& Totals::operator+=(Totals const& other) {
15609 assertions += other.assertions;
15610 testCases += other.testCases;
15614 Totals Totals::delta(Totals const& prevTotals) const {
15615 Totals diff = *this - prevTotals;
15616 if (diff.assertions.failed > 0)
15617 ++diff.testCases.failed;
15618 else if (diff.assertions.failedButOk > 0)
15619 ++diff.testCases.failedButOk;
15621 ++diff.testCases.passed;
15625 } // namespace Catch
15626 // end catch_totals.cpp
15627 // start catch_uncaught_exceptions.cpp
15629 // start catch_config_uncaught_exceptions.hpp
15631 // Copyright Catch2 Authors
15632 // Distributed under the Boost Software License, Version 1.0.
15633 // (See accompanying file LICENSE_1_0.txt or copy at
15634 // https://www.boost.org/LICENSE_1_0.txt)
15636 // SPDX-License-Identifier: BSL-1.0
15638 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15639 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15641 #if defined(_MSC_VER)
15642 #if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15643 #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15647 #include <exception>
15649 #if defined(__cpp_lib_uncaught_exceptions) && \
15650 !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15652 #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15653 #endif // __cpp_lib_uncaught_exceptions
15655 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && \
15656 !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && \
15657 !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15659 #define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15662 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15663 // end catch_config_uncaught_exceptions.hpp
15664 #include <exception>
15667 bool uncaught_exceptions() {
15668 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15670 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15671 return std::uncaught_exceptions() > 0;
15673 return std::uncaught_exception();
15676 } // end namespace Catch
15677 // end catch_uncaught_exceptions.cpp
15678 // start catch_version.cpp
15684 Version::Version(unsigned int _majorVersion,
15685 unsigned int _minorVersion,
15686 unsigned int _patchNumber,
15687 char const* const _branchName,
15688 unsigned int _buildNumber) :
15689 majorVersion(_majorVersion),
15690 minorVersion(_minorVersion),
15691 patchNumber(_patchNumber),
15692 branchName(_branchName),
15693 buildNumber(_buildNumber) {}
15695 std::ostream& operator<<(std::ostream& os, Version const& version) {
15696 os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber;
15697 // branchName is never null -> 0th char is \0 if it is empty
15698 if (version.branchName[0]) {
15699 os << '-' << version.branchName << '.' << version.buildNumber;
15704 Version const& libraryVersion() {
15705 static Version version(2, 13, 7, "", 0);
15709 } // namespace Catch
15710 // end catch_version.cpp
15711 // start catch_wildcard_pattern.cpp
15715 WildcardPattern::WildcardPattern(std::string const& pattern,
15716 CaseSensitive::Choice caseSensitivity) :
15717 m_caseSensitivity(caseSensitivity), m_pattern(normaliseString(pattern)) {
15718 if (startsWith(m_pattern, '*')) {
15719 m_pattern = m_pattern.substr(1);
15720 m_wildcard = WildcardAtStart;
15722 if (endsWith(m_pattern, '*')) {
15723 m_pattern = m_pattern.substr(0, m_pattern.size() - 1);
15724 m_wildcard = static_cast<WildcardPosition>(m_wildcard | WildcardAtEnd);
15728 bool WildcardPattern::matches(std::string const& str) const {
15729 switch (m_wildcard) {
15731 return m_pattern == normaliseString(str);
15732 case WildcardAtStart:
15733 return endsWith(normaliseString(str), m_pattern);
15734 case WildcardAtEnd:
15735 return startsWith(normaliseString(str), m_pattern);
15736 case WildcardAtBothEnds:
15737 return contains(normaliseString(str), m_pattern);
15739 CATCH_INTERNAL_ERROR("Unknown enum");
15743 std::string WildcardPattern::normaliseString(std::string const& str) const {
15744 return trim(m_caseSensitivity == CaseSensitive::No ? toLower(str) : str);
15746 } // namespace Catch
15747 // end catch_wildcard_pattern.cpp
15748 // start catch_xmlwriter.cpp
15751 #include <type_traits>
15757 size_t trailingBytes(unsigned char c) {
15758 if ((c & 0xE0) == 0xC0) {
15761 if ((c & 0xF0) == 0xE0) {
15764 if ((c & 0xF8) == 0xF0) {
15767 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15770 uint32_t headerValue(unsigned char c) {
15771 if ((c & 0xE0) == 0xC0) {
15774 if ((c & 0xF0) == 0xE0) {
15777 if ((c & 0xF8) == 0xF0) {
15780 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15783 void hexEscapeChar(std::ostream& os, unsigned char c) {
15784 std::ios_base::fmtflags f(os.flags());
15785 os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15786 << static_cast<int>(c);
15790 bool shouldNewline(XmlFormatting fmt) {
15791 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(
15792 fmt & XmlFormatting::Newline));
15795 bool shouldIndent(XmlFormatting fmt) {
15796 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(
15797 fmt & XmlFormatting::Indent));
15800 } // anonymous namespace
15802 XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs) {
15803 return static_cast<XmlFormatting>(
15804 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15805 static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
15808 XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs) {
15809 return static_cast<XmlFormatting>(
15810 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15811 static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
15814 XmlEncode::XmlEncode(std::string const& str, ForWhat forWhat) :
15815 m_str(str), m_forWhat(forWhat) {}
15817 void XmlEncode::encodeTo(std::ostream& os) const {
15818 // Apostrophe escaping not necessary if we always use " to write
15819 // attributes (see: http://www.w3.org/TR/xml/#syntax)
15821 for (std::size_t idx = 0; idx < m_str.size(); ++idx) {
15822 unsigned char c = m_str[idx];
15832 // See: http://www.w3.org/TR/xml/#syntax
15833 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15840 if (m_forWhat == ForAttributes)
15847 // Check for control characters and invalid utf-8
15849 // Escape control characters in standard ascii
15851 // http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15852 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15853 hexEscapeChar(os, c);
15857 // Plain ASCII: Write it to stream
15864 // Check if the encoding is valid and if it is not, hex
15865 // escape bytes. Important: We do not check the exact
15866 // decoded values for validity, only the encoding format
15867 // First check that this bytes is a valid lead byte:
15868 // This means that it is not encoded as 1111 1XXX
15870 if (c < 0xC0 || c >= 0xF8) {
15871 hexEscapeChar(os, c);
15875 auto encBytes = trailingBytes(c);
15876 // Are there enough bytes left to avoid accessing
15877 // out-of-bounds memory?
15878 if (idx + encBytes - 1 >= m_str.size()) {
15879 hexEscapeChar(os, c);
15882 // The header is valid, check data
15883 // The next encBytes bytes must together be a valid utf-8
15884 // This means: bitpattern 10XX XXXX and the extracted value
15887 uint32_t value = headerValue(c);
15888 for (std::size_t n = 1; n < encBytes; ++n) {
15889 unsigned char nc = m_str[idx + n];
15890 valid &= ((nc & 0xC0) == 0x80);
15891 value = (value << 6) | (nc & 0x3F);
15895 // Wrong bit pattern of following bytes
15897 // Overlong encodings
15898 (value < 0x80) || (0x80 <= value && value < 0x800 && encBytes > 2) ||
15899 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15900 // Encoded value out of range
15901 (value >= 0x110000))
15903 hexEscapeChar(os, c);
15907 // If we got here, this is in fact a valid(ish) utf-8
15909 for (std::size_t n = 0; n < encBytes; ++n) {
15910 os << m_str[idx + n];
15912 idx += encBytes - 1;
15918 std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode) {
15919 xmlEncode.encodeTo(os);
15923 XmlWriter::ScopedElement::ScopedElement(XmlWriter* writer, XmlFormatting fmt) :
15924 m_writer(writer), m_fmt(fmt) {}
15926 XmlWriter::ScopedElement::ScopedElement(ScopedElement&& other) noexcept :
15927 m_writer(other.m_writer), m_fmt(other.m_fmt) {
15928 other.m_writer = nullptr;
15929 other.m_fmt = XmlFormatting::None;
15931 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=(ScopedElement&& other) noexcept {
15933 m_writer->endElement();
15935 m_writer = other.m_writer;
15936 other.m_writer = nullptr;
15937 m_fmt = other.m_fmt;
15938 other.m_fmt = XmlFormatting::None;
15942 XmlWriter::ScopedElement::~ScopedElement() {
15944 m_writer->endElement(m_fmt);
15948 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText(std::string const& text,
15949 XmlFormatting fmt) {
15950 m_writer->writeText(text, fmt);
15954 XmlWriter::XmlWriter(std::ostream& os) : m_os(os) { writeDeclaration(); }
15956 XmlWriter::~XmlWriter() {
15957 while (!m_tags.empty()) {
15960 newlineIfNecessary();
15963 XmlWriter& XmlWriter::startElement(std::string const& name, XmlFormatting fmt) {
15965 newlineIfNecessary();
15966 if (shouldIndent(fmt)) {
15970 m_os << '<' << name;
15971 m_tags.push_back(name);
15972 m_tagIsOpen = true;
15973 applyFormatting(fmt);
15977 XmlWriter::ScopedElement XmlWriter::scopedElement(std::string const& name, XmlFormatting fmt) {
15978 ScopedElement scoped(this, fmt);
15979 startElement(name, fmt);
15983 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15984 m_indent = m_indent.substr(0, m_indent.size() - 2);
15988 m_tagIsOpen = false;
15990 newlineIfNecessary();
15991 if (shouldIndent(fmt)) {
15994 m_os << "</" << m_tags.back() << ">";
15996 m_os << std::flush;
15997 applyFormatting(fmt);
16002 XmlWriter& XmlWriter::writeAttribute(std::string const& name, std::string const& attribute) {
16003 if (!name.empty() && !attribute.empty())
16004 m_os << ' ' << name << "=\"" << XmlEncode(attribute, XmlEncode::ForAttributes) << '"';
16008 XmlWriter& XmlWriter::writeAttribute(std::string const& name, bool attribute) {
16009 m_os << ' ' << name << "=\"" << (attribute ? "true" : "false") << '"';
16013 XmlWriter& XmlWriter::writeText(std::string const& text, XmlFormatting fmt) {
16014 if (!text.empty()) {
16015 bool tagWasOpen = m_tagIsOpen;
16017 if (tagWasOpen && shouldIndent(fmt)) {
16020 m_os << XmlEncode(text);
16021 applyFormatting(fmt);
16026 XmlWriter& XmlWriter::writeComment(std::string const& text, XmlFormatting fmt) {
16028 if (shouldIndent(fmt)) {
16031 m_os << "<!--" << text << "-->";
16032 applyFormatting(fmt);
16036 void XmlWriter::writeStylesheetRef(std::string const& url) {
16037 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
16040 XmlWriter& XmlWriter::writeBlankLine() {
16046 void XmlWriter::ensureTagClosed() {
16048 m_os << '>' << std::flush;
16049 newlineIfNecessary();
16050 m_tagIsOpen = false;
16054 void XmlWriter::applyFormatting(XmlFormatting fmt) { m_needsNewline = shouldNewline(fmt); }
16056 void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; }
16058 void XmlWriter::newlineIfNecessary() {
16059 if (m_needsNewline) {
16061 m_needsNewline = false;
16064 } // namespace Catch
16065 // end catch_xmlwriter.cpp
16066 // start catch_reporter_bases.cpp
16075 void prepareExpandedExpression(AssertionResult& result) { result.getExpandedExpression(); }
16077 // Because formatting using c++ streams is stateful, drop down to C is
16078 // required Alternatively we could use stringstream, but its performance
16080 std::string getFormattedDuration(double duration) {
16081 // Max exponent + 1 is required to represent the whole part
16082 // + 1 for decimal point
16083 // + 3 for the 3 decimal places
16084 // + 1 for null terminator
16085 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
16086 char buffer[maxDoubleSize];
16088 // Save previous errno, to prevent sprintf from overwriting it
16091 sprintf_s(buffer, "%.3f", duration);
16093 std::sprintf(buffer, "%.3f", duration);
16095 return std::string(buffer);
16098 bool shouldShowDuration(IConfig const& config, double duration) {
16099 if (config.showDurations() == ShowDurations::Always) {
16102 if (config.showDurations() == ShowDurations::Never) {
16105 const double min = config.minDuration();
16106 return min >= 0 && duration >= min;
16109 std::string serializeFilters(std::vector<std::string> const& container) {
16110 ReusableStringStream oss;
16112 for (auto&& filter : container) {
16123 TestEventListenerBase::TestEventListenerBase(ReporterConfig const& _config) :
16124 StreamingReporterBase(_config) {}
16126 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
16127 return {Verbosity::Quiet, Verbosity::Normal, Verbosity::High};
16130 void TestEventListenerBase::assertionStarting(AssertionInfo const&) {}
16132 bool TestEventListenerBase::assertionEnded(AssertionStats const&) { return false; }
16134 } // end namespace Catch
16135 // end catch_reporter_bases.cpp
16136 // start catch_reporter_compact.cpp
16140 #ifdef CATCH_PLATFORM_MAC
16141 const char* failedString() { return "FAILED"; }
16142 const char* passedString() { return "PASSED"; }
16144 const char* failedString() { return "failed"; }
16145 const char* passedString() { return "passed"; }
16148 // Colour::LightGrey
16149 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
16151 std::string bothOrAll(std::size_t count) {
16152 return count == 1 ? std::string() : count == 2 ? "both " : "all ";
16159 // Colour, message variants:
16160 // - white: No tests ran.
16161 // - red: Failed [both/all] N test cases, failed [both/all] M
16163 // - white: Passed [both/all] N test cases (no assertions).
16164 // - red: Failed N tests cases, failed M assertions.
16165 // - green: Passed [both/all] N tests cases with M assertions.
16166 void printTotals(std::ostream& out, const Totals& totals) {
16167 if (totals.testCases.total() == 0) {
16168 out << "No tests ran.";
16169 } else if (totals.testCases.failed == totals.testCases.total()) {
16170 Colour colour(Colour::ResultError);
16171 const std::string qualify_assertions_failed =
16172 totals.assertions.failed == totals.assertions.total()
16173 ? bothOrAll(totals.assertions.failed)
16175 out << "Failed " << bothOrAll(totals.testCases.failed)
16176 << pluralise(totals.testCases.failed, "test case")
16179 << qualify_assertions_failed << pluralise(totals.assertions.failed, "assertion")
16181 } else if (totals.assertions.total() == 0) {
16182 out << "Passed " << bothOrAll(totals.testCases.total())
16183 << pluralise(totals.testCases.total(), "test case") << " (no assertions).";
16184 } else if (totals.assertions.failed) {
16185 Colour colour(Colour::ResultError);
16186 out << "Failed " << pluralise(totals.testCases.failed, "test case")
16189 << pluralise(totals.assertions.failed, "assertion") << '.';
16191 Colour colour(Colour::ResultSuccess);
16192 out << "Passed " << bothOrAll(totals.testCases.passed)
16193 << pluralise(totals.testCases.passed, "test case") << " with "
16194 << pluralise(totals.assertions.passed, "assertion") << '.';
16198 // Implementation of CompactReporter formatting
16199 class AssertionPrinter {
16201 AssertionPrinter& operator=(AssertionPrinter const&) = delete;
16202 AssertionPrinter(AssertionPrinter const&) = delete;
16203 AssertionPrinter(std::ostream& _stream,
16204 AssertionStats const& _stats,
16205 bool _printInfoMessages) :
16207 result(_stats.assertionResult),
16208 messages(_stats.infoMessages),
16209 itMessage(_stats.infoMessages.begin()),
16210 printInfoMessages(_printInfoMessages) {}
16215 itMessage = messages.begin();
16217 switch (result.getResultType()) {
16218 case ResultWas::Ok:
16219 printResultType(Colour::ResultSuccess, passedString());
16220 printOriginalExpression();
16221 printReconstructedExpression();
16222 if (!result.hasExpression())
16223 printRemainingMessages(Colour::None);
16225 printRemainingMessages();
16227 case ResultWas::ExpressionFailed:
16229 printResultType(Colour::ResultSuccess,
16230 failedString() + std::string(" - but was ok"));
16232 printResultType(Colour::Error, failedString());
16233 printOriginalExpression();
16234 printReconstructedExpression();
16235 printRemainingMessages();
16237 case ResultWas::ThrewException:
16238 printResultType(Colour::Error, failedString());
16239 printIssue("unexpected exception with message:");
16241 printExpressionWas();
16242 printRemainingMessages();
16244 case ResultWas::FatalErrorCondition:
16245 printResultType(Colour::Error, failedString());
16246 printIssue("fatal error condition with message:");
16248 printExpressionWas();
16249 printRemainingMessages();
16251 case ResultWas::DidntThrowException:
16252 printResultType(Colour::Error, failedString());
16253 printIssue("expected exception, got none");
16254 printExpressionWas();
16255 printRemainingMessages();
16257 case ResultWas::Info:
16258 printResultType(Colour::None, "info");
16260 printRemainingMessages();
16262 case ResultWas::Warning:
16263 printResultType(Colour::None, "warning");
16265 printRemainingMessages();
16267 case ResultWas::ExplicitFailure:
16268 printResultType(Colour::Error, failedString());
16269 printIssue("explicitly");
16270 printRemainingMessages(Colour::None);
16272 // These cases are here to prevent compiler warnings
16273 case ResultWas::Unknown:
16274 case ResultWas::FailureBit:
16275 case ResultWas::Exception:
16276 printResultType(Colour::Error, "** internal error **");
16282 void printSourceInfo() const {
16283 Colour colourGuard(Colour::FileName);
16284 stream << result.getSourceInfo() << ':';
16287 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
16288 if (!passOrFail.empty()) {
16290 Colour colourGuard(colour);
16291 stream << ' ' << passOrFail;
16297 void printIssue(std::string const& issue) const { stream << ' ' << issue; }
16299 void printExpressionWas() {
16300 if (result.hasExpression()) {
16303 Colour colour(dimColour());
16304 stream << " expression was:";
16306 printOriginalExpression();
16310 void printOriginalExpression() const {
16311 if (result.hasExpression()) {
16312 stream << ' ' << result.getExpression();
16316 void printReconstructedExpression() const {
16317 if (result.hasExpandedExpression()) {
16319 Colour colour(dimColour());
16320 stream << " for: ";
16322 stream << result.getExpandedExpression();
16326 void printMessage() {
16327 if (itMessage != messages.end()) {
16328 stream << " '" << itMessage->message << '\'';
16333 void printRemainingMessages(Colour::Code colour = dimColour()) {
16334 if (itMessage == messages.end())
16337 const auto itEnd = messages.cend();
16338 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16341 Colour colourGuard(colour);
16342 stream << " with " << pluralise(N, "message") << ':';
16345 while (itMessage != itEnd) {
16346 // If this assertion is a warning ignore any INFO messages
16347 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16349 if (itMessage != itEnd) {
16350 Colour colourGuard(dimColour());
16360 std::ostream& stream;
16361 AssertionResult const& result;
16362 std::vector<MessageInfo> messages;
16363 std::vector<MessageInfo>::const_iterator itMessage;
16364 bool printInfoMessages;
16369 std::string CompactReporter::getDescription() {
16370 return "Reports test results on a single line, suitable for IDEs";
16373 void CompactReporter::noMatchingTestCases(std::string const& spec) {
16374 stream << "No test cases matched '" << spec << '\'' << std::endl;
16377 void CompactReporter::assertionStarting(AssertionInfo const&) {}
16379 bool CompactReporter::assertionEnded(AssertionStats const& _assertionStats) {
16380 AssertionResult const& result = _assertionStats.assertionResult;
16382 bool printInfoMessages = true;
16384 // Drop out if result was successful and we're not printing those
16385 if (!m_config->includeSuccessfulResults() && result.isOk()) {
16386 if (result.getResultType() != ResultWas::Warning)
16388 printInfoMessages = false;
16391 AssertionPrinter printer(stream, _assertionStats, printInfoMessages);
16394 stream << std::endl;
16398 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16399 double dur = _sectionStats.durationInSeconds;
16400 if (shouldShowDuration(*m_config, dur)) {
16401 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name
16406 void CompactReporter::testRunEnded(TestRunStats const& _testRunStats) {
16407 printTotals(stream, _testRunStats.totals);
16408 stream << '\n' << std::endl;
16409 StreamingReporterBase::testRunEnded(_testRunStats);
16412 CompactReporter::~CompactReporter() {}
16414 CATCH_REGISTER_REPORTER("compact", CompactReporter)
16416 } // end namespace Catch
16417 // end catch_reporter_compact.cpp
16418 // start catch_reporter_console.cpp
16423 #if defined(_MSC_VER)
16424 #pragma warning(push)
16425 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in switch
16426 // Note that 4062 (not all labels are handled and default is missing) is
16430 #if defined(__clang__)
16431 #pragma clang diagnostic push
16432 // For simplicity, benchmarking-only helpers are always enabled
16433 #pragma clang diagnostic ignored "-Wunused-function"
16440 // Formatter impl for ConsoleReporter
16441 class ConsoleAssertionPrinter {
16443 ConsoleAssertionPrinter& operator=(ConsoleAssertionPrinter const&) = delete;
16444 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
16445 ConsoleAssertionPrinter(std::ostream& _stream,
16446 AssertionStats const& _stats,
16447 bool _printInfoMessages) :
16450 result(_stats.assertionResult),
16451 colour(Colour::None),
16452 message(result.getMessage()),
16453 messages(_stats.infoMessages),
16454 printInfoMessages(_printInfoMessages) {
16455 switch (result.getResultType()) {
16456 case ResultWas::Ok:
16457 colour = Colour::Success;
16458 passOrFail = "PASSED";
16459 // if( result.hasMessage() )
16460 if (_stats.infoMessages.size() == 1)
16461 messageLabel = "with message";
16462 if (_stats.infoMessages.size() > 1)
16463 messageLabel = "with messages";
16465 case ResultWas::ExpressionFailed:
16466 if (result.isOk()) {
16467 colour = Colour::Success;
16468 passOrFail = "FAILED - but was ok";
16470 colour = Colour::Error;
16471 passOrFail = "FAILED";
16473 if (_stats.infoMessages.size() == 1)
16474 messageLabel = "with message";
16475 if (_stats.infoMessages.size() > 1)
16476 messageLabel = "with messages";
16478 case ResultWas::ThrewException:
16479 colour = Colour::Error;
16480 passOrFail = "FAILED";
16481 messageLabel = "due to unexpected exception with ";
16482 if (_stats.infoMessages.size() == 1)
16483 messageLabel += "message";
16484 if (_stats.infoMessages.size() > 1)
16485 messageLabel += "messages";
16487 case ResultWas::FatalErrorCondition:
16488 colour = Colour::Error;
16489 passOrFail = "FAILED";
16490 messageLabel = "due to a fatal error condition";
16492 case ResultWas::DidntThrowException:
16493 colour = Colour::Error;
16494 passOrFail = "FAILED";
16495 messageLabel = "because no exception was thrown where "
16496 "one was expected";
16498 case ResultWas::Info:
16499 messageLabel = "info";
16501 case ResultWas::Warning:
16502 messageLabel = "warning";
16504 case ResultWas::ExplicitFailure:
16505 passOrFail = "FAILED";
16506 colour = Colour::Error;
16507 if (_stats.infoMessages.size() == 1)
16508 messageLabel = "explicitly with message";
16509 if (_stats.infoMessages.size() > 1)
16510 messageLabel = "explicitly with messages";
16512 // These cases are here to prevent compiler warnings
16513 case ResultWas::Unknown:
16514 case ResultWas::FailureBit:
16515 case ResultWas::Exception:
16516 passOrFail = "** internal error **";
16517 colour = Colour::Error;
16522 void print() const {
16524 if (stats.totals.assertions.total() > 0) {
16526 printOriginalExpression();
16527 printReconstructedExpression();
16535 void printResultType() const {
16536 if (!passOrFail.empty()) {
16537 Colour colourGuard(colour);
16538 stream << passOrFail << ":\n";
16541 void printOriginalExpression() const {
16542 if (result.hasExpression()) {
16543 Colour colourGuard(Colour::OriginalExpression);
16545 stream << result.getExpressionInMacro();
16549 void printReconstructedExpression() const {
16550 if (result.hasExpandedExpression()) {
16551 stream << "with expansion:\n";
16552 Colour colourGuard(Colour::ReconstructedExpression);
16553 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16556 void printMessage() const {
16557 if (!messageLabel.empty())
16558 stream << messageLabel << ':' << '\n';
16559 for (auto const& msg : messages) {
16560 // If this assertion is a warning ignore any INFO messages
16561 if (printInfoMessages || msg.type != ResultWas::Info)
16562 stream << Column(msg.message).indent(2) << '\n';
16565 void printSourceInfo() const {
16566 Colour colourGuard(Colour::FileName);
16567 stream << result.getSourceInfo() << ": ";
16570 std::ostream& stream;
16571 AssertionStats const& stats;
16572 AssertionResult const& result;
16573 Colour::Code colour;
16574 std::string passOrFail;
16575 std::string messageLabel;
16576 std::string message;
16577 std::vector<MessageInfo> messages;
16578 bool printInfoMessages;
16581 std::size_t makeRatio(std::size_t number, std::size_t total) {
16582 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16583 return (ratio == 0 && number > 0) ? 1 : ratio;
16586 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16587 if (i > j && i > k)
16595 struct ColumnInfo {
16596 enum Justification { Left, Right };
16599 Justification justification;
16601 struct ColumnBreak {};
16602 struct RowBreak {};
16605 enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes };
16606 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16607 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16608 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16609 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16611 double m_inNanoseconds;
16615 explicit Duration(double inNanoseconds, Unit units = Unit::Auto) :
16616 m_inNanoseconds(inNanoseconds), m_units(units) {
16617 if (m_units == Unit::Auto) {
16618 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16619 m_units = Unit::Nanoseconds;
16620 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16621 m_units = Unit::Microseconds;
16622 else if (m_inNanoseconds < s_nanosecondsInASecond)
16623 m_units = Unit::Milliseconds;
16624 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16625 m_units = Unit::Seconds;
16627 m_units = Unit::Minutes;
16631 auto value() const -> double {
16633 case Unit::Microseconds:
16634 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16635 case Unit::Milliseconds:
16636 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16637 case Unit::Seconds:
16638 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16639 case Unit::Minutes:
16640 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16642 return m_inNanoseconds;
16645 auto unitsAsString() const -> std::string {
16647 case Unit::Nanoseconds:
16649 case Unit::Microseconds:
16651 case Unit::Milliseconds:
16653 case Unit::Seconds:
16655 case Unit::Minutes:
16658 return "** internal error **";
16661 friend auto operator<<(std::ostream& os, Duration const& duration) -> std::ostream& {
16662 return os << duration.value() << ' ' << duration.unitsAsString();
16667 class TablePrinter {
16668 std::ostream& m_os;
16669 std::vector<ColumnInfo> m_columnInfos;
16670 std::ostringstream m_oss;
16671 int m_currentColumn = -1;
16672 bool m_isOpen = false;
16675 TablePrinter(std::ostream& os, std::vector<ColumnInfo> columnInfos) :
16676 m_os(os), m_columnInfos(std::move(columnInfos)) {}
16678 auto columnInfos() const -> std::vector<ColumnInfo> const& { return m_columnInfos; }
16683 *this << RowBreak();
16685 Columns headerCols;
16687 for (auto const& info : m_columnInfos) {
16688 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16689 headerCols += spacer;
16691 m_os << headerCols << '\n';
16693 m_os << Catch::getLineOfChars<'-'>() << '\n';
16698 *this << RowBreak();
16704 template <typename T> friend TablePrinter& operator<<(TablePrinter& tp, T const& value) {
16709 friend TablePrinter& operator<<(TablePrinter& tp, ColumnBreak) {
16710 auto colStr = tp.m_oss.str();
16711 const auto strSize = colStr.size();
16714 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16715 tp.m_currentColumn = -1;
16718 tp.m_currentColumn++;
16720 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16721 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16722 ? std::string(colInfo.width - (strSize + 1), ' ')
16724 if (colInfo.justification == ColumnInfo::Left)
16725 tp.m_os << colStr << padding << ' ';
16727 tp.m_os << padding << colStr << ' ';
16731 friend TablePrinter& operator<<(TablePrinter& tp, RowBreak) {
16732 if (tp.m_currentColumn > 0) {
16734 tp.m_currentColumn = -1;
16740 ConsoleReporter::ConsoleReporter(ReporterConfig const& config) :
16741 StreamingReporterBase(config),
16742 m_tablePrinter(new TablePrinter(config.stream(), [&config]() -> std::vector<ColumnInfo> {
16743 if (config.fullConfig()->benchmarkNoAnalysis()) {
16744 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16745 {" samples", 14, ColumnInfo::Right},
16746 {" iterations", 14, ColumnInfo::Right},
16747 {" mean", 14, ColumnInfo::Right}};
16749 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16750 {"samples mean std dev", 14, ColumnInfo::Right},
16751 {"iterations low mean low std dev", 14, ColumnInfo::Right},
16752 {"estimated high mean high std dev", 14, ColumnInfo::Right}};
16755 ConsoleReporter::~ConsoleReporter() = default;
16757 std::string ConsoleReporter::getDescription() {
16758 return "Reports test results as plain lines of text";
16761 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16762 stream << "No test cases matched '" << spec << '\'' << std::endl;
16765 void ConsoleReporter::reportInvalidArguments(std::string const& arg) {
16766 stream << "Invalid Filter: " << arg << std::endl;
16769 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16771 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16772 AssertionResult const& result = _assertionStats.assertionResult;
16774 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16776 // Drop out if result was successful but we're not printing them.
16777 if (!includeResults && result.getResultType() != ResultWas::Warning)
16782 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16784 stream << std::endl;
16788 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16789 m_tablePrinter->close();
16790 m_headerPrinted = false;
16791 StreamingReporterBase::sectionStarting(_sectionInfo);
16793 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16794 m_tablePrinter->close();
16795 if (_sectionStats.missingAssertions) {
16797 Colour colour(Colour::ResultError);
16798 if (m_sectionStack.size() > 1)
16799 stream << "\nNo assertions in section";
16801 stream << "\nNo assertions in test case";
16802 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16804 double dur = _sectionStats.durationInSeconds;
16805 if (shouldShowDuration(*m_config, dur)) {
16806 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name
16809 if (m_headerPrinted) {
16810 m_headerPrinted = false;
16812 StreamingReporterBase::sectionEnded(_sectionStats);
16815 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16816 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16817 lazyPrintWithoutClosingBenchmarkTable();
16819 auto nameCol = Column(name).width(
16820 static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16822 bool firstLine = true;
16823 for (auto line : nameCol) {
16825 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16829 (*m_tablePrinter) << line << ColumnBreak();
16833 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16834 (*m_tablePrinter) << info.samples << ColumnBreak() << info.iterations << ColumnBreak();
16835 if (!m_config->benchmarkNoAnalysis())
16836 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16838 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16839 if (m_config->benchmarkNoAnalysis()) {
16840 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16842 (*m_tablePrinter) << ColumnBreak() << Duration(stats.mean.point.count())
16843 << ColumnBreak() << Duration(stats.mean.lower_bound.count())
16844 << ColumnBreak() << Duration(stats.mean.upper_bound.count())
16845 << ColumnBreak() << ColumnBreak()
16846 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16847 << Duration(stats.standardDeviation.lower_bound.count())
16849 << Duration(stats.standardDeviation.upper_bound.count())
16850 << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak()
16855 void ConsoleReporter::benchmarkFailed(std::string const& error) {
16856 Colour colour(Colour::Red);
16857 (*m_tablePrinter) << "Benchmark failed (" << error << ')' << ColumnBreak() << RowBreak();
16859 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16861 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16862 m_tablePrinter->close();
16863 StreamingReporterBase::testCaseEnded(_testCaseStats);
16864 m_headerPrinted = false;
16866 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16867 if (currentGroupInfo.used) {
16868 printSummaryDivider();
16869 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16870 printTotals(_testGroupStats.totals);
16871 stream << '\n' << std::endl;
16873 StreamingReporterBase::testGroupEnded(_testGroupStats);
16875 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16876 printTotalsDivider(_testRunStats.totals);
16877 printTotals(_testRunStats.totals);
16878 stream << std::endl;
16879 StreamingReporterBase::testRunEnded(_testRunStats);
16881 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16882 StreamingReporterBase::testRunStarting(_testInfo);
16883 printTestFilters();
16886 void ConsoleReporter::lazyPrint() {
16888 m_tablePrinter->close();
16889 lazyPrintWithoutClosingBenchmarkTable();
16892 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16894 if (!currentTestRunInfo.used)
16895 lazyPrintRunInfo();
16896 if (!currentGroupInfo.used)
16897 lazyPrintGroupInfo();
16899 if (!m_headerPrinted) {
16900 printTestCaseAndSectionHeader();
16901 m_headerPrinted = true;
16904 void ConsoleReporter::lazyPrintRunInfo() {
16905 stream << '\n' << getLineOfChars<'~'>() << '\n';
16906 Colour colour(Colour::SecondaryText);
16907 stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion()
16908 << " host application.\n"
16909 << "Run with -? for options\n\n";
16911 if (m_config->rngSeed() != 0)
16912 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16914 currentTestRunInfo.used = true;
16916 void ConsoleReporter::lazyPrintGroupInfo() {
16917 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16918 printClosedHeader("Group: " + currentGroupInfo->name);
16919 currentGroupInfo.used = true;
16922 void ConsoleReporter::printTestCaseAndSectionHeader() {
16923 assert(!m_sectionStack.empty());
16924 printOpenHeader(currentTestCaseInfo->name);
16926 if (m_sectionStack.size() > 1) {
16927 Colour colourGuard(Colour::Headers);
16929 auto it = m_sectionStack.begin() + 1, // Skip first section (test case)
16930 itEnd = m_sectionStack.end();
16931 for (; it != itEnd; ++it)
16932 printHeaderString(it->name, 2);
16935 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16937 stream << getLineOfChars<'-'>() << '\n';
16938 Colour colourGuard(Colour::FileName);
16939 stream << lineInfo << '\n';
16940 stream << getLineOfChars<'.'>() << '\n' << std::endl;
16943 void ConsoleReporter::printClosedHeader(std::string const& _name) {
16944 printOpenHeader(_name);
16945 stream << getLineOfChars<'.'>() << '\n';
16947 void ConsoleReporter::printOpenHeader(std::string const& _name) {
16948 stream << getLineOfChars<'-'>() << '\n';
16950 Colour colourGuard(Colour::Headers);
16951 printHeaderString(_name);
16955 // if string has a : in first line will set indent to follow it on
16956 // subsequent lines
16957 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16958 std::size_t i = _string.find(": ");
16959 if (i != std::string::npos)
16963 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16966 struct SummaryColumn {
16968 SummaryColumn(std::string _label, Colour::Code _colour) :
16969 label(std::move(_label)), colour(_colour) {}
16970 SummaryColumn addRow(std::size_t count) {
16971 ReusableStringStream rss;
16973 std::string row = rss.str();
16974 for (auto& oldRow : rows) {
16975 while (oldRow.size() < row.size())
16976 oldRow = ' ' + oldRow;
16977 while (oldRow.size() > row.size())
16980 rows.push_back(row);
16985 Colour::Code colour;
16986 std::vector<std::string> rows;
16989 void ConsoleReporter::printTotals(Totals const& totals) {
16990 if (totals.testCases.total() == 0) {
16991 stream << Colour(Colour::Warning) << "No tests ran\n";
16992 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16993 stream << Colour(Colour::ResultSuccess) << "All tests passed";
16994 stream << " (" << pluralise(totals.assertions.passed, "assertion") << " in "
16995 << pluralise(totals.testCases.passed, "test case") << ')' << '\n';
16998 std::vector<SummaryColumn> columns;
16999 columns.push_back(SummaryColumn("", Colour::None)
17000 .addRow(totals.testCases.total())
17001 .addRow(totals.assertions.total()));
17002 columns.push_back(SummaryColumn("passed", Colour::Success)
17003 .addRow(totals.testCases.passed)
17004 .addRow(totals.assertions.passed));
17005 columns.push_back(SummaryColumn("failed", Colour::ResultError)
17006 .addRow(totals.testCases.failed)
17007 .addRow(totals.assertions.failed));
17008 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
17009 .addRow(totals.testCases.failedButOk)
17010 .addRow(totals.assertions.failedButOk));
17012 printSummaryRow("test cases", columns, 0);
17013 printSummaryRow("assertions", columns, 1);
17016 void ConsoleReporter::printSummaryRow(std::string const& label,
17017 std::vector<SummaryColumn> const& cols,
17019 for (auto col : cols) {
17020 std::string value = col.rows[row];
17021 if (col.label.empty()) {
17022 stream << label << ": ";
17026 stream << Colour(Colour::Warning) << "- none -";
17027 } else if (value != "0") {
17028 stream << Colour(Colour::LightGrey) << " | ";
17029 stream << Colour(col.colour) << value << ' ' << col.label;
17035 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
17036 if (totals.testCases.total() > 0) {
17037 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
17038 std::size_t failedButOkRatio =
17039 makeRatio(totals.testCases.failedButOk, totals.testCases.total());
17040 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
17041 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
17042 findMax(failedRatio, failedButOkRatio, passedRatio)++;
17043 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
17044 findMax(failedRatio, failedButOkRatio, passedRatio)--;
17046 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
17047 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
17048 if (totals.testCases.allPassed())
17049 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
17051 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
17053 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
17057 void ConsoleReporter::printSummaryDivider() { stream << getLineOfChars<'-'>() << '\n'; }
17059 void ConsoleReporter::printTestFilters() {
17060 if (m_config->testSpec().hasFilters()) {
17061 Colour guard(Colour::BrightYellow);
17062 stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
17066 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
17068 } // end namespace Catch
17070 #if defined(_MSC_VER)
17071 #pragma warning(pop)
17074 #if defined(__clang__)
17075 #pragma clang diagnostic pop
17077 // end catch_reporter_console.cpp
17078 // start catch_reporter_junit.cpp
17083 #include <algorithm>
17089 std::string getCurrentTimestamp() {
17090 // Beware, this is not reentrant because of backward compatibility
17091 // issues Also, UTC only, again because of backward compatibility
17094 std::time(&rawtime);
17095 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
17098 std::tm timeInfo = {};
17099 gmtime_s(&timeInfo, &rawtime);
17102 timeInfo = std::gmtime(&rawtime);
17105 char timeStamp[timeStampSize];
17106 const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
17109 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
17111 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
17113 return std::string(timeStamp, timeStampSize - 1);
17116 std::string fileNameTag(const std::vector<std::string>& tags) {
17117 auto it = std::find_if(
17118 begin(tags), end(tags), [](std::string const& tag) { return tag.front() == '#'; });
17119 if (it != tags.end())
17120 return it->substr(1);
17121 return std::string();
17124 // Formats the duration in seconds to 3 decimal places.
17125 // This is done because some genius defined Maven Surefire schema
17126 // in a way that only accepts 3 decimal places, and tools like
17127 // Jenkins use that schema for validation JUnit reporter output.
17128 std::string formatDuration(double seconds) {
17129 ReusableStringStream rss;
17130 rss << std::fixed << std::setprecision(3) << seconds;
17134 } // anonymous namespace
17136 JunitReporter::JunitReporter(ReporterConfig const& _config) :
17137 CumulativeReporterBase(_config), xml(_config.stream()) {
17138 m_reporterPrefs.shouldRedirectStdOut = true;
17139 m_reporterPrefs.shouldReportAllAssertions = true;
17142 JunitReporter::~JunitReporter() {}
17144 std::string JunitReporter::getDescription() {
17145 return "Reports test results in an XML format that looks like Ant's "
17146 "junitreport target";
17149 void JunitReporter::noMatchingTestCases(std::string const& /*spec*/) {}
17151 void JunitReporter::testRunStarting(TestRunInfo const& runInfo) {
17152 CumulativeReporterBase::testRunStarting(runInfo);
17153 xml.startElement("testsuites");
17156 void JunitReporter::testGroupStarting(GroupInfo const& groupInfo) {
17157 suiteTimer.start();
17158 stdOutForSuite.clear();
17159 stdErrForSuite.clear();
17160 unexpectedExceptions = 0;
17161 CumulativeReporterBase::testGroupStarting(groupInfo);
17164 void JunitReporter::testCaseStarting(TestCaseInfo const& testCaseInfo) {
17165 m_okToFail = testCaseInfo.okToFail();
17168 bool JunitReporter::assertionEnded(AssertionStats const& assertionStats) {
17169 if (assertionStats.assertionResult.getResultType() == ResultWas::ThrewException &&
17171 unexpectedExceptions++;
17172 return CumulativeReporterBase::assertionEnded(assertionStats);
17175 void JunitReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17176 stdOutForSuite += testCaseStats.stdOut;
17177 stdErrForSuite += testCaseStats.stdErr;
17178 CumulativeReporterBase::testCaseEnded(testCaseStats);
17181 void JunitReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17182 double suiteTime = suiteTimer.getElapsedSeconds();
17183 CumulativeReporterBase::testGroupEnded(testGroupStats);
17184 writeGroup(*m_testGroups.back(), suiteTime);
17187 void JunitReporter::testRunEndedCumulative() { xml.endElement(); }
17189 void JunitReporter::writeGroup(TestGroupNode const& groupNode, double suiteTime) {
17190 XmlWriter::ScopedElement e = xml.scopedElement("testsuite");
17192 TestGroupStats const& stats = groupNode.value;
17193 xml.writeAttribute("name", stats.groupInfo.name);
17194 xml.writeAttribute("errors", unexpectedExceptions);
17195 xml.writeAttribute("failures", stats.totals.assertions.failed - unexpectedExceptions);
17196 xml.writeAttribute("tests", stats.totals.assertions.total());
17197 xml.writeAttribute("hostname", "tbd"); // !TBD
17198 if (m_config->showDurations() == ShowDurations::Never)
17199 xml.writeAttribute("time", "");
17201 xml.writeAttribute("time", formatDuration(suiteTime));
17202 xml.writeAttribute("timestamp", getCurrentTimestamp());
17204 // Write properties if there are any
17205 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
17206 auto properties = xml.scopedElement("properties");
17207 if (m_config->hasTestFilters()) {
17208 xml.scopedElement("property")
17209 .writeAttribute("name", "filters")
17210 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
17212 if (m_config->rngSeed() != 0) {
17213 xml.scopedElement("property")
17214 .writeAttribute("name", "random-seed")
17215 .writeAttribute("value", m_config->rngSeed());
17219 // Write test cases
17220 for (auto const& child : groupNode.children)
17221 writeTestCase(*child);
17223 xml.scopedElement("system-out").writeText(trim(stdOutForSuite), XmlFormatting::Newline);
17224 xml.scopedElement("system-err").writeText(trim(stdErrForSuite), XmlFormatting::Newline);
17227 void JunitReporter::writeTestCase(TestCaseNode const& testCaseNode) {
17228 TestCaseStats const& stats = testCaseNode.value;
17230 // All test cases have exactly one section - which represents the
17231 // test case itself. That section may have 0-n nested sections
17232 assert(testCaseNode.children.size() == 1);
17233 SectionNode const& rootSection = *testCaseNode.children.front();
17235 std::string className = stats.testInfo.className;
17237 if (className.empty()) {
17238 className = fileNameTag(stats.testInfo.tags);
17239 if (className.empty())
17240 className = "global";
17243 if (!m_config->name().empty())
17244 className = m_config->name() + "." + className;
17246 writeSection(className, "", rootSection, stats.testInfo.okToFail());
17249 void JunitReporter::writeSection(std::string const& className,
17250 std::string const& rootName,
17251 SectionNode const& sectionNode,
17252 bool testOkToFail) {
17253 std::string name = trim(sectionNode.stats.sectionInfo.name);
17254 if (!rootName.empty())
17255 name = rootName + '/' + name;
17257 if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() ||
17258 !sectionNode.stdErr.empty()) {
17259 XmlWriter::ScopedElement e = xml.scopedElement("testcase");
17260 if (className.empty()) {
17261 xml.writeAttribute("classname", name);
17262 xml.writeAttribute("name", "root");
17264 xml.writeAttribute("classname", className);
17265 xml.writeAttribute("name", name);
17267 xml.writeAttribute("time", formatDuration(sectionNode.stats.durationInSeconds));
17268 // This is not ideal, but it should be enough to mimic gtest's
17270 // Ideally the JUnit reporter would also handle `skipTest`
17271 // events and write those out appropriately.
17272 xml.writeAttribute("status", "run");
17274 if (sectionNode.stats.assertions.failedButOk) {
17275 xml.scopedElement("skipped").writeAttribute("message",
17276 "TEST_CASE tagged with !mayfail");
17279 writeAssertions(sectionNode);
17281 if (!sectionNode.stdOut.empty())
17282 xml.scopedElement("system-out")
17283 .writeText(trim(sectionNode.stdOut), XmlFormatting::Newline);
17284 if (!sectionNode.stdErr.empty())
17285 xml.scopedElement("system-err")
17286 .writeText(trim(sectionNode.stdErr), XmlFormatting::Newline);
17288 for (auto const& childNode : sectionNode.childSections)
17289 if (className.empty())
17290 writeSection(name, "", *childNode, testOkToFail);
17292 writeSection(className, name, *childNode, testOkToFail);
17295 void JunitReporter::writeAssertions(SectionNode const& sectionNode) {
17296 for (auto const& assertion : sectionNode.assertions)
17297 writeAssertion(assertion);
17300 void JunitReporter::writeAssertion(AssertionStats const& stats) {
17301 AssertionResult const& result = stats.assertionResult;
17302 if (!result.isOk()) {
17303 std::string elementName;
17304 switch (result.getResultType()) {
17305 case ResultWas::ThrewException:
17306 case ResultWas::FatalErrorCondition:
17307 elementName = "error";
17309 case ResultWas::ExplicitFailure:
17310 case ResultWas::ExpressionFailed:
17311 case ResultWas::DidntThrowException:
17312 elementName = "failure";
17315 // We should never see these here:
17316 case ResultWas::Info:
17317 case ResultWas::Warning:
17318 case ResultWas::Ok:
17319 case ResultWas::Unknown:
17320 case ResultWas::FailureBit:
17321 case ResultWas::Exception:
17322 elementName = "internalError";
17326 XmlWriter::ScopedElement e = xml.scopedElement(elementName);
17328 xml.writeAttribute("message", result.getExpression());
17329 xml.writeAttribute("type", result.getTestMacroName());
17331 ReusableStringStream rss;
17332 if (stats.totals.assertions.total() > 0) {
17335 if (result.hasExpression()) {
17337 rss << result.getExpressionInMacro();
17340 if (result.hasExpandedExpression()) {
17341 rss << "with expansion:\n";
17342 rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17348 if (!result.getMessage().empty())
17349 rss << result.getMessage() << '\n';
17350 for (auto const& msg : stats.infoMessages)
17351 if (msg.type == ResultWas::Info)
17352 rss << msg.message << '\n';
17354 rss << "at " << result.getSourceInfo();
17355 xml.writeText(rss.str(), XmlFormatting::Newline);
17359 CATCH_REGISTER_REPORTER("junit", JunitReporter)
17361 } // end namespace Catch
17362 // end catch_reporter_junit.cpp
17363 // start catch_reporter_listening.cpp
17369 ListeningReporter::ListeningReporter() {
17370 // We will assume that listeners will always want all assertions
17371 m_preferences.shouldReportAllAssertions = true;
17374 void ListeningReporter::addListener(IStreamingReporterPtr&& listener) {
17375 m_listeners.push_back(std::move(listener));
17378 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17379 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17380 m_reporter = std::move(reporter);
17381 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17384 ReporterPreferences ListeningReporter::getPreferences() const { return m_preferences; }
17386 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17387 return std::set<Verbosity>{};
17390 void ListeningReporter::noMatchingTestCases(std::string const& spec) {
17391 for (auto const& listener : m_listeners) {
17392 listener->noMatchingTestCases(spec);
17394 m_reporter->noMatchingTestCases(spec);
17397 void ListeningReporter::reportInvalidArguments(std::string const& arg) {
17398 for (auto const& listener : m_listeners) {
17399 listener->reportInvalidArguments(arg);
17401 m_reporter->reportInvalidArguments(arg);
17404 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17405 void ListeningReporter::benchmarkPreparing(std::string const& name) {
17406 for (auto const& listener : m_listeners) {
17407 listener->benchmarkPreparing(name);
17409 m_reporter->benchmarkPreparing(name);
17411 void ListeningReporter::benchmarkStarting(BenchmarkInfo const& benchmarkInfo) {
17412 for (auto const& listener : m_listeners) {
17413 listener->benchmarkStarting(benchmarkInfo);
17415 m_reporter->benchmarkStarting(benchmarkInfo);
17417 void ListeningReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17418 for (auto const& listener : m_listeners) {
17419 listener->benchmarkEnded(benchmarkStats);
17421 m_reporter->benchmarkEnded(benchmarkStats);
17424 void ListeningReporter::benchmarkFailed(std::string const& error) {
17425 for (auto const& listener : m_listeners) {
17426 listener->benchmarkFailed(error);
17428 m_reporter->benchmarkFailed(error);
17430 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17432 void ListeningReporter::testRunStarting(TestRunInfo const& testRunInfo) {
17433 for (auto const& listener : m_listeners) {
17434 listener->testRunStarting(testRunInfo);
17436 m_reporter->testRunStarting(testRunInfo);
17439 void ListeningReporter::testGroupStarting(GroupInfo const& groupInfo) {
17440 for (auto const& listener : m_listeners) {
17441 listener->testGroupStarting(groupInfo);
17443 m_reporter->testGroupStarting(groupInfo);
17446 void ListeningReporter::testCaseStarting(TestCaseInfo const& testInfo) {
17447 for (auto const& listener : m_listeners) {
17448 listener->testCaseStarting(testInfo);
17450 m_reporter->testCaseStarting(testInfo);
17453 void ListeningReporter::sectionStarting(SectionInfo const& sectionInfo) {
17454 for (auto const& listener : m_listeners) {
17455 listener->sectionStarting(sectionInfo);
17457 m_reporter->sectionStarting(sectionInfo);
17460 void ListeningReporter::assertionStarting(AssertionInfo const& assertionInfo) {
17461 for (auto const& listener : m_listeners) {
17462 listener->assertionStarting(assertionInfo);
17464 m_reporter->assertionStarting(assertionInfo);
17467 // The return value indicates if the messages buffer should be cleared:
17468 bool ListeningReporter::assertionEnded(AssertionStats const& assertionStats) {
17469 for (auto const& listener : m_listeners) {
17470 static_cast<void>(listener->assertionEnded(assertionStats));
17472 return m_reporter->assertionEnded(assertionStats);
17475 void ListeningReporter::sectionEnded(SectionStats const& sectionStats) {
17476 for (auto const& listener : m_listeners) {
17477 listener->sectionEnded(sectionStats);
17479 m_reporter->sectionEnded(sectionStats);
17482 void ListeningReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17483 for (auto const& listener : m_listeners) {
17484 listener->testCaseEnded(testCaseStats);
17486 m_reporter->testCaseEnded(testCaseStats);
17489 void ListeningReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17490 for (auto const& listener : m_listeners) {
17491 listener->testGroupEnded(testGroupStats);
17493 m_reporter->testGroupEnded(testGroupStats);
17496 void ListeningReporter::testRunEnded(TestRunStats const& testRunStats) {
17497 for (auto const& listener : m_listeners) {
17498 listener->testRunEnded(testRunStats);
17500 m_reporter->testRunEnded(testRunStats);
17503 void ListeningReporter::skipTest(TestCaseInfo const& testInfo) {
17504 for (auto const& listener : m_listeners) {
17505 listener->skipTest(testInfo);
17507 m_reporter->skipTest(testInfo);
17510 bool ListeningReporter::isMulti() const { return true; }
17512 } // end namespace Catch
17513 // end catch_reporter_listening.cpp
17514 // start catch_reporter_xml.cpp
17516 #if defined(_MSC_VER)
17517 #pragma warning(push)
17518 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in
17519 // switch Note that 4062 (not all labels are
17520 // handled and default is missing) is enabled
17524 XmlReporter::XmlReporter(ReporterConfig const& _config) :
17525 StreamingReporterBase(_config), m_xml(_config.stream()) {
17526 m_reporterPrefs.shouldRedirectStdOut = true;
17527 m_reporterPrefs.shouldReportAllAssertions = true;
17530 XmlReporter::~XmlReporter() = default;
17532 std::string XmlReporter::getDescription() { return "Reports test results as an XML document"; }
17534 std::string XmlReporter::getStylesheetRef() const { return std::string(); }
17536 void XmlReporter::writeSourceInfo(SourceLineInfo const& sourceInfo) {
17537 m_xml.writeAttribute("filename", sourceInfo.file).writeAttribute("line", sourceInfo.line);
17540 void XmlReporter::noMatchingTestCases(std::string const& s) {
17541 StreamingReporterBase::noMatchingTestCases(s);
17544 void XmlReporter::testRunStarting(TestRunInfo const& testInfo) {
17545 StreamingReporterBase::testRunStarting(testInfo);
17546 std::string stylesheetRef = getStylesheetRef();
17547 if (!stylesheetRef.empty())
17548 m_xml.writeStylesheetRef(stylesheetRef);
17549 m_xml.startElement("Catch");
17550 if (!m_config->name().empty())
17551 m_xml.writeAttribute("name", m_config->name());
17552 if (m_config->testSpec().hasFilters())
17553 m_xml.writeAttribute("filters", serializeFilters(m_config->getTestsOrTags()));
17554 if (m_config->rngSeed() != 0)
17555 m_xml.scopedElement("Randomness").writeAttribute("seed", m_config->rngSeed());
17558 void XmlReporter::testGroupStarting(GroupInfo const& groupInfo) {
17559 StreamingReporterBase::testGroupStarting(groupInfo);
17560 m_xml.startElement("Group").writeAttribute("name", groupInfo.name);
17563 void XmlReporter::testCaseStarting(TestCaseInfo const& testInfo) {
17564 StreamingReporterBase::testCaseStarting(testInfo);
17565 m_xml.startElement("TestCase")
17566 .writeAttribute("name", trim(testInfo.name))
17567 .writeAttribute("description", testInfo.description)
17568 .writeAttribute("tags", testInfo.tagsAsString());
17570 writeSourceInfo(testInfo.lineInfo);
17572 if (m_config->showDurations() == ShowDurations::Always)
17573 m_testCaseTimer.start();
17574 m_xml.ensureTagClosed();
17577 void XmlReporter::sectionStarting(SectionInfo const& sectionInfo) {
17578 StreamingReporterBase::sectionStarting(sectionInfo);
17579 if (m_sectionDepth++ > 0) {
17580 m_xml.startElement("Section").writeAttribute("name", trim(sectionInfo.name));
17581 writeSourceInfo(sectionInfo.lineInfo);
17582 m_xml.ensureTagClosed();
17586 void XmlReporter::assertionStarting(AssertionInfo const&) {}
17588 bool XmlReporter::assertionEnded(AssertionStats const& assertionStats) {
17590 AssertionResult const& result = assertionStats.assertionResult;
17592 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17594 if (includeResults || result.getResultType() == ResultWas::Warning) {
17595 // Print any info messages in <Info> tags.
17596 for (auto const& msg : assertionStats.infoMessages) {
17597 if (msg.type == ResultWas::Info && includeResults) {
17598 m_xml.scopedElement("Info").writeText(msg.message);
17599 } else if (msg.type == ResultWas::Warning) {
17600 m_xml.scopedElement("Warning").writeText(msg.message);
17605 // Drop out if result was successful but we're not printing them.
17606 if (!includeResults && result.getResultType() != ResultWas::Warning)
17609 // Print the expression if there is one.
17610 if (result.hasExpression()) {
17611 m_xml.startElement("Expression")
17612 .writeAttribute("success", result.succeeded())
17613 .writeAttribute("type", result.getTestMacroName());
17615 writeSourceInfo(result.getSourceInfo());
17617 m_xml.scopedElement("Original").writeText(result.getExpression());
17618 m_xml.scopedElement("Expanded").writeText(result.getExpandedExpression());
17621 // And... Print a result applicable to each result type.
17622 switch (result.getResultType()) {
17623 case ResultWas::ThrewException:
17624 m_xml.startElement("Exception");
17625 writeSourceInfo(result.getSourceInfo());
17626 m_xml.writeText(result.getMessage());
17627 m_xml.endElement();
17629 case ResultWas::FatalErrorCondition:
17630 m_xml.startElement("FatalErrorCondition");
17631 writeSourceInfo(result.getSourceInfo());
17632 m_xml.writeText(result.getMessage());
17633 m_xml.endElement();
17635 case ResultWas::Info:
17636 m_xml.scopedElement("Info").writeText(result.getMessage());
17638 case ResultWas::Warning:
17639 // Warning will already have been written
17641 case ResultWas::ExplicitFailure:
17642 m_xml.startElement("Failure");
17643 writeSourceInfo(result.getSourceInfo());
17644 m_xml.writeText(result.getMessage());
17645 m_xml.endElement();
17651 if (result.hasExpression())
17652 m_xml.endElement();
17657 void XmlReporter::sectionEnded(SectionStats const& sectionStats) {
17658 StreamingReporterBase::sectionEnded(sectionStats);
17659 if (--m_sectionDepth > 0) {
17660 XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults");
17661 e.writeAttribute("successes", sectionStats.assertions.passed);
17662 e.writeAttribute("failures", sectionStats.assertions.failed);
17663 e.writeAttribute("expectedFailures", sectionStats.assertions.failedButOk);
17665 if (m_config->showDurations() == ShowDurations::Always)
17666 e.writeAttribute("durationInSeconds", sectionStats.durationInSeconds);
17668 m_xml.endElement();
17672 void XmlReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17673 StreamingReporterBase::testCaseEnded(testCaseStats);
17674 XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult");
17675 e.writeAttribute("success", testCaseStats.totals.assertions.allOk());
17677 if (m_config->showDurations() == ShowDurations::Always)
17678 e.writeAttribute("durationInSeconds", m_testCaseTimer.getElapsedSeconds());
17680 if (!testCaseStats.stdOut.empty())
17681 m_xml.scopedElement("StdOut").writeText(trim(testCaseStats.stdOut),
17682 XmlFormatting::Newline);
17683 if (!testCaseStats.stdErr.empty())
17684 m_xml.scopedElement("StdErr").writeText(trim(testCaseStats.stdErr),
17685 XmlFormatting::Newline);
17687 m_xml.endElement();
17690 void XmlReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17691 StreamingReporterBase::testGroupEnded(testGroupStats);
17692 // TODO: Check testGroupStats.aborting and act accordingly.
17693 m_xml.scopedElement("OverallResults")
17694 .writeAttribute("successes", testGroupStats.totals.assertions.passed)
17695 .writeAttribute("failures", testGroupStats.totals.assertions.failed)
17696 .writeAttribute("expectedFailures", testGroupStats.totals.assertions.failedButOk);
17697 m_xml.scopedElement("OverallResultsCases")
17698 .writeAttribute("successes", testGroupStats.totals.testCases.passed)
17699 .writeAttribute("failures", testGroupStats.totals.testCases.failed)
17700 .writeAttribute("expectedFailures", testGroupStats.totals.testCases.failedButOk);
17701 m_xml.endElement();
17704 void XmlReporter::testRunEnded(TestRunStats const& testRunStats) {
17705 StreamingReporterBase::testRunEnded(testRunStats);
17706 m_xml.scopedElement("OverallResults")
17707 .writeAttribute("successes", testRunStats.totals.assertions.passed)
17708 .writeAttribute("failures", testRunStats.totals.assertions.failed)
17709 .writeAttribute("expectedFailures", testRunStats.totals.assertions.failedButOk);
17710 m_xml.scopedElement("OverallResultsCases")
17711 .writeAttribute("successes", testRunStats.totals.testCases.passed)
17712 .writeAttribute("failures", testRunStats.totals.testCases.failed)
17713 .writeAttribute("expectedFailures", testRunStats.totals.testCases.failedButOk);
17714 m_xml.endElement();
17717 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17718 void XmlReporter::benchmarkPreparing(std::string const& name) {
17719 m_xml.startElement("BenchmarkResults").writeAttribute("name", name);
17722 void XmlReporter::benchmarkStarting(BenchmarkInfo const& info) {
17723 m_xml.writeAttribute("samples", info.samples)
17724 .writeAttribute("resamples", info.resamples)
17725 .writeAttribute("iterations", info.iterations)
17726 .writeAttribute("clockResolution", info.clockResolution)
17727 .writeAttribute("estimatedDuration", info.estimatedDuration)
17728 .writeComment("All values in nano seconds");
17731 void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17732 m_xml.startElement("mean")
17733 .writeAttribute("value", benchmarkStats.mean.point.count())
17734 .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17735 .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17736 .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17737 m_xml.endElement();
17738 m_xml.startElement("standardDeviation")
17739 .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17740 .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17741 .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17742 .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17743 m_xml.endElement();
17744 m_xml.startElement("outliers")
17745 .writeAttribute("variance", benchmarkStats.outlierVariance)
17746 .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17747 .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17748 .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17749 .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17750 m_xml.endElement();
17751 m_xml.endElement();
17754 void XmlReporter::benchmarkFailed(std::string const& error) {
17755 m_xml.scopedElement("failed").writeAttribute("message", error);
17756 m_xml.endElement();
17758 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17760 CATCH_REGISTER_REPORTER("xml", XmlReporter)
17762 } // end namespace Catch
17764 #if defined(_MSC_VER)
17765 #pragma warning(pop)
17767 // end catch_reporter_xml.cpp
17770 LeakDetector leakDetector;
17774 #pragma clang diagnostic pop
17777 // end catch_impl.hpp
17780 #ifdef CATCH_CONFIG_MAIN
17781 // start catch_default_main.hpp
17785 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && \
17786 !defined(DO_NOT_USE_WMAIN)
17787 // Standard C/C++ Win32 Unicode wmain entry point
17788 extern "C" int wmain(int argc, wchar_t* argv[], wchar_t*[]) {
17790 // Standard C/C++ main entry point
17791 int main(int argc, char* argv[]) {
17794 return Catch::Session().run(argc, argv);
17799 // Objective-C entry point
17800 int main(int argc, char* const argv[]) {
17801 #if !CATCH_ARC_ENABLED
17802 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
17805 Catch::registerTestMethods();
17806 int result = Catch::Session().run(argc, (char**)argv);
17808 #if !CATCH_ARC_ENABLED
17817 // end catch_default_main.hpp
17820 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17822 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17823 #undef CLARA_CONFIG_MAIN
17826 #if !defined(CATCH_CONFIG_DISABLE)
17828 // If this config identifier is defined then all CATCH macros are prefixed with
17830 #ifdef CATCH_CONFIG_PREFIX_ALL
17832 #define CATCH_REQUIRE(...) \
17833 INTERNAL_CATCH_TEST("CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
17834 #define CATCH_REQUIRE_FALSE(...) \
17835 INTERNAL_CATCH_TEST("CATCH_REQUIRE_FALSE", \
17836 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
17839 #define CATCH_REQUIRE_THROWS(...) \
17840 INTERNAL_CATCH_THROWS("CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
17841 #define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) \
17842 INTERNAL_CATCH_THROWS_AS( \
17843 "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr)
17844 #define CATCH_REQUIRE_THROWS_WITH(expr, matcher) \
17845 INTERNAL_CATCH_THROWS_STR_MATCHES( \
17846 "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr)
17847 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17848 #define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
17849 INTERNAL_CATCH_THROWS_MATCHES("CATCH_REQUIRE_THROWS_MATCHES", \
17851 Catch::ResultDisposition::Normal, \
17854 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17855 #define CATCH_REQUIRE_NOTHROW(...) \
17856 INTERNAL_CATCH_NO_THROW("CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
17858 #define CATCH_CHECK(...) \
17859 INTERNAL_CATCH_TEST("CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17860 #define CATCH_CHECK_FALSE(...) \
17861 INTERNAL_CATCH_TEST("CATCH_CHECK_FALSE", \
17862 Catch::ResultDisposition::ContinueOnFailure | \
17863 Catch::ResultDisposition::FalseTest, \
17865 #define CATCH_CHECKED_IF(...) \
17866 INTERNAL_CATCH_IF("CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17867 #define CATCH_CHECKED_ELSE(...) \
17868 INTERNAL_CATCH_ELSE( \
17869 "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17870 #define CATCH_CHECK_NOFAIL(...) \
17871 INTERNAL_CATCH_TEST("CATCH_CHECK_NOFAIL", \
17872 Catch::ResultDisposition::ContinueOnFailure | \
17873 Catch::ResultDisposition::SuppressFail, \
17876 #define CATCH_CHECK_THROWS(...) \
17877 INTERNAL_CATCH_THROWS( \
17878 "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17879 #define CATCH_CHECK_THROWS_AS(expr, exceptionType) \
17880 INTERNAL_CATCH_THROWS_AS( \
17881 "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr)
17882 #define CATCH_CHECK_THROWS_WITH(expr, matcher) \
17883 INTERNAL_CATCH_THROWS_STR_MATCHES( \
17884 "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17885 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17886 #define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
17887 INTERNAL_CATCH_THROWS_MATCHES("CATCH_CHECK_THROWS_MATCHES", \
17889 Catch::ResultDisposition::ContinueOnFailure, \
17892 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17893 #define CATCH_CHECK_NOTHROW(...) \
17894 INTERNAL_CATCH_NO_THROW( \
17895 "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17897 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17898 #define CATCH_CHECK_THAT(arg, matcher) \
17899 INTERNAL_CHECK_THAT( \
17900 "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
17902 #define CATCH_REQUIRE_THAT(arg, matcher) \
17903 INTERNAL_CHECK_THAT("CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
17904 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17906 #define CATCH_INFO(msg) INTERNAL_CATCH_INFO("CATCH_INFO", msg)
17907 #define CATCH_UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("CATCH_UNSCOPED_INFO", msg)
17908 #define CATCH_WARN(msg) \
17909 INTERNAL_CATCH_MSG( \
17910 "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg)
17911 #define CATCH_CAPTURE(...) \
17912 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__)
17914 #define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
17915 #define CATCH_TEST_CASE_METHOD(className, ...) \
17916 INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
17917 #define CATCH_METHOD_AS_TEST_CASE(method, ...) \
17918 INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
17919 #define CATCH_REGISTER_TEST_CASE(Function, ...) \
17920 INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
17921 #define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
17922 #define CATCH_DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
17923 #define CATCH_FAIL(...) \
17924 INTERNAL_CATCH_MSG("CATCH_FAIL", \
17925 Catch::ResultWas::ExplicitFailure, \
17926 Catch::ResultDisposition::Normal, \
17928 #define CATCH_FAIL_CHECK(...) \
17929 INTERNAL_CATCH_MSG("CATCH_FAIL_CHECK", \
17930 Catch::ResultWas::ExplicitFailure, \
17931 Catch::ResultDisposition::ContinueOnFailure, \
17933 #define CATCH_SUCCEED(...) \
17934 INTERNAL_CATCH_MSG("CATCH_SUCCEED", \
17935 Catch::ResultWas::Ok, \
17936 Catch::ResultDisposition::ContinueOnFailure, \
17939 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17941 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17942 #define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17943 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
17944 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17945 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17946 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17947 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17948 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
17949 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17950 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
17951 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17952 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
17953 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17954 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17956 #define CATCH_TEMPLATE_TEST_CASE(...) \
17957 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
17958 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17959 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
17960 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17961 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
17962 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17963 INTERNAL_CATCH_EXPAND_VARGS( \
17964 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17965 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \
17966 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
17967 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17968 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
17969 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17970 INTERNAL_CATCH_EXPAND_VARGS( \
17971 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
17972 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17973 INTERNAL_CATCH_EXPAND_VARGS( \
17974 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17977 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17978 #define CATCH_STATIC_REQUIRE(...) \
17979 static_assert(__VA_ARGS__, #__VA_ARGS__); \
17980 CATCH_SUCCEED(#__VA_ARGS__)
17981 #define CATCH_STATIC_REQUIRE_FALSE(...) \
17982 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
17983 CATCH_SUCCEED(#__VA_ARGS__)
17985 #define CATCH_STATIC_REQUIRE(...) CATCH_REQUIRE(__VA_ARGS__)
17986 #define CATCH_STATIC_REQUIRE_FALSE(...) CATCH_REQUIRE_FALSE(__VA_ARGS__)
17989 // "BDD-style" convenience wrappers
17990 #define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__)
17991 #define CATCH_SCENARIO_METHOD(className, ...) \
17992 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
17993 #define CATCH_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
17994 #define CATCH_AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
17995 #define CATCH_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
17996 #define CATCH_AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
17997 #define CATCH_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
17998 #define CATCH_AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
18000 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18001 #define CATCH_BENCHMARK(...) \
18002 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18003 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
18004 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
18005 #define CATCH_BENCHMARK_ADVANCED(name) \
18006 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18008 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18010 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not
18014 #define REQUIRE(...) INTERNAL_CATCH_TEST("REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
18015 #define REQUIRE_FALSE(...) \
18016 INTERNAL_CATCH_TEST("REQUIRE_FALSE", \
18017 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
18020 #define REQUIRE_THROWS(...) \
18021 INTERNAL_CATCH_THROWS("REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
18022 #define REQUIRE_THROWS_AS(expr, exceptionType) \
18023 INTERNAL_CATCH_THROWS_AS( \
18024 "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr)
18025 #define REQUIRE_THROWS_WITH(expr, matcher) \
18026 INTERNAL_CATCH_THROWS_STR_MATCHES( \
18027 "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr)
18028 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18029 #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
18030 INTERNAL_CATCH_THROWS_MATCHES( \
18031 "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr)
18032 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18033 #define REQUIRE_NOTHROW(...) \
18034 INTERNAL_CATCH_NO_THROW("REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
18036 #define CHECK(...) \
18037 INTERNAL_CATCH_TEST("CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18038 #define CHECK_FALSE(...) \
18039 INTERNAL_CATCH_TEST("CHECK_FALSE", \
18040 Catch::ResultDisposition::ContinueOnFailure | \
18041 Catch::ResultDisposition::FalseTest, \
18043 #define CHECKED_IF(...) \
18044 INTERNAL_CATCH_IF("CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18045 #define CHECKED_ELSE(...) \
18046 INTERNAL_CATCH_ELSE("CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18047 #define CHECK_NOFAIL(...) \
18048 INTERNAL_CATCH_TEST("CHECK_NOFAIL", \
18049 Catch::ResultDisposition::ContinueOnFailure | \
18050 Catch::ResultDisposition::SuppressFail, \
18053 #define CHECK_THROWS(...) \
18054 INTERNAL_CATCH_THROWS("CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18055 #define CHECK_THROWS_AS(expr, exceptionType) \
18056 INTERNAL_CATCH_THROWS_AS( \
18057 "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr)
18058 #define CHECK_THROWS_WITH(expr, matcher) \
18059 INTERNAL_CATCH_THROWS_STR_MATCHES( \
18060 "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
18061 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18062 #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
18063 INTERNAL_CATCH_THROWS_MATCHES("CHECK_THROWS_MATCHES", \
18065 Catch::ResultDisposition::ContinueOnFailure, \
18068 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18069 #define CHECK_NOTHROW(...) \
18070 INTERNAL_CATCH_NO_THROW( \
18071 "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18073 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18074 #define CHECK_THAT(arg, matcher) \
18075 INTERNAL_CHECK_THAT("CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
18077 #define REQUIRE_THAT(arg, matcher) \
18078 INTERNAL_CHECK_THAT("REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
18079 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18081 #define INFO(msg) INTERNAL_CATCH_INFO("INFO", msg)
18082 #define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("UNSCOPED_INFO", msg)
18083 #define WARN(msg) \
18084 INTERNAL_CATCH_MSG( \
18085 "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg)
18086 #define CAPTURE(...) \
18087 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__)
18089 #define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
18090 #define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
18091 #define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
18092 #define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
18093 #define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
18094 #define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
18095 #define FAIL(...) \
18096 INTERNAL_CATCH_MSG( \
18097 "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__)
18098 #define FAIL_CHECK(...) \
18099 INTERNAL_CATCH_MSG("FAIL_CHECK", \
18100 Catch::ResultWas::ExplicitFailure, \
18101 Catch::ResultDisposition::ContinueOnFailure, \
18103 #define SUCCEED(...) \
18104 INTERNAL_CATCH_MSG( \
18105 "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18106 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
18108 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18109 #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18110 #define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
18111 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18112 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18113 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18114 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18115 #define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
18116 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
18117 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
18118 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18119 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
18120 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18121 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18122 #define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
18123 #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
18124 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__)
18126 #define TEMPLATE_TEST_CASE(...) \
18127 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
18128 #define TEMPLATE_TEST_CASE_SIG(...) \
18129 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
18130 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18131 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
18132 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18133 INTERNAL_CATCH_EXPAND_VARGS( \
18134 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18135 #define TEMPLATE_PRODUCT_TEST_CASE(...) \
18136 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
18137 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
18138 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
18139 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18140 INTERNAL_CATCH_EXPAND_VARGS( \
18141 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
18142 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18143 INTERNAL_CATCH_EXPAND_VARGS( \
18144 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18145 #define TEMPLATE_LIST_TEST_CASE(...) \
18146 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__))
18147 #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
18148 INTERNAL_CATCH_EXPAND_VARGS( \
18149 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__))
18152 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
18153 #define STATIC_REQUIRE(...) \
18154 static_assert(__VA_ARGS__, #__VA_ARGS__); \
18155 SUCCEED(#__VA_ARGS__)
18156 #define STATIC_REQUIRE_FALSE(...) \
18157 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
18158 SUCCEED("!(" #__VA_ARGS__ ")")
18160 #define STATIC_REQUIRE(...) REQUIRE(__VA_ARGS__)
18161 #define STATIC_REQUIRE_FALSE(...) REQUIRE_FALSE(__VA_ARGS__)
18166 #define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature)
18168 // "BDD-style" convenience wrappers
18169 #define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__)
18170 #define SCENARIO_METHOD(className, ...) \
18171 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
18173 #define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
18174 #define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
18175 #define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
18176 #define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
18177 #define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
18178 #define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
18180 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18181 #define BENCHMARK(...) \
18182 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18183 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
18184 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
18185 #define BENCHMARK_ADVANCED(name) \
18186 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18188 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18190 using Catch::Detail::Approx;
18192 #else // CATCH_CONFIG_DISABLE
18195 // If this config identifier is defined then all CATCH macros are prefixed with
18197 #ifdef CATCH_CONFIG_PREFIX_ALL
18199 #define CATCH_REQUIRE(...) (void)(0)
18200 #define CATCH_REQUIRE_FALSE(...) (void)(0)
18202 #define CATCH_REQUIRE_THROWS(...) (void)(0)
18203 #define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
18204 #define CATCH_REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
18205 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18206 #define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18207 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18208 #define CATCH_REQUIRE_NOTHROW(...) (void)(0)
18210 #define CATCH_CHECK(...) (void)(0)
18211 #define CATCH_CHECK_FALSE(...) (void)(0)
18212 #define CATCH_CHECKED_IF(...) if (__VA_ARGS__)
18213 #define CATCH_CHECKED_ELSE(...) if (!(__VA_ARGS__))
18214 #define CATCH_CHECK_NOFAIL(...) (void)(0)
18216 #define CATCH_CHECK_THROWS(...) (void)(0)
18217 #define CATCH_CHECK_THROWS_AS(expr, exceptionType) (void)(0)
18218 #define CATCH_CHECK_THROWS_WITH(expr, matcher) (void)(0)
18219 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18220 #define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18221 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18222 #define CATCH_CHECK_NOTHROW(...) (void)(0)
18224 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18225 #define CATCH_CHECK_THAT(arg, matcher) (void)(0)
18227 #define CATCH_REQUIRE_THAT(arg, matcher) (void)(0)
18228 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18230 #define CATCH_INFO(msg) (void)(0)
18231 #define CATCH_UNSCOPED_INFO(msg) (void)(0)
18232 #define CATCH_WARN(msg) (void)(0)
18233 #define CATCH_CAPTURE(msg) (void)(0)
18235 #define CATCH_TEST_CASE(...) \
18236 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18237 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18238 #define CATCH_TEST_CASE_METHOD(className, ...) \
18239 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18240 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18241 #define CATCH_METHOD_AS_TEST_CASE(method, ...)
18242 #define CATCH_REGISTER_TEST_CASE(Function, ...) (void)(0)
18243 #define CATCH_SECTION(...)
18244 #define CATCH_DYNAMIC_SECTION(...)
18245 #define CATCH_FAIL(...) (void)(0)
18246 #define CATCH_FAIL_CHECK(...) (void)(0)
18247 #define CATCH_SUCCEED(...) (void)(0)
18249 #define CATCH_ANON_TEST_CASE() \
18250 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18251 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18253 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18254 #define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18255 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
18256 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18257 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
18258 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18259 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18260 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18261 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18262 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18263 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18264 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18265 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18266 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18268 #define CATCH_TEMPLATE_TEST_CASE(...) \
18269 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18270 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
18271 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18272 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
18273 INTERNAL_CATCH_EXPAND_VARGS( \
18274 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18275 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18276 INTERNAL_CATCH_EXPAND_VARGS( \
18277 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18278 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18279 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18280 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18281 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18282 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18283 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18286 // "BDD-style" convenience wrappers
18287 #define CATCH_SCENARIO(...) \
18288 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18289 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18290 #define CATCH_SCENARIO_METHOD(className, ...) \
18291 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \
18292 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className)
18293 #define CATCH_GIVEN(desc)
18294 #define CATCH_AND_GIVEN(desc)
18295 #define CATCH_WHEN(desc)
18296 #define CATCH_AND_WHEN(desc)
18297 #define CATCH_THEN(desc)
18298 #define CATCH_AND_THEN(desc)
18300 #define CATCH_STATIC_REQUIRE(...) (void)(0)
18301 #define CATCH_STATIC_REQUIRE_FALSE(...) (void)(0)
18303 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not
18307 #define REQUIRE(...) (void)(0)
18308 #define REQUIRE_FALSE(...) (void)(0)
18310 #define REQUIRE_THROWS(...) (void)(0)
18311 #define REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
18312 #define REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
18313 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18314 #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18315 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18316 #define REQUIRE_NOTHROW(...) (void)(0)
18318 #define CHECK(...) (void)(0)
18319 #define CHECK_FALSE(...) (void)(0)
18320 #define CHECKED_IF(...) if (__VA_ARGS__)
18321 #define CHECKED_ELSE(...) if (!(__VA_ARGS__))
18322 #define CHECK_NOFAIL(...) (void)(0)
18324 #define CHECK_THROWS(...) (void)(0)
18325 #define CHECK_THROWS_AS(expr, exceptionType) (void)(0)
18326 #define CHECK_THROWS_WITH(expr, matcher) (void)(0)
18327 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18328 #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18329 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18330 #define CHECK_NOTHROW(...) (void)(0)
18332 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18333 #define CHECK_THAT(arg, matcher) (void)(0)
18335 #define REQUIRE_THAT(arg, matcher) (void)(0)
18336 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18338 #define INFO(msg) (void)(0)
18339 #define UNSCOPED_INFO(msg) (void)(0)
18340 #define WARN(msg) (void)(0)
18341 #define CAPTURE(msg) (void)(0)
18343 #define TEST_CASE(...) \
18344 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18345 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18346 #define TEST_CASE_METHOD(className, ...) \
18347 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18348 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18349 #define METHOD_AS_TEST_CASE(method, ...)
18350 #define REGISTER_TEST_CASE(Function, ...) (void)(0)
18351 #define SECTION(...)
18352 #define DYNAMIC_SECTION(...)
18353 #define FAIL(...) (void)(0)
18354 #define FAIL_CHECK(...) (void)(0)
18355 #define SUCCEED(...) (void)(0)
18356 #define ANON_TEST_CASE() \
18357 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18358 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18360 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18361 #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18362 #define TEMPLATE_TEST_CASE_SIG(...) \
18363 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18364 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18365 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18366 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18367 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18368 #define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18369 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18370 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18371 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18372 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18373 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18375 #define TEMPLATE_TEST_CASE(...) \
18376 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18377 #define TEMPLATE_TEST_CASE_SIG(...) \
18378 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18379 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18380 INTERNAL_CATCH_EXPAND_VARGS( \
18381 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18382 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18383 INTERNAL_CATCH_EXPAND_VARGS( \
18384 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18385 #define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18386 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18387 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18388 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18389 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18390 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18393 #define STATIC_REQUIRE(...) (void)(0)
18394 #define STATIC_REQUIRE_FALSE(...) (void)(0)
18398 #define CATCH_TRANSLATE_EXCEPTION(signature) \
18399 INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( \
18400 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
18402 // "BDD-style" convenience wrappers
18403 #define SCENARIO(...) \
18404 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \
18405 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18406 #define SCENARIO_METHOD(className, ...) \
18407 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \
18408 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className)
18410 #define GIVEN(desc)
18411 #define AND_GIVEN(desc)
18413 #define AND_WHEN(desc)
18415 #define AND_THEN(desc)
18417 using Catch::Detail::Approx;
18421 #endif // ! CATCH_CONFIG_IMPL_ONLY
18423 // start catch_reenable_warnings.h
18426 #ifdef __ICC // icpc defines the __clang__ macro
18427 #pragma warning(pop)
18429 #pragma clang diagnostic pop
18431 #elif defined __GNUC__
18432 #pragma GCC diagnostic pop
18435 // end catch_reenable_warnings.h
18437 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED