3 * Generated: 2021-04-16 18:23:38.044268
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it directly
6 * 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
16 #define CATCH_VERSION_MAJOR 2
17 #define CATCH_VERSION_MINOR 13
18 #define CATCH_VERSION_PATCH 6
21 # pragma clang system_header
22 #elif defined __GNUC__
23 # pragma GCC system_header
26 // start catch_suppress_warnings.h
29 # ifdef __ICC // icpc defines the __clang__ macro
30 # pragma warning(push)
31 # pragma warning(disable: 161 1682)
33 # pragma clang diagnostic push
34 # pragma clang diagnostic ignored "-Wpadded"
35 # pragma clang diagnostic ignored "-Wswitch-enum"
36 # pragma clang diagnostic ignored "-Wcovered-switch-default"
38 #elif defined __GNUC__
39 // Because REQUIREs trigger GCC's -Wparentheses, and because still
40 // supported version of g++ have only buggy support for _Pragmas,
41 // Wparentheses have to be suppressed globally.
42 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
44 # pragma GCC diagnostic push
45 # pragma GCC diagnostic ignored "-Wunused-variable"
46 # pragma GCC diagnostic ignored "-Wpadded"
48 // end catch_suppress_warnings.h
49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
51 # define CATCH_CONFIG_ALL_PARTS
54 // In the impl file, we want to have access to all parts of the headers
55 // Can also be used to sanely support PCHs
56 #if defined(CATCH_CONFIG_ALL_PARTS)
57 # define CATCH_CONFIG_EXTERNAL_INTERFACES
58 # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
59 # undef CATCH_CONFIG_DISABLE_MATCHERS
61 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
62 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
66 #if !defined(CATCH_CONFIG_IMPL_ONLY)
67 // start catch_platform.h
70 // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
72 # include <TargetConditionals.h>
73 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
74 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
75 # define CATCH_PLATFORM_MAC
76 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
77 # define CATCH_PLATFORM_IPHONE
80 #elif defined(linux) || defined(__linux) || defined(__linux__)
81 # define CATCH_PLATFORM_LINUX
83 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
84 # define CATCH_PLATFORM_WINDOWS
87 // end catch_platform.h
90 # ifndef CLARA_CONFIG_MAIN
91 # define CLARA_CONFIG_MAIN_NOT_DEFINED
92 # define CLARA_CONFIG_MAIN
96 // start catch_user_interfaces.h
99 unsigned int rngSeed();
102 // end catch_user_interfaces.h
103 // start catch_tag_alias_autoregistrar.h
105 // start catch_common.h
107 // start catch_compiler_capabilities.h
109 // Detect a number of compiler features - by compiler
110 // The following features are defined:
112 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
113 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
114 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
115 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
117 // Note to maintainers: if new toggles are added please document them
118 // in configuration.md, too
121 // In general each macro has a _NO_<feature name> form
122 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
123 // Many features, at point of detection, define an _INTERNAL_ macro, so they
124 // can be combined, en-mass, with the _NO_ forms later.
128 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
129 # define CATCH_CPP14_OR_GREATER
132 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
133 # define CATCH_CPP17_OR_GREATER
138 // Only GCC compiler should be used in this block, so other compilers trying to
139 // mask themselves as GCC should be ignored.
140 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
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(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
168 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
169 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
170 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
172 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
173 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
175 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
176 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
178 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
179 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
181 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
182 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
186 ////////////////////////////////////////////////////////////////////////////////
187 // Assume that non-Windows platforms support posix signals by default
188 #if !defined(CATCH_PLATFORM_WINDOWS)
189 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
192 ////////////////////////////////////////////////////////////////////////////////
193 // We know some environments not to support full POSIX signals
194 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
195 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
199 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
200 # define CATCH_CONFIG_COLOUR_NONE
203 ////////////////////////////////////////////////////////////////////////////////
204 // Android somehow still does not support std::to_string
205 #if defined(__ANDROID__)
206 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
207 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
210 ////////////////////////////////////////////////////////////////////////////////
211 // Not all Windows environments support SEH properly
212 #if defined(__MINGW32__)
213 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
216 ////////////////////////////////////////////////////////////////////////////////
218 #if defined(__ORBIS__)
219 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
222 ////////////////////////////////////////////////////////////////////////////////
226 // Required for some versions of Cygwin to declare gettimeofday
227 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
229 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
230 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
231 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
232 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
234 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
239 ////////////////////////////////////////////////////////////////////////////////
241 #if defined(_MSC_VER)
243 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
244 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
246 // Universal Windows platform does not support SEH
247 // Or console colours (or console at all...)
248 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
249 # define CATCH_CONFIG_COLOUR_NONE
251 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
254 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
255 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
256 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
257 # if !defined(__clang__) // Handle Clang masquerading for msvc
258 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
259 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
260 # endif // MSVC_TRADITIONAL
265 #if defined(_REENTRANT) || defined(_MSC_VER)
266 // Enable async processing, as -pthread is specified or no additional linking is required
267 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
270 ////////////////////////////////////////////////////////////////////////////////
271 // Check if we are compiled with -fno-exceptions or equivalent
272 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
273 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
276 ////////////////////////////////////////////////////////////////////////////////
279 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
282 ////////////////////////////////////////////////////////////////////////////////
283 // Embarcadero C++Build
284 #if defined(__BORLANDC__)
285 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
288 ////////////////////////////////////////////////////////////////////////////////
290 // Use of __COUNTER__ is suppressed during code analysis in
291 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
293 // Otherwise all supported compilers support COUNTER macro,
294 // but user still might want to turn it off
295 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
296 #define CATCH_INTERNAL_CONFIG_COUNTER
299 ////////////////////////////////////////////////////////////////////////////////
301 // RTX is a special version of Windows that is real time.
302 // This means that it is detected as Windows, but does not provide
303 // the same set of capabilities as real Windows does.
304 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
305 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
306 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
307 #define CATCH_CONFIG_COLOUR_NONE
310 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
311 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
314 // Various stdlib support checks that require __has_include
315 #if defined(__has_include)
316 // Check if string_view is available and usable
317 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
318 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
321 // Check if optional is available and usable
322 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
323 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
324 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
326 // Check if byte is available and usable
327 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
329 # if __cpp_lib_byte > 0
330 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
332 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
334 // Check if variant is available and usable
335 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
336 # if defined(__clang__) && (__clang_major__ < 8)
337 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
338 // fix should be in clang 8, workaround in libstdc++ 8.2
340 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
341 # define CATCH_CONFIG_NO_CPP17_VARIANT
343 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
344 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
346 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
347 # endif // defined(__clang__) && (__clang_major__ < 8)
348 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
349 #endif // defined(__has_include)
351 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
352 # define CATCH_CONFIG_COUNTER
354 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
355 # define CATCH_CONFIG_WINDOWS_SEH
357 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
358 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
359 # define CATCH_CONFIG_POSIX_SIGNALS
361 // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
362 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
363 # define CATCH_CONFIG_WCHAR
366 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
367 # define CATCH_CONFIG_CPP11_TO_STRING
370 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
371 # define CATCH_CONFIG_CPP17_OPTIONAL
374 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
375 # define CATCH_CONFIG_CPP17_STRING_VIEW
378 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
379 # define CATCH_CONFIG_CPP17_VARIANT
382 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
383 # define CATCH_CONFIG_CPP17_BYTE
386 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
387 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
390 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
391 # define CATCH_CONFIG_NEW_CAPTURE
394 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
395 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
398 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
399 # define CATCH_CONFIG_POLYFILL_ISNAN
402 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
403 # define CATCH_CONFIG_USE_ASYNC
406 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
407 # define CATCH_CONFIG_ANDROID_LOGWRITE
410 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
411 # define CATCH_CONFIG_GLOBAL_NEXTAFTER
414 // Even if we do not think the compiler has that warning, we still have
415 // to provide a macro that can be used by the code.
416 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
417 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
419 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
420 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
422 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
423 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
425 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
426 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
428 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
429 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
431 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
432 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
435 // The goal of this macro is to avoid evaluation of the arguments, but
436 // still have the compiler warn on problems inside...
437 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
438 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
441 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
442 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
443 #elif defined(__clang__) && (__clang_major__ < 5)
444 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
447 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
448 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
451 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
452 #define CATCH_TRY if ((true))
453 #define CATCH_CATCH_ALL if ((false))
454 #define CATCH_CATCH_ANON(type) if ((false))
456 #define CATCH_TRY try
457 #define CATCH_CATCH_ALL catch (...)
458 #define CATCH_CATCH_ANON(type) catch (type)
461 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
462 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
465 // end catch_compiler_capabilities.h
466 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
467 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
468 #ifdef CATCH_CONFIG_COUNTER
469 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
471 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
478 // We need a dummy global operator<< so we can bring it into Catch namespace later
479 struct Catch_global_namespace_dummy {};
480 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
484 struct CaseSensitive { enum Choice {
490 NonCopyable( NonCopyable const& ) = delete;
491 NonCopyable( NonCopyable && ) = delete;
492 NonCopyable& operator = ( NonCopyable const& ) = delete;
493 NonCopyable& operator = ( NonCopyable && ) = delete;
497 virtual ~NonCopyable();
500 struct SourceLineInfo {
502 SourceLineInfo() = delete;
503 SourceLineInfo( char const* _file, std::size_t _line ) noexcept
508 SourceLineInfo( SourceLineInfo const& other ) = default;
509 SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
510 SourceLineInfo( SourceLineInfo&& ) noexcept = default;
511 SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
513 bool empty() const noexcept { return file[0] == '\0'; }
514 bool operator == ( SourceLineInfo const& other ) const noexcept;
515 bool operator < ( SourceLineInfo const& other ) const noexcept;
521 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
523 // Bring in operator<< from global namespace into Catch namespace
524 // This is necessary because the overload of operator<< above makes
525 // lookup stop at namespace Catch
528 // Use this in variadic streaming macros to allow
531 // >> stuff +StreamEndStop
532 struct StreamEndStop {
533 std::string operator+() const;
536 T const& operator + ( T const& value, StreamEndStop ) {
541 #define CATCH_INTERNAL_LINEINFO \
542 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
544 // end catch_common.h
547 struct RegistrarForTagAliases {
548 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
551 } // end namespace Catch
553 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
554 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
555 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
556 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
557 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
559 // end catch_tag_alias_autoregistrar.h
560 // start catch_test_registry.h
562 // start catch_interfaces_testcase.h
570 struct ITestInvoker {
571 virtual void invoke () const = 0;
572 virtual ~ITestInvoker();
578 struct ITestCaseRegistry {
579 virtual ~ITestCaseRegistry();
580 virtual std::vector<TestCase> const& getAllTests() const = 0;
581 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
584 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
585 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
586 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
587 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
591 // end catch_interfaces_testcase.h
592 // start catch_stringref.h
601 /// A non-owning string class (similar to the forthcoming std::string_view)
602 /// Note that, because a StringRef may be a substring of another string,
603 /// it may not be null terminated.
606 using size_type = std::size_t;
607 using const_iterator = const char*;
610 static constexpr char const* const s_empty = "";
612 char const* m_start = s_empty;
613 size_type m_size = 0;
615 public: // construction
616 constexpr StringRef() noexcept = default;
618 StringRef( char const* rawChars ) noexcept;
620 constexpr StringRef( char const* rawChars, size_type size ) noexcept
621 : m_start( rawChars ),
625 StringRef( std::string const& stdString ) noexcept
626 : m_start( stdString.c_str() ),
627 m_size( stdString.size() )
630 explicit operator std::string() const {
631 return std::string(m_start, m_size);
635 auto operator == ( StringRef const& other ) const noexcept -> bool;
636 auto operator != (StringRef const& other) const noexcept -> bool {
637 return !(*this == other);
640 auto operator[] ( size_type index ) const noexcept -> char {
641 assert(index < m_size);
642 return m_start[index];
645 public: // named queries
646 constexpr auto empty() const noexcept -> bool {
649 constexpr auto size() const noexcept -> size_type {
653 // Returns the current start pointer. If the StringRef is not
654 // null-terminated, throws std::domain_exception
655 auto c_str() const -> char const*;
657 public: // substrings and searches
658 // Returns a substring of [start, start + length).
659 // If start + length > size(), then the substring is [start, size()).
660 // If start > size(), then the substring is empty.
661 auto substr( size_type start, size_type length ) const noexcept -> StringRef;
663 // Returns the current start pointer. May not be null-terminated.
664 auto data() const noexcept -> char const*;
666 constexpr auto isNullTerminated() const noexcept -> bool {
667 return m_start[m_size] == '\0';
671 constexpr const_iterator begin() const { return m_start; }
672 constexpr const_iterator end() const { return m_start + m_size; }
675 auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
676 auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
678 constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
679 return StringRef( rawChars, size );
683 constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
684 return Catch::StringRef( rawChars, size );
687 // end catch_stringref.h
688 // start catch_preprocessor.hpp
691 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
692 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
693 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
694 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
695 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
696 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
698 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
699 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
700 // MSVC needs more evaluations
701 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
702 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
704 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
707 #define CATCH_REC_END(...)
708 #define CATCH_REC_OUT
710 #define CATCH_EMPTY()
711 #define CATCH_DEFER(id) id CATCH_EMPTY()
713 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
714 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
715 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
716 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
717 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
718 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
720 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
721 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
722 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
724 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
725 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
726 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
728 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
729 // and passes userdata as the first parameter to each invocation,
730 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
731 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
733 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
735 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
736 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
737 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
738 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
739 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
740 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
741 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
742 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
744 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
745 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
746 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
747 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
750 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
751 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
753 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
755 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
756 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
757 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
759 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
760 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
763 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
764 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
766 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
767 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
768 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
769 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
770 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
771 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
772 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
773 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
774 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
775 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
776 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
778 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
780 #define INTERNAL_CATCH_TYPE_GEN\
781 template<typename...> struct TypeList {};\
782 template<typename...Ts>\
783 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
784 template<template<typename...> class...> struct TemplateTypeList{};\
785 template<template<typename...> class...Cs>\
786 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
787 template<typename...>\
789 template<typename...>\
791 template<template<typename...> class, typename...>\
793 template<template<typename...> class, typename>\
796 template<typename T> \
797 struct append<T> { using type = T; };\
798 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
799 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
800 template< template<typename...> class L1, typename...E1, typename...Rest>\
801 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
803 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
804 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
805 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
806 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
808 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
809 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
810 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
811 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
813 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
814 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
815 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
816 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
817 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
818 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
819 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
821 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
822 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
824 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
825 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
826 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
828 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
829 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
830 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
831 static void TestName()
832 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
833 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
834 static void TestName()
836 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
837 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
838 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
839 static void TestName()
840 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
841 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
842 static void TestName()
844 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
845 template<typename Type>\
846 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
848 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
851 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
852 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
853 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
855 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
858 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
859 template<typename Type>\
860 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
862 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
865 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
866 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
867 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
869 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
872 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
873 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
874 template<typename TestType> \
875 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
879 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
880 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
881 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
885 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
886 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
887 template<typename TestType> \
888 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
889 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
890 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
891 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
893 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
894 #define INTERNAL_CATCH_NTTP_0
895 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
896 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
897 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
898 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
899 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
900 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
901 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
902 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
904 #define INTERNAL_CATCH_NTTP_0(signature)
905 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
906 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
907 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
908 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
909 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
910 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
911 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
912 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
915 // end catch_preprocessor.hpp
916 // start catch_meta.hpp
919 #include <type_traits>
923 struct always_false : std::false_type {};
925 template <typename> struct true_given : std::true_type {};
926 struct is_callable_tester {
927 template <typename Fun, typename... Args>
928 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
929 template <typename...>
930 std::false_type static test(...);
933 template <typename T>
936 template <typename Fun, typename... Args>
937 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
939 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
940 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
941 // replaced with std::invoke_result here.
942 template <typename Func, typename... U>
943 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
945 // Keep ::type here because we still support C++11
946 template <typename Func, typename... U>
947 using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
956 // end catch_meta.hpp
960 class TestInvokerAsMethod : public ITestInvoker {
961 void (C::*m_testAsMethod)();
963 TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
965 void invoke() const override {
967 (obj.*m_testAsMethod)();
971 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
974 auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
975 return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
979 NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
984 struct AutoReg : NonCopyable {
985 AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
989 } // end namespace Catch
991 #if defined(CATCH_CONFIG_DISABLE)
992 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
993 static void TestName()
994 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
996 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1000 void TestName::test()
1001 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1002 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1003 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1005 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1006 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1009 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1011 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1012 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1013 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1015 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1016 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1019 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1020 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1021 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1023 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1024 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1027 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1028 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1029 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1031 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1032 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1035 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1036 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1037 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1039 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1040 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1044 ///////////////////////////////////////////////////////////////////////////////
1045 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1046 static void TestName(); \
1047 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1048 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1049 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1050 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1051 static void TestName()
1052 #define INTERNAL_CATCH_TESTCASE( ... ) \
1053 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1055 ///////////////////////////////////////////////////////////////////////////////
1056 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1057 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1058 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1059 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1060 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1062 ///////////////////////////////////////////////////////////////////////////////
1063 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1064 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1065 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1067 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1070 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1072 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1073 void TestName::test()
1074 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1075 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1077 ///////////////////////////////////////////////////////////////////////////////
1078 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1079 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1080 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1081 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1082 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1084 ///////////////////////////////////////////////////////////////////////////////
1085 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1086 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1087 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1088 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1089 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1090 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1092 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1093 INTERNAL_CATCH_TYPE_GEN\
1094 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1095 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1096 template<typename...Types> \
1100 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1101 using expander = int[];\
1102 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1105 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1106 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1111 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1112 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1114 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1115 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1116 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1118 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1119 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1122 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1123 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1124 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1126 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1127 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1130 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1131 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1132 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1133 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1134 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1135 template<typename TestType> static void TestFuncName(); \
1137 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1138 INTERNAL_CATCH_TYPE_GEN \
1139 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1140 template<typename... Types> \
1142 void reg_tests() { \
1144 using expander = int[]; \
1145 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1146 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1147 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1148 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\
1151 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1152 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1159 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1160 template<typename TestType> \
1161 static void TestFuncName()
1163 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1164 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1165 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
1167 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1168 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
1171 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1172 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1173 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
1175 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1176 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1179 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1180 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1181 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1182 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1183 template<typename TestType> static void TestFunc(); \
1185 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1186 INTERNAL_CATCH_TYPE_GEN\
1187 template<typename... Types> \
1189 void reg_tests() { \
1191 using expander = int[]; \
1192 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
1195 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1196 using TestInit = typename convert<TestName, TmplList>::type; \
1202 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1203 template<typename TestType> \
1204 static void TestFunc()
1206 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1207 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
1209 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1210 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1211 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1212 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1213 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1215 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1216 INTERNAL_CATCH_TYPE_GEN\
1217 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1218 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1219 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1220 template<typename...Types> \
1221 struct TestNameClass{\
1224 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1225 using expander = int[];\
1226 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1229 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1230 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1235 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1236 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1238 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1239 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1240 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1242 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1243 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1246 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1247 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1248 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1250 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1251 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( 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____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1254 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1255 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1256 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1257 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1258 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1259 template<typename TestType> \
1260 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1264 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1265 INTERNAL_CATCH_TYPE_GEN \
1266 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1267 template<typename...Types>\
1268 struct TestNameClass{\
1271 using expander = int[];\
1272 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1273 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1274 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1275 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \
1278 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1279 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
1286 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1287 template<typename TestType> \
1288 void TestName<TestType>::test()
1290 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1291 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1292 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
1294 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1295 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
1298 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1299 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1300 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
1302 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1303 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
1306 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1307 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1308 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1309 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1310 template<typename TestType> \
1311 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1315 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1316 INTERNAL_CATCH_TYPE_GEN\
1317 template<typename...Types>\
1318 struct TestNameClass{\
1321 using expander = int[];\
1322 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
1325 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1326 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1332 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1333 template<typename TestType> \
1334 void TestName<TestType>::test()
1336 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1337 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
1339 // end catch_test_registry.h
1340 // start catch_capture.hpp
1342 // start catch_assertionhandler.h
1344 // start catch_assertioninfo.h
1346 // start catch_result_type.h
1350 // ResultWas::OfType enum
1351 struct ResultWas { enum OfType {
1359 ExpressionFailed = FailureBit | 1,
1360 ExplicitFailure = FailureBit | 2,
1362 Exception = 0x100 | FailureBit,
1364 ThrewException = Exception | 1,
1365 DidntThrowException = Exception | 2,
1367 FatalErrorCondition = 0x200 | FailureBit
1371 bool isOk( ResultWas::OfType resultType );
1372 bool isJustInfo( int flags );
1374 // ResultDisposition::Flags enum
1375 struct ResultDisposition { enum Flags {
1378 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1379 FalseTest = 0x04, // Prefix expression with !
1380 SuppressFail = 0x08 // Failures are reported but do not fail the test
1383 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1385 bool shouldContinueOnFailure( int flags );
1386 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1387 bool shouldSuppressFailure( int flags );
1389 } // end namespace Catch
1391 // end catch_result_type.h
1394 struct AssertionInfo
1396 StringRef macroName;
1397 SourceLineInfo lineInfo;
1398 StringRef capturedExpression;
1399 ResultDisposition::Flags resultDisposition;
1401 // We want to delete this constructor but a compiler bug in 4.8 means
1402 // the struct is then treated as non-aggregate
1403 //AssertionInfo() = delete;
1406 } // end namespace Catch
1408 // end catch_assertioninfo.h
1409 // start catch_decomposer.h
1411 // start catch_tostring.h
1415 #include <type_traits>
1417 // start catch_stream.h
1425 std::ostream& cout();
1426 std::ostream& cerr();
1427 std::ostream& clog();
1433 virtual std::ostream& stream() const = 0;
1436 auto makeStream( StringRef const &filename ) -> IStream const*;
1438 class ReusableStringStream : NonCopyable {
1439 std::size_t m_index;
1440 std::ostream* m_oss;
1442 ReusableStringStream();
1443 ~ReusableStringStream();
1445 auto str() const -> std::string;
1447 template<typename T>
1448 auto operator << ( T const& value ) -> ReusableStringStream& {
1452 auto get() -> std::ostream& { return *m_oss; }
1456 // end catch_stream.h
1457 // start catch_interfaces_enum_values_registry.h
1466 std::vector<std::pair<int, StringRef>> m_values;
1470 StringRef lookup( int value ) const;
1472 } // namespace Detail
1474 struct IMutableEnumValuesRegistry {
1475 virtual ~IMutableEnumValuesRegistry();
1477 virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1479 template<typename E>
1480 Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1481 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1482 std::vector<int> intValues;
1483 intValues.reserve( values.size() );
1484 for( auto enumValue : values )
1485 intValues.push_back( static_cast<int>( enumValue ) );
1486 return registerEnum( enumName, allEnums, intValues );
1492 // end catch_interfaces_enum_values_registry.h
1494 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1495 #include <string_view>
1499 // start catch_objc_arc.hpp
1501 #import <Foundation/Foundation.h>
1503 #ifdef __has_feature
1504 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1506 #define CATCH_ARC_ENABLED 0
1509 void arcSafeRelease( NSObject* obj );
1510 id performOptionalSelector( id obj, SEL sel );
1512 #if !CATCH_ARC_ENABLED
1513 inline void arcSafeRelease( NSObject* obj ) {
1516 inline id performOptionalSelector( id obj, SEL sel ) {
1517 if( [obj respondsToSelector: sel] )
1518 return [obj performSelector: sel];
1521 #define CATCH_UNSAFE_UNRETAINED
1522 #define CATCH_ARC_STRONG
1524 inline void arcSafeRelease( NSObject* ){}
1525 inline id performOptionalSelector( id obj, SEL sel ) {
1527 #pragma clang diagnostic push
1528 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1530 if( [obj respondsToSelector: sel] )
1531 return [obj performSelector: sel];
1533 #pragma clang diagnostic pop
1537 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1538 #define CATCH_ARC_STRONG __strong
1541 // end catch_objc_arc.hpp
1545 #pragma warning(push)
1546 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1552 extern const std::string unprintableString;
1554 std::string rawMemoryToString( const void *object, std::size_t size );
1556 template<typename T>
1557 std::string rawMemoryToString( const T& object ) {
1558 return rawMemoryToString( &object, sizeof(object) );
1561 template<typename T>
1562 class IsStreamInsertable {
1563 template<typename Stream, typename U>
1564 static auto test(int)
1565 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1567 template<typename, typename>
1568 static auto test(...)->std::false_type;
1571 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1574 template<typename E>
1575 std::string convertUnknownEnumToString( E e );
1577 template<typename T>
1578 typename std::enable_if<
1579 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1580 std::string>::type convertUnstreamable( T const& ) {
1581 return Detail::unprintableString;
1583 template<typename T>
1584 typename std::enable_if<
1585 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1586 std::string>::type convertUnstreamable(T const& ex) {
1590 template<typename T>
1591 typename std::enable_if<
1592 std::is_enum<T>::value
1593 , std::string>::type convertUnstreamable( T const& value ) {
1594 return convertUnknownEnumToString( value );
1597 #if defined(_MANAGED)
1598 //! Convert a CLR string to a utf8 std::string
1599 template<typename T>
1600 std::string clrReferenceToString( T^ ref ) {
1602 return std::string("null");
1603 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1604 cli::pin_ptr<System::Byte> p = &bytes[0];
1605 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1609 } // namespace Detail
1611 // If we decide for C++14, change these to enable_if_ts
1612 template <typename T, typename = void>
1613 struct StringMaker {
1614 template <typename Fake = T>
1616 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1617 convert(const Fake& value) {
1618 ReusableStringStream rss;
1619 // NB: call using the function-like syntax to avoid ambiguity with
1620 // user-defined templated operator<< under clang.
1621 rss.operator<<(value);
1625 template <typename Fake = T>
1627 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1628 convert( const Fake& value ) {
1629 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1630 return Detail::convertUnstreamable(value);
1632 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1639 // This function dispatches all stringification requests inside of Catch.
1640 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1641 template <typename T>
1642 std::string stringify(const T& e) {
1643 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1646 template<typename E>
1647 std::string convertUnknownEnumToString( E e ) {
1648 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1651 #if defined(_MANAGED)
1652 template <typename T>
1653 std::string stringify( T^ e ) {
1654 return ::Catch::StringMaker<T^>::convert(e);
1658 } // namespace Detail
1660 // Some predefined specializations
1663 struct StringMaker<std::string> {
1664 static std::string convert(const std::string& str);
1667 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1669 struct StringMaker<std::string_view> {
1670 static std::string convert(std::string_view str);
1675 struct StringMaker<char const *> {
1676 static std::string convert(char const * str);
1679 struct StringMaker<char *> {
1680 static std::string convert(char * str);
1683 #ifdef CATCH_CONFIG_WCHAR
1685 struct StringMaker<std::wstring> {
1686 static std::string convert(const std::wstring& wstr);
1689 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1691 struct StringMaker<std::wstring_view> {
1692 static std::string convert(std::wstring_view str);
1697 struct StringMaker<wchar_t const *> {
1698 static std::string convert(wchar_t const * str);
1701 struct StringMaker<wchar_t *> {
1702 static std::string convert(wchar_t * str);
1706 // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1707 // while keeping string semantics?
1709 struct StringMaker<char[SZ]> {
1710 static std::string convert(char const* str) {
1711 return ::Catch::Detail::stringify(std::string{ str });
1715 struct StringMaker<signed char[SZ]> {
1716 static std::string convert(signed char const* str) {
1717 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1721 struct StringMaker<unsigned char[SZ]> {
1722 static std::string convert(unsigned char const* str) {
1723 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1727 #if defined(CATCH_CONFIG_CPP17_BYTE)
1729 struct StringMaker<std::byte> {
1730 static std::string convert(std::byte value);
1732 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1734 struct StringMaker<int> {
1735 static std::string convert(int value);
1738 struct StringMaker<long> {
1739 static std::string convert(long value);
1742 struct StringMaker<long long> {
1743 static std::string convert(long long value);
1746 struct StringMaker<unsigned int> {
1747 static std::string convert(unsigned int value);
1750 struct StringMaker<unsigned long> {
1751 static std::string convert(unsigned long value);
1754 struct StringMaker<unsigned long long> {
1755 static std::string convert(unsigned long long value);
1759 struct StringMaker<bool> {
1760 static std::string convert(bool b);
1764 struct StringMaker<char> {
1765 static std::string convert(char c);
1768 struct StringMaker<signed char> {
1769 static std::string convert(signed char c);
1772 struct StringMaker<unsigned char> {
1773 static std::string convert(unsigned char c);
1777 struct StringMaker<std::nullptr_t> {
1778 static std::string convert(std::nullptr_t);
1782 struct StringMaker<float> {
1783 static std::string convert(float value);
1784 static int precision;
1788 struct StringMaker<double> {
1789 static std::string convert(double value);
1790 static int precision;
1793 template <typename T>
1794 struct StringMaker<T*> {
1795 template <typename U>
1796 static std::string convert(U* p) {
1798 return ::Catch::Detail::rawMemoryToString(p);
1805 template <typename R, typename C>
1806 struct StringMaker<R C::*> {
1807 static std::string convert(R C::* p) {
1809 return ::Catch::Detail::rawMemoryToString(p);
1816 #if defined(_MANAGED)
1817 template <typename T>
1818 struct StringMaker<T^> {
1819 static std::string convert( T^ ref ) {
1820 return ::Catch::Detail::clrReferenceToString(ref);
1826 template<typename InputIterator, typename Sentinel = InputIterator>
1827 std::string rangeToString(InputIterator first, Sentinel last) {
1828 ReusableStringStream rss;
1830 if (first != last) {
1831 rss << ::Catch::Detail::stringify(*first);
1832 for (++first; first != last; ++first)
1833 rss << ", " << ::Catch::Detail::stringify(*first);
1842 struct StringMaker<NSString*> {
1843 static std::string convert(NSString * nsstring) {
1846 return std::string("@") + [nsstring UTF8String];
1850 struct StringMaker<NSObject*> {
1851 static std::string convert(NSObject* nsObject) {
1852 return ::Catch::Detail::stringify([nsObject description]);
1857 inline std::string stringify( NSString* nsstring ) {
1858 return StringMaker<NSString*>::convert( nsstring );
1861 } // namespace Detail
1864 } // namespace Catch
1866 //////////////////////////////////////////////////////
1867 // Separate std-lib types stringification, so it can be selectively enabled
1868 // This means that we do not bring in
1870 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1871 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1872 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1873 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1874 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1875 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1878 // Separate std::pair specialization
1879 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1882 template<typename T1, typename T2>
1883 struct StringMaker<std::pair<T1, T2> > {
1884 static std::string convert(const std::pair<T1, T2>& pair) {
1885 ReusableStringStream rss;
1887 << ::Catch::Detail::stringify(pair.first)
1889 << ::Catch::Detail::stringify(pair.second)
1895 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1897 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1900 template<typename T>
1901 struct StringMaker<std::optional<T> > {
1902 static std::string convert(const std::optional<T>& optional) {
1903 ReusableStringStream rss;
1904 if (optional.has_value()) {
1905 rss << ::Catch::Detail::stringify(*optional);
1913 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1915 // Separate std::tuple specialization
1916 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1923 bool = (N < std::tuple_size<Tuple>::value)
1925 struct TupleElementPrinter {
1926 static void print(const Tuple& tuple, std::ostream& os) {
1927 os << (N ? ", " : " ")
1928 << ::Catch::Detail::stringify(std::get<N>(tuple));
1929 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1937 struct TupleElementPrinter<Tuple, N, false> {
1938 static void print(const Tuple&, std::ostream&) {}
1943 template<typename ...Types>
1944 struct StringMaker<std::tuple<Types...>> {
1945 static std::string convert(const std::tuple<Types...>& tuple) {
1946 ReusableStringStream rss;
1948 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1954 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1956 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1960 struct StringMaker<std::monostate> {
1961 static std::string convert(const std::monostate&) {
1966 template<typename... Elements>
1967 struct StringMaker<std::variant<Elements...>> {
1968 static std::string convert(const std::variant<Elements...>& variant) {
1969 if (variant.valueless_by_exception()) {
1970 return "{valueless variant}";
1973 [](const auto& value) {
1974 return ::Catch::Detail::stringify(value);
1982 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1985 // Import begin/ end from std here
1990 template <typename...>
1995 template <typename T, typename = void>
1996 struct is_range_impl : std::false_type {
1999 template <typename T>
2000 struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
2002 } // namespace detail
2004 template <typename T>
2005 struct is_range : detail::is_range_impl<T> {
2008 #if defined(_MANAGED) // Managed types are never ranges
2009 template <typename T>
2010 struct is_range<T^> {
2011 static const bool value = false;
2015 template<typename Range>
2016 std::string rangeToString( Range const& range ) {
2017 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2020 // Handle vector<bool> specially
2021 template<typename Allocator>
2022 std::string rangeToString( std::vector<bool, Allocator> const& v ) {
2023 ReusableStringStream rss;
2031 rss << ::Catch::Detail::stringify( b );
2037 template<typename R>
2038 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2039 static std::string convert( R const& range ) {
2040 return rangeToString( range );
2044 template <typename T, int SZ>
2045 struct StringMaker<T[SZ]> {
2046 static std::string convert(T const(&arr)[SZ]) {
2047 return rangeToString(arr);
2051 } // namespace Catch
2053 // Separate std::chrono::duration specialization
2054 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2061 template <class Ratio>
2062 struct ratio_string {
2063 static std::string symbol();
2066 template <class Ratio>
2067 std::string ratio_string<Ratio>::symbol() {
2068 Catch::ReusableStringStream rss;
2069 rss << '[' << Ratio::num << '/'
2070 << Ratio::den << ']';
2074 struct ratio_string<std::atto> {
2075 static std::string symbol();
2078 struct ratio_string<std::femto> {
2079 static std::string symbol();
2082 struct ratio_string<std::pico> {
2083 static std::string symbol();
2086 struct ratio_string<std::nano> {
2087 static std::string symbol();
2090 struct ratio_string<std::micro> {
2091 static std::string symbol();
2094 struct ratio_string<std::milli> {
2095 static std::string symbol();
2099 // std::chrono::duration specializations
2100 template<typename Value, typename Ratio>
2101 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2102 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2103 ReusableStringStream rss;
2104 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2108 template<typename Value>
2109 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2110 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2111 ReusableStringStream rss;
2112 rss << duration.count() << " s";
2116 template<typename Value>
2117 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2118 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2119 ReusableStringStream rss;
2120 rss << duration.count() << " m";
2124 template<typename Value>
2125 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2126 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2127 ReusableStringStream rss;
2128 rss << duration.count() << " h";
2134 // std::chrono::time_point specialization
2135 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2136 template<typename Clock, typename Duration>
2137 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2138 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2139 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2142 // std::chrono::time_point<system_clock> specialization
2143 template<typename Duration>
2144 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2145 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2146 auto converted = std::chrono::system_clock::to_time_t(time_point);
2149 std::tm timeInfo = {};
2150 gmtime_s(&timeInfo, &converted);
2152 std::tm* timeInfo = std::gmtime(&converted);
2155 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2156 char timeStamp[timeStampSize];
2157 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2160 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2162 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2164 return std::string(timeStamp);
2168 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2170 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2172 template<> struct StringMaker<enumName> { \
2173 static std::string convert( enumName value ) { \
2174 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2175 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2180 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2183 #pragma warning(pop)
2186 // end catch_tostring.h
2190 #pragma warning(push)
2191 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2192 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2193 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2194 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2195 #pragma warning(disable:4800) // Forcing result to true or false
2200 struct ITransientExpression {
2201 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2202 auto getResult() const -> bool { return m_result; }
2203 virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2205 ITransientExpression( bool isBinaryExpression, bool result )
2206 : m_isBinaryExpression( isBinaryExpression ),
2210 // We don't actually need a virtual destructor, but many static analysers
2211 // complain if it's not here :-(
2212 virtual ~ITransientExpression();
2214 bool m_isBinaryExpression;
2219 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2221 template<typename LhsT, typename RhsT>
2222 class BinaryExpr : public ITransientExpression {
2227 void streamReconstructedExpression( std::ostream &os ) const override {
2228 formatReconstructedExpression
2229 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2233 BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2234 : ITransientExpression{ true, comparisonResult },
2240 template<typename T>
2241 auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2242 static_assert(always_false<T>::value,
2243 "chained comparisons are not supported inside assertions, "
2244 "wrap the expression inside parentheses, or decompose it");
2247 template<typename T>
2248 auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2249 static_assert(always_false<T>::value,
2250 "chained comparisons are not supported inside assertions, "
2251 "wrap the expression inside parentheses, or decompose it");
2254 template<typename T>
2255 auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2256 static_assert(always_false<T>::value,
2257 "chained comparisons are not supported inside assertions, "
2258 "wrap the expression inside parentheses, or decompose it");
2261 template<typename T>
2262 auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2263 static_assert(always_false<T>::value,
2264 "chained comparisons are not supported inside assertions, "
2265 "wrap the expression inside parentheses, or decompose it");
2268 template<typename T>
2269 auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2270 static_assert(always_false<T>::value,
2271 "chained comparisons are not supported inside assertions, "
2272 "wrap the expression inside parentheses, or decompose it");
2275 template<typename T>
2276 auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2277 static_assert(always_false<T>::value,
2278 "chained comparisons are not supported inside assertions, "
2279 "wrap the expression inside parentheses, or decompose it");
2282 template<typename T>
2283 auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2284 static_assert(always_false<T>::value,
2285 "chained comparisons are not supported inside assertions, "
2286 "wrap the expression inside parentheses, or decompose it");
2289 template<typename T>
2290 auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2291 static_assert(always_false<T>::value,
2292 "chained comparisons are not supported inside assertions, "
2293 "wrap the expression inside parentheses, or decompose it");
2297 template<typename LhsT>
2298 class UnaryExpr : public ITransientExpression {
2301 void streamReconstructedExpression( std::ostream &os ) const override {
2302 os << Catch::Detail::stringify( m_lhs );
2306 explicit UnaryExpr( LhsT lhs )
2307 : ITransientExpression{ false, static_cast<bool>(lhs) },
2312 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2313 template<typename LhsT, typename RhsT>
2314 auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2315 template<typename T>
2316 auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2317 template<typename T>
2318 auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2319 template<typename T>
2320 auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2321 template<typename T>
2322 auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2324 template<typename LhsT, typename RhsT>
2325 auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2326 template<typename T>
2327 auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2328 template<typename T>
2329 auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2330 template<typename T>
2331 auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2332 template<typename T>
2333 auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2335 template<typename LhsT>
2339 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2341 template<typename RhsT>
2342 auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2343 return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2345 auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2346 return { m_lhs == rhs, m_lhs, "==", rhs };
2349 template<typename RhsT>
2350 auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2351 return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2353 auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2354 return { m_lhs != rhs, m_lhs, "!=", rhs };
2357 template<typename RhsT>
2358 auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2359 return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2361 template<typename RhsT>
2362 auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2363 return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2365 template<typename RhsT>
2366 auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2367 return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2369 template<typename RhsT>
2370 auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2371 return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2373 template <typename RhsT>
2374 auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2375 return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
2377 template <typename RhsT>
2378 auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2379 return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
2381 template <typename RhsT>
2382 auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2383 return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
2386 template<typename RhsT>
2387 auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2388 static_assert(always_false<RhsT>::value,
2389 "operator&& is not supported inside assertions, "
2390 "wrap the expression inside parentheses, or decompose it");
2393 template<typename RhsT>
2394 auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2395 static_assert(always_false<RhsT>::value,
2396 "operator|| is not supported inside assertions, "
2397 "wrap the expression inside parentheses, or decompose it");
2400 auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2401 return UnaryExpr<LhsT>{ m_lhs };
2405 void handleExpression( ITransientExpression const& expr );
2407 template<typename T>
2408 void handleExpression( ExprLhs<T> const& expr ) {
2409 handleExpression( expr.makeUnaryExpr() );
2413 template<typename T>
2414 auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2415 return ExprLhs<T const&>{ lhs };
2418 auto operator <=( bool value ) -> ExprLhs<bool> {
2419 return ExprLhs<bool>{ value };
2423 } // end namespace Catch
2426 #pragma warning(pop)
2429 // end catch_decomposer.h
2430 // start catch_interfaces_capture.h
2437 class AssertionResult;
2438 struct AssertionInfo;
2440 struct SectionEndInfo;
2442 struct MessageBuilder;
2444 struct AssertionReaction;
2445 struct SourceLineInfo;
2447 struct ITransientExpression;
2448 struct IGeneratorTracker;
2450 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2451 struct BenchmarkInfo;
2452 template <typename Duration = std::chrono::duration<double, std::nano>>
2453 struct BenchmarkStats;
2454 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2456 struct IResultCapture {
2458 virtual ~IResultCapture();
2460 virtual bool sectionStarted( SectionInfo const& sectionInfo,
2461 Counts& assertions ) = 0;
2462 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2463 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2465 virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2467 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2468 virtual void benchmarkPreparing( std::string const& name ) = 0;
2469 virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2470 virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2471 virtual void benchmarkFailed( std::string const& error ) = 0;
2472 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2474 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2475 virtual void popScopedMessage( MessageInfo const& message ) = 0;
2477 virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2479 virtual void handleFatalErrorCondition( StringRef message ) = 0;
2481 virtual void handleExpr
2482 ( AssertionInfo const& info,
2483 ITransientExpression const& expr,
2484 AssertionReaction& reaction ) = 0;
2485 virtual void handleMessage
2486 ( AssertionInfo const& info,
2487 ResultWas::OfType resultType,
2488 StringRef const& message,
2489 AssertionReaction& reaction ) = 0;
2490 virtual void handleUnexpectedExceptionNotThrown
2491 ( AssertionInfo const& info,
2492 AssertionReaction& reaction ) = 0;
2493 virtual void handleUnexpectedInflightException
2494 ( AssertionInfo const& info,
2495 std::string const& message,
2496 AssertionReaction& reaction ) = 0;
2497 virtual void handleIncomplete
2498 ( AssertionInfo const& info ) = 0;
2499 virtual void handleNonExpr
2500 ( AssertionInfo const &info,
2501 ResultWas::OfType resultType,
2502 AssertionReaction &reaction ) = 0;
2504 virtual bool lastAssertionPassed() = 0;
2505 virtual void assertionPassed() = 0;
2507 // Deprecated, do not use:
2508 virtual std::string getCurrentTestName() const = 0;
2509 virtual const AssertionResult* getLastResult() const = 0;
2510 virtual void exceptionEarlyReported() = 0;
2513 IResultCapture& getResultCapture();
2516 // end catch_interfaces_capture.h
2519 struct TestFailureException{};
2520 struct AssertionResultData;
2521 struct IResultCapture;
2524 class LazyExpression {
2525 friend class AssertionHandler;
2526 friend struct AssertionStats;
2527 friend class RunContext;
2529 ITransientExpression const* m_transientExpression = nullptr;
2532 LazyExpression( bool isNegated );
2533 LazyExpression( LazyExpression const& other );
2534 LazyExpression& operator = ( LazyExpression const& ) = delete;
2536 explicit operator bool() const;
2538 friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2541 struct AssertionReaction {
2542 bool shouldDebugBreak = false;
2543 bool shouldThrow = false;
2546 class AssertionHandler {
2547 AssertionInfo m_assertionInfo;
2548 AssertionReaction m_reaction;
2549 bool m_completed = false;
2550 IResultCapture& m_resultCapture;
2554 ( StringRef const& macroName,
2555 SourceLineInfo const& lineInfo,
2556 StringRef capturedExpression,
2557 ResultDisposition::Flags resultDisposition );
2558 ~AssertionHandler() {
2559 if ( !m_completed ) {
2560 m_resultCapture.handleIncomplete( m_assertionInfo );
2564 template<typename T>
2565 void handleExpr( ExprLhs<T> const& expr ) {
2566 handleExpr( expr.makeUnaryExpr() );
2568 void handleExpr( ITransientExpression const& expr );
2570 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2572 void handleExceptionThrownAsExpected();
2573 void handleUnexpectedExceptionNotThrown();
2574 void handleExceptionNotThrownAsExpected();
2575 void handleThrowingCallSkipped();
2576 void handleUnexpectedInflightException();
2579 void setCompleted();
2582 auto allowThrows() const -> bool;
2585 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2587 } // namespace Catch
2589 // end catch_assertionhandler.h
2590 // start catch_message.h
2597 struct MessageInfo {
2598 MessageInfo( StringRef const& _macroName,
2599 SourceLineInfo const& _lineInfo,
2600 ResultWas::OfType _type );
2602 StringRef macroName;
2603 std::string message;
2604 SourceLineInfo lineInfo;
2605 ResultWas::OfType type;
2606 unsigned int sequence;
2608 bool operator == ( MessageInfo const& other ) const;
2609 bool operator < ( MessageInfo const& other ) const;
2611 static unsigned int globalCount;
2614 struct MessageStream {
2616 template<typename T>
2617 MessageStream& operator << ( T const& value ) {
2622 ReusableStringStream m_stream;
2625 struct MessageBuilder : MessageStream {
2626 MessageBuilder( StringRef const& macroName,
2627 SourceLineInfo const& lineInfo,
2628 ResultWas::OfType type );
2630 template<typename T>
2631 MessageBuilder& operator << ( T const& value ) {
2639 class ScopedMessage {
2641 explicit ScopedMessage( MessageBuilder const& builder );
2642 ScopedMessage( ScopedMessage& duplicate ) = delete;
2643 ScopedMessage( ScopedMessage&& old );
2651 std::vector<MessageInfo> m_messages;
2652 IResultCapture& m_resultCapture = getResultCapture();
2653 size_t m_captured = 0;
2655 Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2658 void captureValue( size_t index, std::string const& value );
2660 template<typename T>
2661 void captureValues( size_t index, T const& value ) {
2662 captureValue( index, Catch::Detail::stringify( value ) );
2665 template<typename T, typename... Ts>
2666 void captureValues( size_t index, T const& value, Ts const&... values ) {
2667 captureValue( index, Catch::Detail::stringify(value) );
2668 captureValues( index+1, values... );
2672 } // end namespace Catch
2674 // end catch_message.h
2675 #if !defined(CATCH_CONFIG_DISABLE)
2677 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2678 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2680 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2683 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2685 ///////////////////////////////////////////////////////////////////////////////
2686 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2688 #define INTERNAL_CATCH_TRY
2689 #define INTERNAL_CATCH_CATCH( capturer )
2691 #else // CATCH_CONFIG_FAST_COMPILE
2693 #define INTERNAL_CATCH_TRY try
2694 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2698 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2700 ///////////////////////////////////////////////////////////////////////////////
2701 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2703 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2704 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2705 INTERNAL_CATCH_TRY { \
2706 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2707 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2708 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2709 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2710 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2711 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2712 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2714 ///////////////////////////////////////////////////////////////////////////////
2715 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2716 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2717 if( Catch::getResultCapture().lastAssertionPassed() )
2719 ///////////////////////////////////////////////////////////////////////////////
2720 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2721 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2722 if( !Catch::getResultCapture().lastAssertionPassed() )
2724 ///////////////////////////////////////////////////////////////////////////////
2725 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2727 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2729 static_cast<void>(__VA_ARGS__); \
2730 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2733 catchAssertionHandler.handleUnexpectedInflightException(); \
2735 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2738 ///////////////////////////////////////////////////////////////////////////////
2739 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2741 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2742 if( catchAssertionHandler.allowThrows() ) \
2744 static_cast<void>(__VA_ARGS__); \
2745 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2748 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2751 catchAssertionHandler.handleThrowingCallSkipped(); \
2752 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2755 ///////////////////////////////////////////////////////////////////////////////
2756 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2758 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2759 if( catchAssertionHandler.allowThrows() ) \
2761 static_cast<void>(expr); \
2762 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2764 catch( exceptionType const& ) { \
2765 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2768 catchAssertionHandler.handleUnexpectedInflightException(); \
2771 catchAssertionHandler.handleThrowingCallSkipped(); \
2772 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2775 ///////////////////////////////////////////////////////////////////////////////
2776 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2778 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2779 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2780 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2783 ///////////////////////////////////////////////////////////////////////////////
2784 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2785 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2786 varName.captureValues( 0, __VA_ARGS__ )
2788 ///////////////////////////////////////////////////////////////////////////////
2789 #define INTERNAL_CATCH_INFO( macroName, log ) \
2790 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2792 ///////////////////////////////////////////////////////////////////////////////
2793 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2794 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2796 ///////////////////////////////////////////////////////////////////////////////
2797 // Although this is matcher-based, it can be used with just a string
2798 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2800 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2801 if( catchAssertionHandler.allowThrows() ) \
2803 static_cast<void>(__VA_ARGS__); \
2804 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2807 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2810 catchAssertionHandler.handleThrowingCallSkipped(); \
2811 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2814 #endif // CATCH_CONFIG_DISABLE
2816 // end catch_capture.hpp
2817 // start catch_section.h
2819 // start catch_section_info.h
2821 // start catch_totals.h
2828 Counts operator - ( Counts const& other ) const;
2829 Counts& operator += ( Counts const& other );
2831 std::size_t total() const;
2832 bool allPassed() const;
2835 std::size_t passed = 0;
2836 std::size_t failed = 0;
2837 std::size_t failedButOk = 0;
2842 Totals operator - ( Totals const& other ) const;
2843 Totals& operator += ( Totals const& other );
2845 Totals delta( Totals const& prevTotals ) const;
2853 // end catch_totals.h
2858 struct SectionInfo {
2860 ( SourceLineInfo const& _lineInfo,
2861 std::string const& _name );
2865 ( SourceLineInfo const& _lineInfo,
2866 std::string const& _name,
2867 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2870 std::string description; // !Deprecated: this will always be empty
2871 SourceLineInfo lineInfo;
2874 struct SectionEndInfo {
2875 SectionInfo sectionInfo;
2876 Counts prevAssertions;
2877 double durationInSeconds;
2880 } // end namespace Catch
2882 // end catch_section_info.h
2883 // start catch_timer.h
2889 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2890 auto getEstimatedClockResolution() -> uint64_t;
2893 uint64_t m_nanoseconds = 0;
2896 auto getElapsedNanoseconds() const -> uint64_t;
2897 auto getElapsedMicroseconds() const -> uint64_t;
2898 auto getElapsedMilliseconds() const -> unsigned int;
2899 auto getElapsedSeconds() const -> double;
2902 } // namespace Catch
2904 // end catch_timer.h
2909 class Section : NonCopyable {
2911 Section( SectionInfo const& info );
2914 // This indicates whether the section should be executed or not
2915 explicit operator bool() const;
2921 Counts m_assertions;
2922 bool m_sectionIncluded;
2926 } // end namespace Catch
2928 #define INTERNAL_CATCH_SECTION( ... ) \
2929 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2930 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2931 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2932 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2934 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2935 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2936 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2937 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2938 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2940 // end catch_section.h
2941 // start catch_interfaces_exception.h
2943 // start catch_interfaces_registry_hub.h
2951 struct ITestCaseRegistry;
2952 struct IExceptionTranslatorRegistry;
2953 struct IExceptionTranslator;
2954 struct IReporterRegistry;
2955 struct IReporterFactory;
2956 struct ITagAliasRegistry;
2957 struct IMutableEnumValuesRegistry;
2959 class StartupExceptionRegistry;
2961 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2963 struct IRegistryHub {
2964 virtual ~IRegistryHub();
2966 virtual IReporterRegistry const& getReporterRegistry() const = 0;
2967 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2968 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2969 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2971 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2974 struct IMutableRegistryHub {
2975 virtual ~IMutableRegistryHub();
2976 virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2977 virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2978 virtual void registerTest( TestCase const& testInfo ) = 0;
2979 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2980 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2981 virtual void registerStartupException() noexcept = 0;
2982 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2985 IRegistryHub const& getRegistryHub();
2986 IMutableRegistryHub& getMutableRegistryHub();
2988 std::string translateActiveException();
2992 // end catch_interfaces_registry_hub.h
2993 #if defined(CATCH_CONFIG_DISABLE)
2994 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2995 static std::string translatorName( signature )
2998 #include <exception>
3003 using exceptionTranslateFunction = std::string(*)();
3005 struct IExceptionTranslator;
3006 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3008 struct IExceptionTranslator {
3009 virtual ~IExceptionTranslator();
3010 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
3013 struct IExceptionTranslatorRegistry {
3014 virtual ~IExceptionTranslatorRegistry();
3016 virtual std::string translateActiveException() const = 0;
3019 class ExceptionTranslatorRegistrar {
3020 template<typename T>
3021 class ExceptionTranslator : public IExceptionTranslator {
3024 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3025 : m_translateFunction( translateFunction )
3028 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
3029 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3034 std::rethrow_exception(std::current_exception());
3036 return (*it)->translate( it+1, itEnd );
3039 return m_translateFunction( ex );
3045 std::string(*m_translateFunction)( T& );
3049 template<typename T>
3050 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3051 getMutableRegistryHub().registerTranslator
3052 ( new ExceptionTranslator<T>( translateFunction ) );
3057 ///////////////////////////////////////////////////////////////////////////////
3058 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3059 static std::string translatorName( signature ); \
3060 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3061 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3062 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3063 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3064 static std::string translatorName( signature )
3066 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3068 // end catch_interfaces_exception.h
3069 // start catch_approx.h
3071 #include <type_traits>
3078 bool equalityComparisonImpl(double other) const;
3079 // Validates the new margin (margin >= 0)
3080 // out-of-line to avoid including stdexcept in the header
3081 void setMargin(double margin);
3082 // Validates the new epsilon (0 < epsilon < 1)
3083 // out-of-line to avoid including stdexcept in the header
3084 void setEpsilon(double epsilon);
3087 explicit Approx ( double value );
3089 static Approx custom();
3091 Approx operator-() const;
3093 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3094 Approx operator()( T const& value ) {
3095 Approx approx( static_cast<double>(value) );
3096 approx.m_epsilon = m_epsilon;
3097 approx.m_margin = m_margin;
3098 approx.m_scale = m_scale;
3102 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3103 explicit Approx( T const& value ): Approx(static_cast<double>(value))
3106 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3107 friend bool operator == ( const T& lhs, Approx const& rhs ) {
3108 auto lhs_v = static_cast<double>(lhs);
3109 return rhs.equalityComparisonImpl(lhs_v);
3112 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3113 friend bool operator == ( Approx const& lhs, const T& rhs ) {
3114 return operator==( rhs, lhs );
3117 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3118 friend bool operator != ( T const& lhs, Approx const& rhs ) {
3119 return !operator==( lhs, rhs );
3122 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3123 friend bool operator != ( Approx const& lhs, T const& rhs ) {
3124 return !operator==( rhs, lhs );
3127 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3128 friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3129 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3132 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3133 friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3134 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3137 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3138 friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3139 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3142 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3143 friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3144 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3147 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3148 Approx& epsilon( T const& newEpsilon ) {
3149 double epsilonAsDouble = static_cast<double>(newEpsilon);
3150 setEpsilon(epsilonAsDouble);
3154 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3155 Approx& margin( T const& newMargin ) {
3156 double marginAsDouble = static_cast<double>(newMargin);
3157 setMargin(marginAsDouble);
3161 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3162 Approx& scale( T const& newScale ) {
3163 m_scale = static_cast<double>(newScale);
3167 std::string toString() const;
3175 } // end namespace Detail
3177 namespace literals {
3178 Detail::Approx operator "" _a(long double val);
3179 Detail::Approx operator "" _a(unsigned long long val);
3180 } // end namespace literals
3183 struct StringMaker<Catch::Detail::Approx> {
3184 static std::string convert(Catch::Detail::Approx const& value);
3187 } // end namespace Catch
3189 // end catch_approx.h
3190 // start catch_string_manip.h
3198 bool startsWith( std::string const& s, std::string const& prefix );
3199 bool startsWith( std::string const& s, char prefix );
3200 bool endsWith( std::string const& s, std::string const& suffix );
3201 bool endsWith( std::string const& s, char suffix );
3202 bool contains( std::string const& s, std::string const& infix );
3203 void toLowerInPlace( std::string& s );
3204 std::string toLower( std::string const& s );
3205 //! Returns a new string without whitespace at the start/end
3206 std::string trim( std::string const& str );
3207 //! Returns a substring of the original ref without whitespace. Beware lifetimes!
3208 StringRef trim(StringRef ref);
3210 // !!! Be aware, returns refs into original string - make sure original string outlives them
3211 std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3212 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3215 pluralise( std::size_t count, std::string const& label );
3217 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3219 std::size_t m_count;
3220 std::string m_label;
3224 // end catch_string_manip.h
3225 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3226 // start catch_capture_matchers.h
3228 // start catch_matchers.h
3234 namespace Matchers {
3237 template<typename ArgT> struct MatchAllOf;
3238 template<typename ArgT> struct MatchAnyOf;
3239 template<typename ArgT> struct MatchNotOf;
3241 class MatcherUntypedBase {
3243 MatcherUntypedBase() = default;
3244 MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3245 MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3246 std::string toString() const;
3249 virtual ~MatcherUntypedBase();
3250 virtual std::string describe() const = 0;
3251 mutable std::string m_cachedToString;
3255 # pragma clang diagnostic push
3256 # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3259 template<typename ObjectT>
3260 struct MatcherMethod {
3261 virtual bool match( ObjectT const& arg ) const = 0;
3264 #if defined(__OBJC__)
3265 // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3266 // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3268 struct MatcherMethod<NSString*> {
3269 virtual bool match( NSString* arg ) const = 0;
3274 # pragma clang diagnostic pop
3277 template<typename T>
3278 struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3280 MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3281 MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3282 MatchNotOf<T> operator ! () const;
3285 template<typename ArgT>
3286 struct MatchAllOf : MatcherBase<ArgT> {
3287 bool match( ArgT const& arg ) const override {
3288 for( auto matcher : m_matchers ) {
3289 if (!matcher->match(arg))
3294 std::string describe() const override {
3295 std::string description;
3296 description.reserve( 4 + m_matchers.size()*32 );
3297 description += "( ";
3299 for( auto matcher : m_matchers ) {
3303 description += " and ";
3304 description += matcher->toString();
3306 description += " )";
3310 MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
3312 copy.m_matchers.push_back( &other );
3316 std::vector<MatcherBase<ArgT> const*> m_matchers;
3318 template<typename ArgT>
3319 struct MatchAnyOf : MatcherBase<ArgT> {
3321 bool match( ArgT const& arg ) const override {
3322 for( auto matcher : m_matchers ) {
3323 if (matcher->match(arg))
3328 std::string describe() const override {
3329 std::string description;
3330 description.reserve( 4 + m_matchers.size()*32 );
3331 description += "( ";
3333 for( auto matcher : m_matchers ) {
3337 description += " or ";
3338 description += matcher->toString();
3340 description += " )";
3344 MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
3346 copy.m_matchers.push_back( &other );
3350 std::vector<MatcherBase<ArgT> const*> m_matchers;
3353 template<typename ArgT>
3354 struct MatchNotOf : MatcherBase<ArgT> {
3356 MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3358 bool match( ArgT const& arg ) const override {
3359 return !m_underlyingMatcher.match( arg );
3362 std::string describe() const override {
3363 return "not " + m_underlyingMatcher.toString();
3365 MatcherBase<ArgT> const& m_underlyingMatcher;
3368 template<typename T>
3369 MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
3370 return MatchAllOf<T>() && *this && other;
3372 template<typename T>
3373 MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
3374 return MatchAnyOf<T>() || *this || other;
3376 template<typename T>
3377 MatchNotOf<T> MatcherBase<T>::operator ! () const {
3378 return MatchNotOf<T>( *this );
3383 } // namespace Matchers
3385 using namespace Matchers;
3386 using Matchers::Impl::MatcherBase;
3388 } // namespace Catch
3390 // end catch_matchers.h
3391 // start catch_matchers_exception.hpp
3394 namespace Matchers {
3395 namespace Exception {
3397 class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3398 std::string m_message;
3401 ExceptionMessageMatcher(std::string const& message):
3405 bool match(std::exception const& ex) const override;
3407 std::string describe() const override;
3410 } // namespace Exception
3412 Exception::ExceptionMessageMatcher Message(std::string const& message);
3414 } // namespace Matchers
3415 } // namespace Catch
3417 // end catch_matchers_exception.hpp
3418 // start catch_matchers_floating.h
3421 namespace Matchers {
3423 namespace Floating {
3425 enum class FloatingPointKind : uint8_t;
3427 struct WithinAbsMatcher : MatcherBase<double> {
3428 WithinAbsMatcher(double target, double margin);
3429 bool match(double const& matchee) const override;
3430 std::string describe() const override;
3436 struct WithinUlpsMatcher : MatcherBase<double> {
3437 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3438 bool match(double const& matchee) const override;
3439 std::string describe() const override;
3443 FloatingPointKind m_type;
3446 // Given IEEE-754 format for floats and doubles, we can assume
3447 // that float -> double promotion is lossless. Given this, we can
3448 // assume that if we do the standard relative comparison of
3449 // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3450 // the same result if we do this for floats, as if we do this for
3451 // doubles that were promoted from floats.
3452 struct WithinRelMatcher : MatcherBase<double> {
3453 WithinRelMatcher(double target, double epsilon);
3454 bool match(double const& matchee) const override;
3455 std::string describe() const override;
3461 } // namespace Floating
3463 // The following functions create the actual matcher objects.
3464 // This allows the types to be inferred
3465 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3466 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3467 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3468 Floating::WithinRelMatcher WithinRel(double target, double eps);
3469 // defaults epsilon to 100*numeric_limits<double>::epsilon()
3470 Floating::WithinRelMatcher WithinRel(double target);
3471 Floating::WithinRelMatcher WithinRel(float target, float eps);
3472 // defaults epsilon to 100*numeric_limits<float>::epsilon()
3473 Floating::WithinRelMatcher WithinRel(float target);
3475 } // namespace Matchers
3476 } // namespace Catch
3478 // end catch_matchers_floating.h
3479 // start catch_matchers_generic.hpp
3481 #include <functional>
3485 namespace Matchers {
3489 std::string finalizeDescription(const std::string& desc);
3492 template <typename T>
3493 class PredicateMatcher : public MatcherBase<T> {
3494 std::function<bool(T const&)> m_predicate;
3495 std::string m_description;
3498 PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3499 :m_predicate(std::move(elem)),
3500 m_description(Detail::finalizeDescription(descr))
3503 bool match( T const& item ) const override {
3504 return m_predicate(item);
3507 std::string describe() const override {
3508 return m_description;
3512 } // namespace Generic
3514 // The following functions create the actual matcher objects.
3515 // The user has to explicitly specify type to the function, because
3516 // inferring std::function<bool(T const&)> is hard (but possible) and
3517 // requires a lot of TMP.
3518 template<typename T>
3519 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3520 return Generic::PredicateMatcher<T>(predicate, description);
3523 } // namespace Matchers
3524 } // namespace Catch
3526 // end catch_matchers_generic.hpp
3527 // start catch_matchers_string.h
3532 namespace Matchers {
3534 namespace StdString {
3538 CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3539 std::string adjustString( std::string const& str ) const;
3540 std::string caseSensitivitySuffix() const;
3542 CaseSensitive::Choice m_caseSensitivity;
3546 struct StringMatcherBase : MatcherBase<std::string> {
3547 StringMatcherBase( std::string const& operation, CasedString const& comparator );
3548 std::string describe() const override;
3550 CasedString m_comparator;
3551 std::string m_operation;
3554 struct EqualsMatcher : StringMatcherBase {
3555 EqualsMatcher( CasedString const& comparator );
3556 bool match( std::string const& source ) const override;
3558 struct ContainsMatcher : StringMatcherBase {
3559 ContainsMatcher( CasedString const& comparator );
3560 bool match( std::string const& source ) const override;
3562 struct StartsWithMatcher : StringMatcherBase {
3563 StartsWithMatcher( CasedString const& comparator );
3564 bool match( std::string const& source ) const override;
3566 struct EndsWithMatcher : StringMatcherBase {
3567 EndsWithMatcher( CasedString const& comparator );
3568 bool match( std::string const& source ) const override;
3571 struct RegexMatcher : MatcherBase<std::string> {
3572 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3573 bool match( std::string const& matchee ) const override;
3574 std::string describe() const override;
3577 std::string m_regex;
3578 CaseSensitive::Choice m_caseSensitivity;
3581 } // namespace StdString
3583 // The following functions create the actual matcher objects.
3584 // This allows the types to be inferred
3586 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3587 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3588 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3589 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3590 StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3592 } // namespace Matchers
3593 } // namespace Catch
3595 // end catch_matchers_string.h
3596 // start catch_matchers_vector.h
3598 #include <algorithm>
3601 namespace Matchers {
3604 template<typename T, typename Alloc>
3605 struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
3607 ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3609 bool match(std::vector<T, Alloc> const &v) const override {
3610 for (auto const& el : v) {
3611 if (el == m_comparator) {
3618 std::string describe() const override {
3619 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3622 T const& m_comparator;
3625 template<typename T, typename AllocComp, typename AllocMatch>
3626 struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3628 ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3630 bool match(std::vector<T, AllocMatch> const &v) const override {
3631 // !TBD: see note in EqualsMatcher
3632 if (m_comparator.size() > v.size())
3634 for (auto const& comparator : m_comparator) {
3635 auto present = false;
3636 for (const auto& el : v) {
3637 if (el == comparator) {
3648 std::string describe() const override {
3649 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3652 std::vector<T, AllocComp> const& m_comparator;
3655 template<typename T, typename AllocComp, typename AllocMatch>
3656 struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3658 EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3660 bool match(std::vector<T, AllocMatch> const &v) const override {
3661 // !TBD: This currently works if all elements can be compared using !=
3662 // - a more general approach would be via a compare template that defaults
3663 // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
3664 // - then just call that directly
3665 if (m_comparator.size() != v.size())
3667 for (std::size_t i = 0; i < v.size(); ++i)
3668 if (m_comparator[i] != v[i])
3672 std::string describe() const override {
3673 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3675 std::vector<T, AllocComp> const& m_comparator;
3678 template<typename T, typename AllocComp, typename AllocMatch>
3679 struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3681 ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
3683 bool match(std::vector<T, AllocMatch> const &v) const override {
3684 if (m_comparator.size() != v.size())
3686 for (std::size_t i = 0; i < v.size(); ++i)
3687 if (m_comparator[i] != approx(v[i]))
3691 std::string describe() const override {
3692 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3694 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3695 ApproxMatcher& epsilon( T const& newEpsilon ) {
3696 approx.epsilon(newEpsilon);
3699 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3700 ApproxMatcher& margin( T const& newMargin ) {
3701 approx.margin(newMargin);
3704 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3705 ApproxMatcher& scale( T const& newScale ) {
3706 approx.scale(newScale);
3710 std::vector<T, AllocComp> const& m_comparator;
3711 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3714 template<typename T, typename AllocComp, typename AllocMatch>
3715 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3716 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
3717 bool match(std::vector<T, AllocMatch> const& vec) const override {
3718 if (m_target.size() != vec.size()) {
3721 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3724 std::string describe() const override {
3725 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3728 std::vector<T, AllocComp> const& m_target;
3731 } // namespace Vector
3733 // The following functions create the actual matcher objects.
3734 // This allows the types to be inferred
3736 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3737 Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
3738 return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
3741 template<typename T, typename Alloc = std::allocator<T>>
3742 Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
3743 return Vector::ContainsElementMatcher<T, Alloc>( comparator );
3746 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3747 Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
3748 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
3751 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3752 Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
3753 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
3756 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3757 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
3758 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
3761 } // namespace Matchers
3762 } // namespace Catch
3764 // end catch_matchers_vector.h
3767 template<typename ArgT, typename MatcherT>
3768 class MatchExpr : public ITransientExpression {
3771 StringRef m_matcherString;
3773 MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3774 : ITransientExpression{ true, matcher.match( arg ) },
3776 m_matcher( matcher ),
3777 m_matcherString( matcherString )
3780 void streamReconstructedExpression( std::ostream &os ) const override {
3781 auto matcherAsString = m_matcher.toString();
3782 os << Catch::Detail::stringify( m_arg ) << ' ';
3783 if( matcherAsString == Detail::unprintableString )
3784 os << m_matcherString;
3786 os << matcherAsString;
3790 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
3792 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
3794 template<typename ArgT, typename MatcherT>
3795 auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
3796 return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3799 } // namespace Catch
3801 ///////////////////////////////////////////////////////////////////////////////
3802 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3804 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3805 INTERNAL_CATCH_TRY { \
3806 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3807 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3808 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3811 ///////////////////////////////////////////////////////////////////////////////
3812 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3814 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3815 if( catchAssertionHandler.allowThrows() ) \
3817 static_cast<void>(__VA_ARGS__ ); \
3818 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3820 catch( exceptionType const& ex ) { \
3821 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3824 catchAssertionHandler.handleUnexpectedInflightException(); \
3827 catchAssertionHandler.handleThrowingCallSkipped(); \
3828 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3831 // end catch_capture_matchers.h
3833 // start catch_generators.hpp
3835 // start catch_interfaces_generatortracker.h
3842 namespace Generators {
3843 class GeneratorUntypedBase {
3845 GeneratorUntypedBase() = default;
3846 virtual ~GeneratorUntypedBase();
3847 // Attempts to move the generator to the next element
3849 // Returns true iff the move succeeded (and a valid element
3850 // can be retrieved).
3851 virtual bool next() = 0;
3853 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3855 } // namespace Generators
3857 struct IGeneratorTracker {
3858 virtual ~IGeneratorTracker();
3859 virtual auto hasGenerator() const -> bool = 0;
3860 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3861 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3864 } // namespace Catch
3866 // end catch_interfaces_generatortracker.h
3867 // start catch_enforce.h
3869 #include <exception>
3872 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3873 template <typename Ex>
3875 void throw_exception(Ex const& e) {
3878 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
3880 void throw_exception(std::exception const& e);
3884 void throw_logic_error(std::string const& msg);
3886 void throw_domain_error(std::string const& msg);
3888 void throw_runtime_error(std::string const& msg);
3890 } // namespace Catch;
3892 #define CATCH_MAKE_MSG(...) \
3893 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3895 #define CATCH_INTERNAL_ERROR(...) \
3896 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3898 #define CATCH_ERROR(...) \
3899 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3901 #define CATCH_RUNTIME_ERROR(...) \
3902 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3904 #define CATCH_ENFORCE( condition, ... ) \
3905 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3907 // end catch_enforce.h
3913 #include <exception>
3917 class GeneratorException : public std::exception {
3918 const char* const m_msg = "";
3921 GeneratorException(const char* msg):
3925 const char* what() const noexcept override final;
3928 namespace Generators {
3930 // !TBD move this into its own location?
3932 template<typename T, typename... Args>
3933 std::unique_ptr<T> make_unique( Args&&... args ) {
3934 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3938 template<typename T>
3939 struct IGenerator : GeneratorUntypedBase {
3940 virtual ~IGenerator() = default;
3942 // Returns the current element of the generator
3944 // \Precondition The generator is either freshly constructed,
3945 // or the last call to `next()` returned true
3946 virtual T const& get() const = 0;
3950 template<typename T>
3951 class SingleValueGenerator final : public IGenerator<T> {
3954 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3956 T const& get() const override {
3959 bool next() override {
3964 template<typename T>
3965 class FixedValuesGenerator final : public IGenerator<T> {
3966 static_assert(!std::is_same<T, bool>::value,
3967 "FixedValuesGenerator does not support bools because of std::vector<bool>"
3968 "specialization, use SingleValue Generator instead.");
3969 std::vector<T> m_values;
3972 FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3974 T const& get() const override {
3975 return m_values[m_idx];
3977 bool next() override {
3979 return m_idx < m_values.size();
3983 template <typename T>
3984 class GeneratorWrapper final {
3985 std::unique_ptr<IGenerator<T>> m_generator;
3987 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3988 m_generator(std::move(generator))
3990 T const& get() const {
3991 return m_generator->get();
3994 return m_generator->next();
3998 template <typename T>
3999 GeneratorWrapper<T> value(T&& value) {
4000 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4002 template <typename T>
4003 GeneratorWrapper<T> values(std::initializer_list<T> values) {
4004 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4007 template<typename T>
4008 class Generators : public IGenerator<T> {
4009 std::vector<GeneratorWrapper<T>> m_generators;
4010 size_t m_current = 0;
4012 void populate(GeneratorWrapper<T>&& generator) {
4013 m_generators.emplace_back(std::move(generator));
4015 void populate(T&& val) {
4016 m_generators.emplace_back(value(std::forward<T>(val)));
4018 template<typename U>
4019 void populate(U&& val) {
4020 populate(T(std::forward<U>(val)));
4022 template<typename U, typename... Gs>
4023 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4024 populate(std::forward<U>(valueOrGenerator));
4025 populate(std::forward<Gs>(moreGenerators)...);
4029 template <typename... Gs>
4030 Generators(Gs &&... moreGenerators) {
4031 m_generators.reserve(sizeof...(Gs));
4032 populate(std::forward<Gs>(moreGenerators)...);
4035 T const& get() const override {
4036 return m_generators[m_current].get();
4039 bool next() override {
4040 if (m_current >= m_generators.size()) {
4043 const bool current_status = m_generators[m_current].next();
4044 if (!current_status) {
4047 return m_current < m_generators.size();
4051 template<typename... Ts>
4052 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
4053 return values<std::tuple<Ts...>>( tuples );
4056 // Tag type to signal that a generator sequence should convert arguments to a specific type
4057 template <typename T>
4060 template<typename T, typename... Gs>
4061 auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
4062 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4064 template<typename T>
4065 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4066 return Generators<T>(std::move(generator));
4068 template<typename T, typename... Gs>
4069 auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4070 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4072 template<typename T, typename U, typename... Gs>
4073 auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4074 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4077 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
4079 template<typename L>
4080 // Note: The type after -> is weird, because VS2015 cannot parse
4081 // the expression used in the typedef inside, when it is in
4082 // return type. Yeah.
4083 auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4084 using UnderlyingType = typename decltype(generatorExpression())::type;
4086 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4087 if (!tracker.hasGenerator()) {
4088 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4091 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
4092 return generator.get();
4095 } // namespace Generators
4096 } // namespace Catch
4098 #define GENERATE( ... ) \
4099 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4100 CATCH_INTERNAL_LINEINFO, \
4101 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4102 #define GENERATE_COPY( ... ) \
4103 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4104 CATCH_INTERNAL_LINEINFO, \
4105 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4106 #define GENERATE_REF( ... ) \
4107 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4108 CATCH_INTERNAL_LINEINFO, \
4109 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4111 // end catch_generators.hpp
4112 // start catch_generators_generic.hpp
4115 namespace Generators {
4117 template <typename T>
4118 class TakeGenerator : public IGenerator<T> {
4119 GeneratorWrapper<T> m_generator;
4120 size_t m_returned = 0;
4123 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4124 m_generator(std::move(generator)),
4127 assert(target != 0 && "Empty generators are not allowed");
4129 T const& get() const override {
4130 return m_generator.get();
4132 bool next() override {
4134 if (m_returned >= m_target) {
4138 const auto success = m_generator.next();
4139 // If the underlying generator does not contain enough values
4140 // then we cut short as well
4142 m_returned = m_target;
4148 template <typename T>
4149 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4150 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4153 template <typename T, typename Predicate>
4154 class FilterGenerator : public IGenerator<T> {
4155 GeneratorWrapper<T> m_generator;
4156 Predicate m_predicate;
4158 template <typename P = Predicate>
4159 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4160 m_generator(std::move(generator)),
4161 m_predicate(std::forward<P>(pred))
4163 if (!m_predicate(m_generator.get())) {
4164 // It might happen that there are no values that pass the
4165 // filter. In that case we throw an exception.
4166 auto has_initial_value = next();
4167 if (!has_initial_value) {
4168 Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4173 T const& get() const override {
4174 return m_generator.get();
4177 bool next() override {
4178 bool success = m_generator.next();
4182 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4187 template <typename T, typename Predicate>
4188 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4189 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4192 template <typename T>
4193 class RepeatGenerator : public IGenerator<T> {
4194 static_assert(!std::is_same<T, bool>::value,
4195 "RepeatGenerator currently does not support bools"
4196 "because of std::vector<bool> specialization");
4197 GeneratorWrapper<T> m_generator;
4198 mutable std::vector<T> m_returned;
4199 size_t m_target_repeats;
4200 size_t m_current_repeat = 0;
4201 size_t m_repeat_index = 0;
4203 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4204 m_generator(std::move(generator)),
4205 m_target_repeats(repeats)
4207 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4210 T const& get() const override {
4211 if (m_current_repeat == 0) {
4212 m_returned.push_back(m_generator.get());
4213 return m_returned.back();
4215 return m_returned[m_repeat_index];
4218 bool next() override {
4219 // There are 2 basic cases:
4220 // 1) We are still reading the generator
4221 // 2) We are reading our own cache
4223 // In the first case, we need to poke the underlying generator.
4224 // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4225 if (m_current_repeat == 0) {
4226 const auto success = m_generator.next();
4230 return m_current_repeat < m_target_repeats;
4233 // In the second case, we need to move indices forward and check that we haven't run up against the end
4235 if (m_repeat_index == m_returned.size()) {
4239 return m_current_repeat < m_target_repeats;
4243 template <typename T>
4244 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4245 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4248 template <typename T, typename U, typename Func>
4249 class MapGenerator : public IGenerator<T> {
4250 // TBD: provide static assert for mapping function, for friendly error message
4251 GeneratorWrapper<U> m_generator;
4253 // To avoid returning dangling reference, we have to save the values
4256 template <typename F2 = Func>
4257 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4258 m_generator(std::move(generator)),
4259 m_function(std::forward<F2>(function)),
4260 m_cache(m_function(m_generator.get()))
4263 T const& get() const override {
4266 bool next() override {
4267 const auto success = m_generator.next();
4269 m_cache = m_function(m_generator.get());
4275 template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4276 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4277 return GeneratorWrapper<T>(
4278 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4282 template <typename T, typename U, typename Func>
4283 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4284 return GeneratorWrapper<T>(
4285 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4289 template <typename T>
4290 class ChunkGenerator final : public IGenerator<std::vector<T>> {
4291 std::vector<T> m_chunk;
4292 size_t m_chunk_size;
4293 GeneratorWrapper<T> m_generator;
4294 bool m_used_up = false;
4296 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4297 m_chunk_size(size), m_generator(std::move(generator))
4299 m_chunk.reserve(m_chunk_size);
4300 if (m_chunk_size != 0) {
4301 m_chunk.push_back(m_generator.get());
4302 for (size_t i = 1; i < m_chunk_size; ++i) {
4303 if (!m_generator.next()) {
4304 Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4306 m_chunk.push_back(m_generator.get());
4310 std::vector<T> const& get() const override {
4313 bool next() override {
4315 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4316 if (!m_generator.next()) {
4319 m_chunk.push_back(m_generator.get());
4325 template <typename T>
4326 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4327 return GeneratorWrapper<std::vector<T>>(
4328 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4332 } // namespace Generators
4333 } // namespace Catch
4335 // end catch_generators_generic.hpp
4336 // start catch_generators_specific.hpp
4338 // start catch_context.h
4344 struct IResultCapture;
4347 struct IMutableContext;
4349 using IConfigPtr = std::shared_ptr<IConfig const>;
4353 virtual ~IContext();
4355 virtual IResultCapture* getResultCapture() = 0;
4356 virtual IRunner* getRunner() = 0;
4357 virtual IConfigPtr const& getConfig() const = 0;
4360 struct IMutableContext : IContext
4362 virtual ~IMutableContext();
4363 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4364 virtual void setRunner( IRunner* runner ) = 0;
4365 virtual void setConfig( IConfigPtr const& config ) = 0;
4368 static IMutableContext *currentContext;
4369 friend IMutableContext& getCurrentMutableContext();
4370 friend void cleanUpContext();
4371 static void createContext();
4374 inline IMutableContext& getCurrentMutableContext()
4376 if( !IMutableContext::currentContext )
4377 IMutableContext::createContext();
4378 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4379 return *IMutableContext::currentContext;
4382 inline IContext& getCurrentContext()
4384 return getCurrentMutableContext();
4387 void cleanUpContext();
4393 // end catch_context.h
4394 // start catch_interfaces_config.h
4396 // start catch_option.hpp
4401 template<typename T>
4404 Option() : nullableValue( nullptr ) {}
4405 Option( T const& _value )
4406 : nullableValue( new( storage ) T( _value ) )
4408 Option( Option const& _other )
4409 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4416 Option& operator= ( Option const& _other ) {
4417 if( &_other != this ) {
4420 nullableValue = new( storage ) T( *_other );
4424 Option& operator = ( T const& _value ) {
4426 nullableValue = new( storage ) T( _value );
4432 nullableValue->~T();
4433 nullableValue = nullptr;
4436 T& operator*() { return *nullableValue; }
4437 T const& operator*() const { return *nullableValue; }
4438 T* operator->() { return nullableValue; }
4439 const T* operator->() const { return nullableValue; }
4441 T valueOr( T const& defaultValue ) const {
4442 return nullableValue ? *nullableValue : defaultValue;
4445 bool some() const { return nullableValue != nullptr; }
4446 bool none() const { return nullableValue == nullptr; }
4448 bool operator !() const { return nullableValue == nullptr; }
4449 explicit operator bool() const {
4455 alignas(alignof(T)) char storage[sizeof(T)];
4458 } // end namespace Catch
4460 // end catch_option.hpp
4469 enum class Verbosity {
4475 struct WarnAbout { enum What {
4477 NoAssertions = 0x01,
4481 struct ShowDurations { enum OrNot {
4486 struct RunTests { enum InWhatOrder {
4488 InLexicographicalOrder,
4491 struct UseColour { enum YesOrNo {
4496 struct WaitForKeypress { enum When {
4500 BeforeStartAndExit = BeforeStart | BeforeExit
4505 struct IConfig : NonCopyable {
4509 virtual bool allowThrows() const = 0;
4510 virtual std::ostream& stream() const = 0;
4511 virtual std::string name() const = 0;
4512 virtual bool includeSuccessfulResults() const = 0;
4513 virtual bool shouldDebugBreak() const = 0;
4514 virtual bool warnAboutMissingAssertions() const = 0;
4515 virtual bool warnAboutNoTests() const = 0;
4516 virtual int abortAfter() const = 0;
4517 virtual bool showInvisibles() const = 0;
4518 virtual ShowDurations::OrNot showDurations() const = 0;
4519 virtual double minDuration() const = 0;
4520 virtual TestSpec const& testSpec() const = 0;
4521 virtual bool hasTestFilters() const = 0;
4522 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4523 virtual RunTests::InWhatOrder runOrder() const = 0;
4524 virtual unsigned int rngSeed() const = 0;
4525 virtual UseColour::YesOrNo useColour() const = 0;
4526 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4527 virtual Verbosity verbosity() const = 0;
4529 virtual bool benchmarkNoAnalysis() const = 0;
4530 virtual int benchmarkSamples() const = 0;
4531 virtual double benchmarkConfidenceInterval() const = 0;
4532 virtual unsigned int benchmarkResamples() const = 0;
4533 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
4536 using IConfigPtr = std::shared_ptr<IConfig const>;
4539 // end catch_interfaces_config.h
4540 // start catch_random_number_generator.h
4546 // This is a simple implementation of C++11 Uniform Random Number
4547 // Generator. It does not provide all operators, because Catch2
4548 // does not use it, but it should behave as expected inside stdlib's
4550 // The implementation is based on the PCG family (http://pcg-random.org)
4552 using state_type = std::uint64_t;
4554 using result_type = std::uint32_t;
4555 static constexpr result_type (min)() {
4558 static constexpr result_type (max)() {
4559 return static_cast<result_type>(-1);
4562 // Provide some default initial state for the default constructor
4563 SimplePcg32():SimplePcg32(0xed743cc4U) {}
4565 explicit SimplePcg32(result_type seed_);
4567 void seed(result_type seed_);
4568 void discard(uint64_t skip);
4570 result_type operator()();
4573 friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4574 friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4576 // In theory we also need operator<< and operator>>
4577 // In practice we do not use them, so we will skip them for now
4579 std::uint64_t m_state;
4580 // This part of the state determines which "stream" of the numbers
4581 // is chosen -- we take it as a constant for Catch2, so we only
4582 // need to deal with seeding the main state.
4583 // Picked by reading 8 bytes from `/dev/random` :-)
4584 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4587 } // end namespace Catch
4589 // end catch_random_number_generator.h
4593 namespace Generators {
4595 template <typename Float>
4596 class RandomFloatingGenerator final : public IGenerator<Float> {
4597 Catch::SimplePcg32& m_rng;
4598 std::uniform_real_distribution<Float> m_dist;
4599 Float m_current_number;
4602 RandomFloatingGenerator(Float a, Float b):
4605 static_cast<void>(next());
4608 Float const& get() const override {
4609 return m_current_number;
4611 bool next() override {
4612 m_current_number = m_dist(m_rng);
4617 template <typename Integer>
4618 class RandomIntegerGenerator final : public IGenerator<Integer> {
4619 Catch::SimplePcg32& m_rng;
4620 std::uniform_int_distribution<Integer> m_dist;
4621 Integer m_current_number;
4624 RandomIntegerGenerator(Integer a, Integer b):
4627 static_cast<void>(next());
4630 Integer const& get() const override {
4631 return m_current_number;
4633 bool next() override {
4634 m_current_number = m_dist(m_rng);
4639 // TODO: Ideally this would be also constrained against the various char types,
4640 // but I don't expect users to run into that in practice.
4641 template <typename T>
4642 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4643 GeneratorWrapper<T>>::type
4645 return GeneratorWrapper<T>(
4646 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4650 template <typename T>
4651 typename std::enable_if<std::is_floating_point<T>::value,
4652 GeneratorWrapper<T>>::type
4654 return GeneratorWrapper<T>(
4655 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4659 template <typename T>
4660 class RangeGenerator final : public IGenerator<T> {
4667 RangeGenerator(T const& start, T const& end, T const& step):
4671 m_positive(m_step > T(0))
4673 assert(m_current != m_end && "Range start and end cannot be equal");
4674 assert(m_step != T(0) && "Step size cannot be zero");
4675 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4678 RangeGenerator(T const& start, T const& end):
4679 RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4682 T const& get() const override {
4686 bool next() override {
4687 m_current += m_step;
4688 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4692 template <typename T>
4693 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4694 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
4695 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4698 template <typename T>
4699 GeneratorWrapper<T> range(T const& start, T const& end) {
4700 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4701 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4704 template <typename T>
4705 class IteratorGenerator final : public IGenerator<T> {
4706 static_assert(!std::is_same<T, bool>::value,
4707 "IteratorGenerator currently does not support bools"
4708 "because of std::vector<bool> specialization");
4710 std::vector<T> m_elems;
4711 size_t m_current = 0;
4713 template <typename InputIterator, typename InputSentinel>
4714 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4715 if (m_elems.empty()) {
4716 Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
4720 T const& get() const override {
4721 return m_elems[m_current];
4724 bool next() override {
4726 return m_current != m_elems.size();
4730 template <typename InputIterator,
4731 typename InputSentinel,
4732 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
4733 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
4734 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
4737 template <typename Container,
4738 typename ResultType = typename Container::value_type>
4739 GeneratorWrapper<ResultType> from_range(Container const& cnt) {
4740 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4743 } // namespace Generators
4744 } // namespace Catch
4746 // end catch_generators_specific.hpp
4748 // These files are included here so the single_include script doesn't put them
4749 // in the conditionally compiled sections
4750 // start catch_test_case_info.h
4757 #pragma clang diagnostic push
4758 #pragma clang diagnostic ignored "-Wpadded"
4763 struct ITestInvoker;
4765 struct TestCaseInfo {
4766 enum SpecialProperties{
4769 ShouldFail = 1 << 2,
4772 NonPortable = 1 << 5,
4776 TestCaseInfo( std::string const& _name,
4777 std::string const& _className,
4778 std::string const& _description,
4779 std::vector<std::string> const& _tags,
4780 SourceLineInfo const& _lineInfo );
4782 friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4784 bool isHidden() const;
4785 bool throws() const;
4786 bool okToFail() const;
4787 bool expectedToFail() const;
4789 std::string tagsAsString() const;
4792 std::string className;
4793 std::string description;
4794 std::vector<std::string> tags;
4795 std::vector<std::string> lcaseTags;
4796 SourceLineInfo lineInfo;
4797 SpecialProperties properties;
4800 class TestCase : public TestCaseInfo {
4803 TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4805 TestCase withName( std::string const& _newName ) const;
4807 void invoke() const;
4809 TestCaseInfo const& getTestCaseInfo() const;
4811 bool operator == ( TestCase const& other ) const;
4812 bool operator < ( TestCase const& other ) const;
4815 std::shared_ptr<ITestInvoker> test;
4818 TestCase makeTestCase( ITestInvoker* testCase,
4819 std::string const& className,
4820 NameAndTags const& nameAndTags,
4821 SourceLineInfo const& lineInfo );
4825 #pragma clang diagnostic pop
4828 // end catch_test_case_info.h
4829 // start catch_interfaces_runner.h
4835 virtual bool aborting() const = 0;
4839 // end catch_interfaces_runner.h
4842 // start catch_objc.hpp
4844 #import <objc/runtime.h>
4848 // NB. Any general catch headers included here must be included
4849 // in catch.hpp first to make sure they are included by the single
4850 // header for non obj-usage
4852 ///////////////////////////////////////////////////////////////////////////////
4853 // This protocol is really only here for (self) documenting purposes, since
4854 // all its methods are optional.
4866 class OcMethod : public ITestInvoker {
4869 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4871 virtual void invoke() const {
4872 id obj = [[m_cls alloc] init];
4874 performOptionalSelector( obj, @selector(setUp) );
4875 performOptionalSelector( obj, m_sel );
4876 performOptionalSelector( obj, @selector(tearDown) );
4878 arcSafeRelease( obj );
4881 virtual ~OcMethod() {}
4889 inline std::string getAnnotation( Class cls,
4890 std::string const& annotationName,
4891 std::string const& testCaseName ) {
4892 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4893 SEL sel = NSSelectorFromString( selStr );
4894 arcSafeRelease( selStr );
4895 id value = performOptionalSelector( cls, sel );
4897 return [(NSString*)value UTF8String];
4902 inline std::size_t registerTestMethods() {
4903 std::size_t noTestMethods = 0;
4904 int noClasses = objc_getClassList( nullptr, 0 );
4906 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4907 objc_getClassList( classes, noClasses );
4909 for( int c = 0; c < noClasses; c++ ) {
4910 Class cls = classes[c];
4913 Method* methods = class_copyMethodList( cls, &count );
4914 for( u_int m = 0; m < count ; m++ ) {
4915 SEL selector = method_getName(methods[m]);
4916 std::string methodName = sel_getName(selector);
4917 if( startsWith( methodName, "Catch_TestCase_" ) ) {
4918 std::string testCaseName = methodName.substr( 15 );
4919 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4920 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4921 const char* className = class_getName( cls );
4923 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4930 return noTestMethods;
4933 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4935 namespace Matchers {
4937 namespace NSStringMatchers {
4939 struct StringHolder : MatcherBase<NSString*>{
4940 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4941 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
4943 arcSafeRelease( m_substr );
4946 bool match( NSString* str ) const override {
4950 NSString* CATCH_ARC_STRONG m_substr;
4953 struct Equals : StringHolder {
4954 Equals( NSString* substr ) : StringHolder( substr ){}
4956 bool match( NSString* str ) const override {
4957 return (str != nil || m_substr == nil ) &&
4958 [str isEqualToString:m_substr];
4961 std::string describe() const override {
4962 return "equals string: " + Catch::Detail::stringify( m_substr );
4966 struct Contains : StringHolder {
4967 Contains( NSString* substr ) : StringHolder( substr ){}
4969 bool match( NSString* str ) const override {
4970 return (str != nil || m_substr == nil ) &&
4971 [str rangeOfString:m_substr].location != NSNotFound;
4974 std::string describe() const override {
4975 return "contains string: " + Catch::Detail::stringify( m_substr );
4979 struct StartsWith : StringHolder {
4980 StartsWith( NSString* substr ) : StringHolder( substr ){}
4982 bool match( NSString* str ) const override {
4983 return (str != nil || m_substr == nil ) &&
4984 [str rangeOfString:m_substr].location == 0;
4987 std::string describe() const override {
4988 return "starts with: " + Catch::Detail::stringify( m_substr );
4991 struct EndsWith : StringHolder {
4992 EndsWith( NSString* substr ) : StringHolder( substr ){}
4994 bool match( NSString* str ) const override {
4995 return (str != nil || m_substr == nil ) &&
4996 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4999 std::string describe() const override {
5000 return "ends with: " + Catch::Detail::stringify( m_substr );
5004 } // namespace NSStringMatchers
5007 inline Impl::NSStringMatchers::Equals
5008 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
5010 inline Impl::NSStringMatchers::Contains
5011 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
5013 inline Impl::NSStringMatchers::StartsWith
5014 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
5016 inline Impl::NSStringMatchers::EndsWith
5017 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
5019 } // namespace Matchers
5021 using namespace Matchers;
5023 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5025 } // namespace Catch
5027 ///////////////////////////////////////////////////////////////////////////////
5028 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5029 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5030 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5034 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5038 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5040 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5042 // end catch_objc.hpp
5045 // Benchmarking needs the externally-facing parts of reporters to work
5046 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5047 // start catch_external_interfaces.h
5049 // start catch_reporter_bases.hpp
5051 // start catch_interfaces_reporter.h
5053 // start catch_config.hpp
5055 // start catch_test_spec_parser.h
5058 #pragma clang diagnostic push
5059 #pragma clang diagnostic ignored "-Wpadded"
5062 // start catch_test_spec.h
5065 #pragma clang diagnostic push
5066 #pragma clang diagnostic ignored "-Wpadded"
5069 // start catch_wildcard_pattern.h
5073 class WildcardPattern {
5074 enum WildcardPosition {
5076 WildcardAtStart = 1,
5078 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5083 WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
5084 virtual ~WildcardPattern() = default;
5085 virtual bool matches( std::string const& str ) const;
5088 std::string normaliseString( std::string const& str ) const;
5089 CaseSensitive::Choice m_caseSensitivity;
5090 WildcardPosition m_wildcard = NoWildcard;
5091 std::string m_pattern;
5095 // end catch_wildcard_pattern.h
5107 explicit Pattern( std::string const& name );
5109 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
5110 std::string const& name() const;
5112 std::string const m_name;
5114 using PatternPtr = std::shared_ptr<Pattern>;
5116 class NamePattern : public Pattern {
5118 explicit NamePattern( std::string const& name, std::string const& filterString );
5119 bool matches( TestCaseInfo const& testCase ) const override;
5121 WildcardPattern m_wildcardPattern;
5124 class TagPattern : public Pattern {
5126 explicit TagPattern( std::string const& tag, std::string const& filterString );
5127 bool matches( TestCaseInfo const& testCase ) const override;
5132 class ExcludedPattern : public Pattern {
5134 explicit ExcludedPattern( PatternPtr const& underlyingPattern );
5135 bool matches( TestCaseInfo const& testCase ) const override;
5137 PatternPtr m_underlyingPattern;
5141 std::vector<PatternPtr> m_patterns;
5143 bool matches( TestCaseInfo const& testCase ) const;
5144 std::string name() const;
5148 struct FilterMatch {
5150 std::vector<TestCase const*> tests;
5152 using Matches = std::vector<FilterMatch>;
5153 using vectorStrings = std::vector<std::string>;
5155 bool hasFilters() const;
5156 bool matches( TestCaseInfo const& testCase ) const;
5157 Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
5158 const vectorStrings & getInvalidArgs() const;
5161 std::vector<Filter> m_filters;
5162 std::vector<std::string> m_invalidArgs;
5163 friend class TestSpecParser;
5168 #pragma clang diagnostic pop
5171 // end catch_test_spec.h
5172 // start catch_interfaces_tag_alias_registry.h
5180 struct ITagAliasRegistry {
5181 virtual ~ITagAliasRegistry();
5182 // Nullptr if not present
5183 virtual TagAlias const* find( std::string const& alias ) const = 0;
5184 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
5186 static ITagAliasRegistry const& get();
5189 } // end namespace Catch
5191 // end catch_interfaces_tag_alias_registry.h
5194 class TestSpecParser {
5195 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5197 Mode lastMode = None;
5198 bool m_exclusion = false;
5199 std::size_t m_pos = 0;
5200 std::size_t m_realPatternPos = 0;
5202 std::string m_substring;
5203 std::string m_patternName;
5204 std::vector<std::size_t> m_escapeChars;
5205 TestSpec::Filter m_currentFilter;
5206 TestSpec m_testSpec;
5207 ITagAliasRegistry const* m_tagAliases = nullptr;
5210 TestSpecParser( ITagAliasRegistry const& tagAliases );
5212 TestSpecParser& parse( std::string const& arg );
5213 TestSpec testSpec();
5216 bool visitChar( char c );
5217 void startNewMode( Mode mode );
5218 bool processNoneChar( char c );
5219 void processNameChar( char c );
5220 bool processOtherChar( char c );
5223 bool isControlChar( char c ) const;
5224 void saveLastMode();
5225 void revertBackToLastMode();
5229 // Handles common preprocessing of the pattern for name/tag patterns
5230 std::string preprocessPattern();
5231 // Adds the current pattern as a test name
5232 void addNamePattern();
5233 // Adds the current pattern as a tag
5234 void addTagPattern();
5236 inline void addCharToPattern(char c) {
5243 TestSpec parseTestSpec( std::string const& arg );
5245 } // namespace Catch
5248 #pragma clang diagnostic pop
5251 // end catch_test_spec_parser.h
5252 // Libstdc++ doesn't like incomplete classes for unique_ptr
5258 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5259 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5267 bool listTests = false;
5268 bool listTags = false;
5269 bool listReporters = false;
5270 bool listTestNamesOnly = false;
5272 bool showSuccessfulTests = false;
5273 bool shouldDebugBreak = false;
5274 bool noThrow = false;
5275 bool showHelp = false;
5276 bool showInvisibles = false;
5277 bool filenamesAsTags = false;
5278 bool libIdentify = false;
5280 int abortAfter = -1;
5281 unsigned int rngSeed = 0;
5283 bool benchmarkNoAnalysis = false;
5284 unsigned int benchmarkSamples = 100;
5285 double benchmarkConfidenceInterval = 0.95;
5286 unsigned int benchmarkResamples = 100000;
5287 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5289 Verbosity verbosity = Verbosity::Normal;
5290 WarnAbout::What warnings = WarnAbout::Nothing;
5291 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5292 double minDuration = -1;
5293 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5294 UseColour::YesOrNo useColour = UseColour::Auto;
5295 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5297 std::string outputFilename;
5299 std::string processName;
5300 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5301 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5303 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5304 #undef CATCH_CONFIG_DEFAULT_REPORTER
5306 std::vector<std::string> testsOrTags;
5307 std::vector<std::string> sectionsToRun;
5310 class Config : public IConfig {
5314 Config( ConfigData const& data );
5315 virtual ~Config() = default;
5317 std::string const& getFilename() const;
5319 bool listTests() const;
5320 bool listTestNamesOnly() const;
5321 bool listTags() const;
5322 bool listReporters() const;
5324 std::string getProcessName() const;
5325 std::string const& getReporterName() const;
5327 std::vector<std::string> const& getTestsOrTags() const override;
5328 std::vector<std::string> const& getSectionsToRun() const override;
5330 TestSpec const& testSpec() const override;
5331 bool hasTestFilters() const override;
5333 bool showHelp() const;
5335 // IConfig interface
5336 bool allowThrows() const override;
5337 std::ostream& stream() const override;
5338 std::string name() const override;
5339 bool includeSuccessfulResults() const override;
5340 bool warnAboutMissingAssertions() const override;
5341 bool warnAboutNoTests() const override;
5342 ShowDurations::OrNot showDurations() const override;
5343 double minDuration() const override;
5344 RunTests::InWhatOrder runOrder() const override;
5345 unsigned int rngSeed() const override;
5346 UseColour::YesOrNo useColour() const override;
5347 bool shouldDebugBreak() const override;
5348 int abortAfter() const override;
5349 bool showInvisibles() const override;
5350 Verbosity verbosity() const override;
5351 bool benchmarkNoAnalysis() const override;
5352 int benchmarkSamples() const override;
5353 double benchmarkConfidenceInterval() const override;
5354 unsigned int benchmarkResamples() const override;
5355 std::chrono::milliseconds benchmarkWarmupTime() const override;
5359 IStream const* openStream();
5362 std::unique_ptr<IStream const> m_stream;
5363 TestSpec m_testSpec;
5364 bool m_hasTestFilters = false;
5367 } // end namespace Catch
5369 // end catch_config.hpp
5370 // start catch_assertionresult.h
5376 struct AssertionResultData
5378 AssertionResultData() = delete;
5380 AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5382 std::string message;
5383 mutable std::string reconstructedExpression;
5384 LazyExpression lazyExpression;
5385 ResultWas::OfType resultType;
5387 std::string reconstructExpression() const;
5390 class AssertionResult {
5392 AssertionResult() = delete;
5393 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5396 bool succeeded() const;
5397 ResultWas::OfType getResultType() const;
5398 bool hasExpression() const;
5399 bool hasMessage() const;
5400 std::string getExpression() const;
5401 std::string getExpressionInMacro() const;
5402 bool hasExpandedExpression() const;
5403 std::string getExpandedExpression() const;
5404 std::string getMessage() const;
5405 SourceLineInfo getSourceInfo() const;
5406 StringRef getTestMacroName() const;
5409 AssertionInfo m_info;
5410 AssertionResultData m_resultData;
5413 } // end namespace Catch
5415 // end catch_assertionresult.h
5416 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5417 // start catch_estimate.hpp
5419 // Statistics estimates
5423 namespace Benchmark {
5424 template <typename Duration>
5427 Duration lower_bound;
5428 Duration upper_bound;
5429 double confidence_interval;
5431 template <typename Duration2>
5432 operator Estimate<Duration2>() const {
5433 return { point, lower_bound, upper_bound, confidence_interval };
5436 } // namespace Benchmark
5437 } // namespace Catch
5439 // end catch_estimate.hpp
5440 // start catch_outlier_classification.hpp
5442 // Outlier information
5445 namespace Benchmark {
5446 struct OutlierClassification {
5447 int samples_seen = 0;
5448 int low_severe = 0; // more than 3 times IQR below Q1
5449 int low_mild = 0; // 1.5 to 3 times IQR below Q1
5450 int high_mild = 0; // 1.5 to 3 times IQR above Q3
5451 int high_severe = 0; // more than 3 times IQR above Q3
5454 return low_severe + low_mild + high_mild + high_severe;
5457 } // namespace Benchmark
5458 } // namespace Catch
5460 // end catch_outlier_classification.hpp
5461 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5468 #include <algorithm>
5472 struct ReporterConfig {
5473 explicit ReporterConfig( IConfigPtr const& _fullConfig );
5475 ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5477 std::ostream& stream() const;
5478 IConfigPtr fullConfig() const;
5481 std::ostream* m_stream;
5482 IConfigPtr m_fullConfig;
5485 struct ReporterPreferences {
5486 bool shouldRedirectStdOut = false;
5487 bool shouldReportAllAssertions = false;
5490 template<typename T>
5491 struct LazyStat : Option<T> {
5492 LazyStat& operator=( T const& _value ) {
5493 Option<T>::operator=( _value );
5504 struct TestRunInfo {
5505 TestRunInfo( std::string const& _name );
5509 GroupInfo( std::string const& _name,
5510 std::size_t _groupIndex,
5511 std::size_t _groupsCount );
5514 std::size_t groupIndex;
5515 std::size_t groupsCounts;
5518 struct AssertionStats {
5519 AssertionStats( AssertionResult const& _assertionResult,
5520 std::vector<MessageInfo> const& _infoMessages,
5521 Totals const& _totals );
5523 AssertionStats( AssertionStats const& ) = default;
5524 AssertionStats( AssertionStats && ) = default;
5525 AssertionStats& operator = ( AssertionStats const& ) = delete;
5526 AssertionStats& operator = ( AssertionStats && ) = delete;
5527 virtual ~AssertionStats();
5529 AssertionResult assertionResult;
5530 std::vector<MessageInfo> infoMessages;
5534 struct SectionStats {
5535 SectionStats( SectionInfo const& _sectionInfo,
5536 Counts const& _assertions,
5537 double _durationInSeconds,
5538 bool _missingAssertions );
5539 SectionStats( SectionStats const& ) = default;
5540 SectionStats( SectionStats && ) = default;
5541 SectionStats& operator = ( SectionStats const& ) = default;
5542 SectionStats& operator = ( SectionStats && ) = default;
5543 virtual ~SectionStats();
5545 SectionInfo sectionInfo;
5547 double durationInSeconds;
5548 bool missingAssertions;
5551 struct TestCaseStats {
5552 TestCaseStats( TestCaseInfo const& _testInfo,
5553 Totals const& _totals,
5554 std::string const& _stdOut,
5555 std::string const& _stdErr,
5558 TestCaseStats( TestCaseStats const& ) = default;
5559 TestCaseStats( TestCaseStats && ) = default;
5560 TestCaseStats& operator = ( TestCaseStats const& ) = default;
5561 TestCaseStats& operator = ( TestCaseStats && ) = default;
5562 virtual ~TestCaseStats();
5564 TestCaseInfo testInfo;
5571 struct TestGroupStats {
5572 TestGroupStats( GroupInfo const& _groupInfo,
5573 Totals const& _totals,
5575 TestGroupStats( GroupInfo const& _groupInfo );
5577 TestGroupStats( TestGroupStats const& ) = default;
5578 TestGroupStats( TestGroupStats && ) = default;
5579 TestGroupStats& operator = ( TestGroupStats const& ) = default;
5580 TestGroupStats& operator = ( TestGroupStats && ) = default;
5581 virtual ~TestGroupStats();
5583 GroupInfo groupInfo;
5588 struct TestRunStats {
5589 TestRunStats( TestRunInfo const& _runInfo,
5590 Totals const& _totals,
5593 TestRunStats( TestRunStats const& ) = default;
5594 TestRunStats( TestRunStats && ) = default;
5595 TestRunStats& operator = ( TestRunStats const& ) = default;
5596 TestRunStats& operator = ( TestRunStats && ) = default;
5597 virtual ~TestRunStats();
5599 TestRunInfo runInfo;
5604 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5605 struct BenchmarkInfo {
5607 double estimatedDuration;
5610 unsigned int resamples;
5611 double clockResolution;
5615 template <class Duration>
5616 struct BenchmarkStats {
5619 std::vector<Duration> samples;
5620 Benchmark::Estimate<Duration> mean;
5621 Benchmark::Estimate<Duration> standardDeviation;
5622 Benchmark::OutlierClassification outliers;
5623 double outlierVariance;
5625 template <typename Duration2>
5626 operator BenchmarkStats<Duration2>() const {
5627 std::vector<Duration2> samples2;
5628 samples2.reserve(samples.size());
5629 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5632 std::move(samples2),
5640 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5642 struct IStreamingReporter {
5643 virtual ~IStreamingReporter() = default;
5645 // Implementing class must also provide the following static methods:
5646 // static std::string getDescription();
5647 // static std::set<Verbosity> getSupportedVerbosities()
5649 virtual ReporterPreferences getPreferences() const = 0;
5651 virtual void noMatchingTestCases( std::string const& spec ) = 0;
5653 virtual void reportInvalidArguments(std::string const&) {}
5655 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5656 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5658 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5659 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5661 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5662 virtual void benchmarkPreparing( std::string const& ) {}
5663 virtual void benchmarkStarting( BenchmarkInfo const& ) {}
5664 virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
5665 virtual void benchmarkFailed( std::string const& ) {}
5666 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5668 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5670 // The return value indicates if the messages buffer should be cleared:
5671 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5673 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5674 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5675 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5676 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5678 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5680 // Default empty implementation provided
5681 virtual void fatalErrorEncountered( StringRef name );
5683 virtual bool isMulti() const;
5685 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5687 struct IReporterFactory {
5688 virtual ~IReporterFactory();
5689 virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5690 virtual std::string getDescription() const = 0;
5692 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5694 struct IReporterRegistry {
5695 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5696 using Listeners = std::vector<IReporterFactoryPtr>;
5698 virtual ~IReporterRegistry();
5699 virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5700 virtual FactoryMap const& getFactories() const = 0;
5701 virtual Listeners const& getListeners() const = 0;
5704 } // end namespace Catch
5706 // end catch_interfaces_reporter.h
5707 #include <algorithm>
5716 void prepareExpandedExpression(AssertionResult& result);
5718 // Returns double formatted as %.3f (format expected on output)
5719 std::string getFormattedDuration( double duration );
5721 //! Should the reporter show
5722 bool shouldShowDuration( IConfig const& config, double duration );
5724 std::string serializeFilters( std::vector<std::string> const& container );
5726 template<typename DerivedT>
5727 struct StreamingReporterBase : IStreamingReporter {
5729 StreamingReporterBase( ReporterConfig const& _config )
5730 : m_config( _config.fullConfig() ),
5731 stream( _config.stream() )
5733 m_reporterPrefs.shouldRedirectStdOut = false;
5734 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5735 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5738 ReporterPreferences getPreferences() const override {
5739 return m_reporterPrefs;
5742 static std::set<Verbosity> getSupportedVerbosities() {
5743 return { Verbosity::Normal };
5746 ~StreamingReporterBase() override = default;
5748 void noMatchingTestCases(std::string const&) override {}
5750 void reportInvalidArguments(std::string const&) override {}
5752 void testRunStarting(TestRunInfo const& _testRunInfo) override {
5753 currentTestRunInfo = _testRunInfo;
5756 void testGroupStarting(GroupInfo const& _groupInfo) override {
5757 currentGroupInfo = _groupInfo;
5760 void testCaseStarting(TestCaseInfo const& _testInfo) override {
5761 currentTestCaseInfo = _testInfo;
5763 void sectionStarting(SectionInfo const& _sectionInfo) override {
5764 m_sectionStack.push_back(_sectionInfo);
5767 void sectionEnded(SectionStats const& /* _sectionStats */) override {
5768 m_sectionStack.pop_back();
5770 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5771 currentTestCaseInfo.reset();
5773 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5774 currentGroupInfo.reset();
5776 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5777 currentTestCaseInfo.reset();
5778 currentGroupInfo.reset();
5779 currentTestRunInfo.reset();
5782 void skipTest(TestCaseInfo const&) override {
5783 // Don't do anything with this by default.
5784 // It can optionally be overridden in the derived class.
5787 IConfigPtr m_config;
5788 std::ostream& stream;
5790 LazyStat<TestRunInfo> currentTestRunInfo;
5791 LazyStat<GroupInfo> currentGroupInfo;
5792 LazyStat<TestCaseInfo> currentTestCaseInfo;
5794 std::vector<SectionInfo> m_sectionStack;
5795 ReporterPreferences m_reporterPrefs;
5798 template<typename DerivedT>
5799 struct CumulativeReporterBase : IStreamingReporter {
5800 template<typename T, typename ChildNodeT>
5802 explicit Node( T const& _value ) : value( _value ) {}
5805 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5807 ChildNodes children;
5809 struct SectionNode {
5810 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5811 virtual ~SectionNode() = default;
5813 bool operator == (SectionNode const& other) const {
5814 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5816 bool operator == (std::shared_ptr<SectionNode> const& other) const {
5817 return operator==(*other);
5821 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5822 using Assertions = std::vector<AssertionStats>;
5823 ChildSections childSections;
5824 Assertions assertions;
5829 struct BySectionInfo {
5830 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
5831 BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
5832 bool operator() (std::shared_ptr<SectionNode> const& node) const {
5833 return ((node->stats.sectionInfo.name == m_other.name) &&
5834 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5836 void operator=(BySectionInfo const&) = delete;
5839 SectionInfo const& m_other;
5842 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5843 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5844 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5846 CumulativeReporterBase( ReporterConfig const& _config )
5847 : m_config( _config.fullConfig() ),
5848 stream( _config.stream() )
5850 m_reporterPrefs.shouldRedirectStdOut = false;
5851 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5852 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5854 ~CumulativeReporterBase() override = default;
5856 ReporterPreferences getPreferences() const override {
5857 return m_reporterPrefs;
5860 static std::set<Verbosity> getSupportedVerbosities() {
5861 return { Verbosity::Normal };
5864 void testRunStarting( TestRunInfo const& ) override {}
5865 void testGroupStarting( GroupInfo const& ) override {}
5867 void testCaseStarting( TestCaseInfo const& ) override {}
5869 void sectionStarting( SectionInfo const& sectionInfo ) override {
5870 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5871 std::shared_ptr<SectionNode> node;
5872 if( m_sectionStack.empty() ) {
5873 if( !m_rootSection )
5874 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5875 node = m_rootSection;
5878 SectionNode& parentNode = *m_sectionStack.back();
5880 std::find_if( parentNode.childSections.begin(),
5881 parentNode.childSections.end(),
5882 BySectionInfo( sectionInfo ) );
5883 if( it == parentNode.childSections.end() ) {
5884 node = std::make_shared<SectionNode>( incompleteStats );
5885 parentNode.childSections.push_back( node );
5890 m_sectionStack.push_back( node );
5891 m_deepestSection = std::move(node);
5894 void assertionStarting(AssertionInfo const&) override {}
5896 bool assertionEnded(AssertionStats const& assertionStats) override {
5897 assert(!m_sectionStack.empty());
5898 // AssertionResult holds a pointer to a temporary DecomposedExpression,
5899 // which getExpandedExpression() calls to build the expression string.
5900 // Our section stack copy of the assertionResult will likely outlive the
5901 // temporary, so it must be expanded or discarded now to avoid calling
5902 // a destroyed object later.
5903 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5904 SectionNode& sectionNode = *m_sectionStack.back();
5905 sectionNode.assertions.push_back(assertionStats);
5908 void sectionEnded(SectionStats const& sectionStats) override {
5909 assert(!m_sectionStack.empty());
5910 SectionNode& node = *m_sectionStack.back();
5911 node.stats = sectionStats;
5912 m_sectionStack.pop_back();
5914 void testCaseEnded(TestCaseStats const& testCaseStats) override {
5915 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5916 assert(m_sectionStack.size() == 0);
5917 node->children.push_back(m_rootSection);
5918 m_testCases.push_back(node);
5919 m_rootSection.reset();
5921 assert(m_deepestSection);
5922 m_deepestSection->stdOut = testCaseStats.stdOut;
5923 m_deepestSection->stdErr = testCaseStats.stdErr;
5925 void testGroupEnded(TestGroupStats const& testGroupStats) override {
5926 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5927 node->children.swap(m_testCases);
5928 m_testGroups.push_back(node);
5930 void testRunEnded(TestRunStats const& testRunStats) override {
5931 auto node = std::make_shared<TestRunNode>(testRunStats);
5932 node->children.swap(m_testGroups);
5933 m_testRuns.push_back(node);
5934 testRunEndedCumulative();
5936 virtual void testRunEndedCumulative() = 0;
5938 void skipTest(TestCaseInfo const&) override {}
5940 IConfigPtr m_config;
5941 std::ostream& stream;
5942 std::vector<AssertionStats> m_assertions;
5943 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5944 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5945 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5947 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5949 std::shared_ptr<SectionNode> m_rootSection;
5950 std::shared_ptr<SectionNode> m_deepestSection;
5951 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5952 ReporterPreferences m_reporterPrefs;
5956 char const* getLineOfChars() {
5957 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5959 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5960 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5965 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5966 TestEventListenerBase( ReporterConfig const& _config );
5968 static std::set<Verbosity> getSupportedVerbosities();
5970 void assertionStarting(AssertionInfo const&) override;
5971 bool assertionEnded(AssertionStats const&) override;
5974 } // end namespace Catch
5976 // end catch_reporter_bases.hpp
5977 // start catch_console_colour.h
5995 BrightRed = Bright | Red,
5996 BrightGreen = Bright | Green,
5997 LightGrey = Bright | Grey,
5998 BrightWhite = Bright | White,
5999 BrightYellow = Bright | Yellow,
6002 FileName = LightGrey,
6003 Warning = BrightYellow,
6004 ResultError = BrightRed,
6005 ResultSuccess = BrightGreen,
6006 ResultExpectedFailure = Warning,
6011 OriginalExpression = Cyan,
6012 ReconstructedExpression = BrightYellow,
6014 SecondaryText = LightGrey,
6018 // Use constructed object for RAII guard
6019 Colour( Code _colourCode );
6020 Colour( Colour&& other ) noexcept;
6021 Colour& operator=( Colour&& other ) noexcept;
6024 // Use static method for one-shot changes
6025 static void use( Code _colourCode );
6028 bool m_moved = false;
6031 std::ostream& operator << ( std::ostream& os, Colour const& );
6033 } // end namespace Catch
6035 // end catch_console_colour.h
6036 // start catch_reporter_registrars.hpp
6041 template<typename T>
6042 class ReporterRegistrar {
6044 class ReporterFactory : public IReporterFactory {
6046 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6047 return std::unique_ptr<T>( new T( config ) );
6050 std::string getDescription() const override {
6051 return T::getDescription();
6057 explicit ReporterRegistrar( std::string const& name ) {
6058 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6062 template<typename T>
6063 class ListenerRegistrar {
6065 class ListenerFactory : public IReporterFactory {
6067 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6068 return std::unique_ptr<T>( new T( config ) );
6070 std::string getDescription() const override {
6071 return std::string();
6077 ListenerRegistrar() {
6078 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6083 #if !defined(CATCH_CONFIG_DISABLE)
6085 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
6086 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6087 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6088 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6089 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6091 #define CATCH_REGISTER_LISTENER( listenerType ) \
6092 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6093 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6094 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6095 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6096 #else // CATCH_CONFIG_DISABLE
6098 #define CATCH_REGISTER_REPORTER(name, reporterType)
6099 #define CATCH_REGISTER_LISTENER(listenerType)
6101 #endif // CATCH_CONFIG_DISABLE
6103 // end catch_reporter_registrars.hpp
6104 // Allow users to base their work off existing reporters
6105 // start catch_reporter_compact.h
6109 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6111 using StreamingReporterBase::StreamingReporterBase;
6113 ~CompactReporter() override;
6115 static std::string getDescription();
6117 void noMatchingTestCases(std::string const& spec) override;
6119 void assertionStarting(AssertionInfo const&) override;
6121 bool assertionEnded(AssertionStats const& _assertionStats) override;
6123 void sectionEnded(SectionStats const& _sectionStats) override;
6125 void testRunEnded(TestRunStats const& _testRunStats) override;
6129 } // end namespace Catch
6131 // end catch_reporter_compact.h
6132 // start catch_reporter_console.h
6134 #if defined(_MSC_VER)
6135 #pragma warning(push)
6136 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
6137 // Note that 4062 (not all labels are handled
6138 // and default is missing) is enabled
6143 struct SummaryColumn;
6146 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6147 std::unique_ptr<TablePrinter> m_tablePrinter;
6149 ConsoleReporter(ReporterConfig const& config);
6150 ~ConsoleReporter() override;
6151 static std::string getDescription();
6153 void noMatchingTestCases(std::string const& spec) override;
6155 void reportInvalidArguments(std::string const&arg) override;
6157 void assertionStarting(AssertionInfo const&) override;
6159 bool assertionEnded(AssertionStats const& _assertionStats) override;
6161 void sectionStarting(SectionInfo const& _sectionInfo) override;
6162 void sectionEnded(SectionStats const& _sectionStats) override;
6164 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6165 void benchmarkPreparing(std::string const& name) override;
6166 void benchmarkStarting(BenchmarkInfo const& info) override;
6167 void benchmarkEnded(BenchmarkStats<> const& stats) override;
6168 void benchmarkFailed(std::string const& error) override;
6169 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6171 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6172 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6173 void testRunEnded(TestRunStats const& _testRunStats) override;
6174 void testRunStarting(TestRunInfo const& _testRunInfo) override;
6179 void lazyPrintWithoutClosingBenchmarkTable();
6180 void lazyPrintRunInfo();
6181 void lazyPrintGroupInfo();
6182 void printTestCaseAndSectionHeader();
6184 void printClosedHeader(std::string const& _name);
6185 void printOpenHeader(std::string const& _name);
6187 // if string has a : in first line will set indent to follow it on
6189 void printHeaderString(std::string const& _string, std::size_t indent = 0);
6191 void printTotals(Totals const& totals);
6192 void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
6194 void printTotalsDivider(Totals const& totals);
6195 void printSummaryDivider();
6196 void printTestFilters();
6199 bool m_headerPrinted = false;
6202 } // end namespace Catch
6204 #if defined(_MSC_VER)
6205 #pragma warning(pop)
6208 // end catch_reporter_console.h
6209 // start catch_reporter_junit.h
6211 // start catch_xmlwriter.h
6216 enum class XmlFormatting {
6222 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6223 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6227 enum ForWhat { ForTextNodes, ForAttributes };
6229 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6231 void encodeTo( std::ostream& os ) const;
6233 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6243 class ScopedElement {
6245 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6247 ScopedElement( ScopedElement&& other ) noexcept;
6248 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6252 ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6254 template<typename T>
6255 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6256 m_writer->writeAttribute( name, attribute );
6261 mutable XmlWriter* m_writer = nullptr;
6262 XmlFormatting m_fmt;
6265 XmlWriter( std::ostream& os = Catch::cout() );
6268 XmlWriter( XmlWriter const& ) = delete;
6269 XmlWriter& operator=( XmlWriter const& ) = delete;
6271 XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6273 ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6275 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6277 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6279 XmlWriter& writeAttribute( std::string const& name, bool attribute );
6281 template<typename T>
6282 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6283 ReusableStringStream rss;
6285 return writeAttribute( name, rss.str() );
6288 XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6290 XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6292 void writeStylesheetRef( std::string const& url );
6294 XmlWriter& writeBlankLine();
6296 void ensureTagClosed();
6300 void applyFormatting(XmlFormatting fmt);
6302 void writeDeclaration();
6304 void newlineIfNecessary();
6306 bool m_tagIsOpen = false;
6307 bool m_needsNewline = false;
6308 std::vector<std::string> m_tags;
6309 std::string m_indent;
6315 // end catch_xmlwriter.h
6318 class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6320 JunitReporter(ReporterConfig const& _config);
6322 ~JunitReporter() override;
6324 static std::string getDescription();
6326 void noMatchingTestCases(std::string const& /*spec*/) override;
6328 void testRunStarting(TestRunInfo const& runInfo) override;
6330 void testGroupStarting(GroupInfo const& groupInfo) override;
6332 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6333 bool assertionEnded(AssertionStats const& assertionStats) override;
6335 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6337 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6339 void testRunEndedCumulative() override;
6341 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6343 void writeTestCase(TestCaseNode const& testCaseNode);
6345 void writeSection(std::string const& className,
6346 std::string const& rootName,
6347 SectionNode const& sectionNode);
6349 void writeAssertions(SectionNode const& sectionNode);
6350 void writeAssertion(AssertionStats const& stats);
6354 std::string stdOutForSuite;
6355 std::string stdErrForSuite;
6356 unsigned int unexpectedExceptions = 0;
6357 bool m_okToFail = false;
6360 } // end namespace Catch
6362 // end catch_reporter_junit.h
6363 // start catch_reporter_xml.h
6366 class XmlReporter : public StreamingReporterBase<XmlReporter> {
6368 XmlReporter(ReporterConfig const& _config);
6370 ~XmlReporter() override;
6372 static std::string getDescription();
6374 virtual std::string getStylesheetRef() const;
6376 void writeSourceInfo(SourceLineInfo const& sourceInfo);
6378 public: // StreamingReporterBase
6380 void noMatchingTestCases(std::string const& s) override;
6382 void testRunStarting(TestRunInfo const& testInfo) override;
6384 void testGroupStarting(GroupInfo const& groupInfo) override;
6386 void testCaseStarting(TestCaseInfo const& testInfo) override;
6388 void sectionStarting(SectionInfo const& sectionInfo) override;
6390 void assertionStarting(AssertionInfo const&) override;
6392 bool assertionEnded(AssertionStats const& assertionStats) override;
6394 void sectionEnded(SectionStats const& sectionStats) override;
6396 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6398 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6400 void testRunEnded(TestRunStats const& testRunStats) override;
6402 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6403 void benchmarkPreparing(std::string const& name) override;
6404 void benchmarkStarting(BenchmarkInfo const&) override;
6405 void benchmarkEnded(BenchmarkStats<> const&) override;
6406 void benchmarkFailed(std::string const&) override;
6407 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6410 Timer m_testCaseTimer;
6412 int m_sectionDepth = 0;
6415 } // end namespace Catch
6417 // end catch_reporter_xml.h
6419 // end catch_external_interfaces.h
6422 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6423 // start catch_benchmarking_all.hpp
6425 // A proxy header that includes all of the benchmarking headers to allow
6426 // concise include of the benchmarking features. You should prefer the
6427 // individual includes in standard use.
6429 // start catch_benchmark.hpp
6433 // start catch_chronometer.hpp
6435 // User-facing chronometer
6438 // start catch_clock.hpp
6447 namespace Benchmark {
6448 template <typename Clock>
6449 using ClockDuration = typename Clock::duration;
6450 template <typename Clock>
6451 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6453 template <typename Clock>
6454 using TimePoint = typename Clock::time_point;
6456 using default_clock = std::chrono::steady_clock;
6458 template <typename Clock>
6460 TimePoint<Clock> operator()() const {
6461 return Clock::now();
6465 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6466 } // namespace Benchmark
6467 } // namespace Catch
6469 // end catch_clock.hpp
6470 // start catch_optimizer.hpp
6472 // Hinting the optimizer
6475 #if defined(_MSC_VER)
6476 # include <atomic> // atomic_thread_fence
6480 namespace Benchmark {
6481 #if defined(__GNUC__) || defined(__clang__)
6482 template <typename T>
6483 inline void keep_memory(T* p) {
6484 asm volatile("" : : "g"(p) : "memory");
6486 inline void keep_memory() {
6487 asm volatile("" : : : "memory");
6491 inline void optimizer_barrier() { keep_memory(); }
6492 } // namespace Detail
6493 #elif defined(_MSC_VER)
6495 #pragma optimize("", off)
6496 template <typename T>
6497 inline void keep_memory(T* p) {
6498 // thanks @milleniumbug
6499 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6501 // TODO equivalent keep_memory()
6502 #pragma optimize("", on)
6505 inline void optimizer_barrier() {
6506 std::atomic_thread_fence(std::memory_order_seq_cst);
6508 } // namespace Detail
6512 template <typename T>
6513 inline void deoptimize_value(T&& x) {
6517 template <typename Fn, typename... Args>
6518 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6519 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6522 template <typename Fn, typename... Args>
6523 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6524 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6526 } // namespace Benchmark
6527 } // namespace Catch
6529 // end catch_optimizer.hpp
6530 // start catch_complete_invoke.hpp
6532 // Invoke with a special case for void
6535 #include <type_traits>
6539 namespace Benchmark {
6541 template <typename T>
6542 struct CompleteType { using type = T; };
6544 struct CompleteType<void> { struct type {}; };
6546 template <typename T>
6547 using CompleteType_t = typename CompleteType<T>::type;
6549 template <typename Result>
6550 struct CompleteInvoker {
6551 template <typename Fun, typename... Args>
6552 static Result invoke(Fun&& fun, Args&&... args) {
6553 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6557 struct CompleteInvoker<void> {
6558 template <typename Fun, typename... Args>
6559 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6560 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6565 // invoke and not return void :(
6566 template <typename Fun, typename... Args>
6567 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6568 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6571 const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6572 } // namespace Detail
6574 template <typename Fun>
6575 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6577 return Detail::complete_invoke(std::forward<Fun>(fun));
6579 getResultCapture().benchmarkFailed(translateActiveException());
6580 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6583 } // namespace Benchmark
6584 } // namespace Catch
6586 // end catch_complete_invoke.hpp
6588 namespace Benchmark {
6590 struct ChronometerConcept {
6591 virtual void start() = 0;
6592 virtual void finish() = 0;
6593 virtual ~ChronometerConcept() = default;
6595 template <typename Clock>
6596 struct ChronometerModel final : public ChronometerConcept {
6597 void start() override { started = Clock::now(); }
6598 void finish() override { finished = Clock::now(); }
6600 ClockDuration<Clock> elapsed() const { return finished - started; }
6602 TimePoint<Clock> started;
6603 TimePoint<Clock> finished;
6605 } // namespace Detail
6607 struct Chronometer {
6609 template <typename Fun>
6610 void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6612 int runs() const { return k; }
6614 Chronometer(Detail::ChronometerConcept& meter, int k)
6619 template <typename Fun>
6620 void measure(Fun&& fun, std::false_type) {
6621 measure([&fun](int) { return fun(); }, std::true_type());
6624 template <typename Fun>
6625 void measure(Fun&& fun, std::true_type) {
6626 Detail::optimizer_barrier();
6628 for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6630 Detail::optimizer_barrier();
6633 Detail::ChronometerConcept* impl;
6636 } // namespace Benchmark
6637 } // namespace Catch
6639 // end catch_chronometer.hpp
6640 // start catch_environment.hpp
6642 // Environment information
6646 namespace Benchmark {
6647 template <typename Duration>
6648 struct EnvironmentEstimate {
6650 OutlierClassification outliers;
6652 template <typename Duration2>
6653 operator EnvironmentEstimate<Duration2>() const {
6654 return { mean, outliers };
6657 template <typename Clock>
6658 struct Environment {
6659 using clock_type = Clock;
6660 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6661 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6663 } // namespace Benchmark
6664 } // namespace Catch
6666 // end catch_environment.hpp
6667 // start catch_execution_plan.hpp
6672 // start catch_benchmark_function.hpp
6674 // Dumb std::function implementation for consistent call overhead
6678 #include <type_traits>
6683 namespace Benchmark {
6685 template <typename T>
6686 using Decay = typename std::decay<T>::type;
6687 template <typename T, typename U>
6689 : std::is_same<Decay<T>, Decay<U>> {};
6691 /// We need to reinvent std::function because every piece of code that might add overhead
6692 /// in a measurement context needs to have consistent performance characteristics so that we
6693 /// can account for it in the measurement.
6694 /// Implementations of std::function with optimizations that aren't always applicable, like
6695 /// small buffer optimizations, are not uncommon.
6696 /// This is effectively an implementation of std::function without any such optimizations;
6697 /// it may be slow, but it is consistently slow.
6698 struct BenchmarkFunction {
6701 virtual void call(Chronometer meter) const = 0;
6702 virtual callable* clone() const = 0;
6703 virtual ~callable() = default;
6705 template <typename Fun>
6706 struct model : public callable {
6707 model(Fun&& fun) : fun(std::move(fun)) {}
6708 model(Fun const& fun) : fun(fun) {}
6710 model<Fun>* clone() const override { return new model<Fun>(*this); }
6712 void call(Chronometer meter) const override {
6713 call(meter, is_callable<Fun(Chronometer)>());
6715 void call(Chronometer meter, std::true_type) const {
6718 void call(Chronometer meter, std::false_type) const {
6725 struct do_nothing { void operator()() const {} };
6727 template <typename T>
6728 BenchmarkFunction(model<T>* c) : f(c) {}
6732 : f(new model<do_nothing>{ {} }) {}
6734 template <typename Fun,
6735 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
6736 BenchmarkFunction(Fun&& fun)
6737 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6739 BenchmarkFunction(BenchmarkFunction&& that)
6740 : f(std::move(that.f)) {}
6742 BenchmarkFunction(BenchmarkFunction const& that)
6743 : f(that.f->clone()) {}
6745 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6746 f = std::move(that.f);
6750 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6751 f.reset(that.f->clone());
6755 void operator()(Chronometer meter) const { f->call(meter); }
6758 std::unique_ptr<callable> f;
6760 } // namespace Detail
6761 } // namespace Benchmark
6762 } // namespace Catch
6764 // end catch_benchmark_function.hpp
6765 // start catch_repeat.hpp
6770 #include <type_traits>
6774 namespace Benchmark {
6776 template <typename Fun>
6778 void operator()(int k) const {
6779 for (int i = 0; i < k; ++i) {
6785 template <typename Fun>
6786 repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6787 return { std::forward<Fun>(fun) };
6789 } // namespace Detail
6790 } // namespace Benchmark
6791 } // namespace Catch
6793 // end catch_repeat.hpp
6794 // start catch_run_for_at_least.hpp
6796 // Run a function for a minimum amount of time
6799 // start catch_measure.hpp
6804 // start catch_timing.hpp
6810 #include <type_traits>
6813 namespace Benchmark {
6814 template <typename Duration, typename Result>
6820 template <typename Clock, typename Func, typename... Args>
6821 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6822 } // namespace Benchmark
6823 } // namespace Catch
6825 // end catch_timing.hpp
6829 namespace Benchmark {
6831 template <typename Clock, typename Fun, typename... Args>
6832 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6833 auto start = Clock::now();
6834 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6835 auto end = Clock::now();
6836 auto delta = end - start;
6837 return { delta, std::forward<decltype(r)>(r), 1 };
6839 } // namespace Detail
6840 } // namespace Benchmark
6841 } // namespace Catch
6843 // end catch_measure.hpp
6845 #include <type_traits>
6848 namespace Benchmark {
6850 template <typename Clock, typename Fun>
6851 TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
6852 return Detail::measure<Clock>(fun, iters);
6854 template <typename Clock, typename Fun>
6855 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
6856 Detail::ChronometerModel<Clock> meter;
6857 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6859 return { meter.elapsed(), std::move(result), iters };
6862 template <typename Clock, typename Fun>
6863 using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6865 struct optimized_away_error : std::exception {
6866 const char* what() const noexcept override {
6867 return "could not measure benchmark, maybe it was optimized away";
6871 template <typename Clock, typename Fun>
6872 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6874 while (iters < (1 << 30)) {
6875 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6877 if (Timing.elapsed >= how_long) {
6878 return { Timing.elapsed, std::move(Timing.result), iters };
6882 throw optimized_away_error{};
6884 } // namespace Detail
6885 } // namespace Benchmark
6886 } // namespace Catch
6888 // end catch_run_for_at_least.hpp
6889 #include <algorithm>
6892 namespace Benchmark {
6893 template <typename Duration>
6894 struct ExecutionPlan {
6895 int iterations_per_sample;
6896 Duration estimated_duration;
6897 Detail::BenchmarkFunction benchmark;
6898 Duration warmup_time;
6899 int warmup_iterations;
6901 template <typename Duration2>
6902 operator ExecutionPlan<Duration2>() const {
6903 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6906 template <typename Clock>
6907 std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6909 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6911 std::vector<FloatDuration<Clock>> times;
6912 times.reserve(cfg.benchmarkSamples());
6913 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6914 Detail::ChronometerModel<Clock> model;
6915 this->benchmark(Chronometer(model, iterations_per_sample));
6916 auto sample_time = model.elapsed() - env.clock_cost.mean;
6917 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6918 return sample_time / iterations_per_sample;
6923 } // namespace Benchmark
6924 } // namespace Catch
6926 // end catch_execution_plan.hpp
6927 // start catch_estimate_clock.hpp
6929 // Environment measurement
6932 // start catch_stats.hpp
6934 // Statistical analysis tools
6937 #include <algorithm>
6938 #include <functional>
6949 namespace Benchmark {
6951 using sample = std::vector<double>;
6953 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6955 template <typename Iterator>
6956 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6957 std::vector<double> copy(first, last);
6959 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6960 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6962 auto los = q1 - (iqr * 3.);
6963 auto lom = q1 - (iqr * 1.5);
6964 auto him = q3 + (iqr * 1.5);
6965 auto his = q3 + (iqr * 3.);
6967 OutlierClassification o;
6968 for (; first != last; ++first) {
6970 if (t < los) ++o.low_severe;
6971 else if (t < lom) ++o.low_mild;
6972 else if (t > his) ++o.high_severe;
6973 else if (t > him) ++o.high_mild;
6979 template <typename Iterator>
6980 double mean(Iterator first, Iterator last) {
6981 auto count = last - first;
6982 double sum = std::accumulate(first, last, 0.);
6986 template <typename URng, typename Iterator, typename Estimator>
6987 sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
6988 auto n = last - first;
6989 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6992 out.reserve(resamples);
6993 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
6994 std::vector<double> resampled;
6995 resampled.reserve(n);
6996 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
6997 return estimator(resampled.begin(), resampled.end());
6999 std::sort(out.begin(), out.end());
7003 template <typename Estimator, typename Iterator>
7004 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7005 auto n = last - first;
7006 auto second = std::next(first);
7010 for (auto it = first; it != last; ++it) {
7011 std::iter_swap(it, first);
7012 results.push_back(estimator(second, last));
7018 inline double normal_cdf(double x) {
7019 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7022 double erfc_inv(double x);
7024 double normal_quantile(double p);
7026 template <typename Iterator, typename Estimator>
7027 Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
7028 auto n_samples = last - first;
7030 double point = estimator(first, last);
7031 // Degenerate case with a single sample
7032 if (n_samples == 1) return { point, point, point, confidence_level };
7034 sample jack = jackknife(estimator, first, last);
7035 double jack_mean = mean(jack.begin(), jack.end());
7036 double sum_squares, sum_cubes;
7037 std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
7038 auto d = jack_mean - x;
7041 return { sqcb.first + d2, sqcb.second + d3 };
7044 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7045 int n = static_cast<int>(resample.size());
7046 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
7047 // degenerate case with uniform samples
7048 if (prob_n == 0) return { point, point, point, confidence_level };
7050 double bias = normal_quantile(prob_n);
7051 double z1 = normal_quantile((1. - confidence_level) / 2.);
7053 auto cumn = [n](double x) -> int {
7054 return std::lround(normal_cdf(x) * n); };
7055 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7056 double b1 = bias + z1;
7057 double b2 = bias - z1;
7060 auto lo = (std::max)(cumn(a1), 0);
7061 auto hi = (std::min)(cumn(a2), n - 1);
7063 return { point, resample[lo], resample[hi], confidence_level };
7066 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7068 struct bootstrap_analysis {
7069 Estimate<double> mean;
7070 Estimate<double> standard_deviation;
7071 double outlier_variance;
7074 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7075 } // namespace Detail
7076 } // namespace Benchmark
7077 } // namespace Catch
7079 // end catch_stats.hpp
7080 #include <algorithm>
7087 namespace Benchmark {
7089 template <typename Clock>
7090 std::vector<double> resolution(int k) {
7091 std::vector<TimePoint<Clock>> times;
7092 times.reserve(k + 1);
7093 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7095 std::vector<double> deltas;
7097 std::transform(std::next(times.begin()), times.end(), times.begin(),
7098 std::back_inserter(deltas),
7099 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7104 const auto warmup_iterations = 10000;
7105 const auto warmup_time = std::chrono::milliseconds(100);
7106 const auto minimum_ticks = 1000;
7107 const auto warmup_seed = 10000;
7108 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7109 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7110 const auto clock_cost_estimation_tick_limit = 100000;
7111 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7112 const auto clock_cost_estimation_iterations = 10000;
7114 template <typename Clock>
7116 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7119 template <typename Clock>
7120 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7121 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7124 FloatDuration<Clock>(mean(r.begin(), r.end())),
7125 classify_outliers(r.begin(), r.end()),
7128 template <typename Clock>
7129 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7130 auto time_limit = (std::min)(
7131 resolution * clock_cost_estimation_tick_limit,
7132 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7133 auto time_clock = [](int k) {
7134 return Detail::measure<Clock>([k] {
7135 for (int i = 0; i < k; ++i) {
7136 volatile auto ignored = Clock::now();
7142 int iters = clock_cost_estimation_iterations;
7143 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7144 std::vector<double> times;
7145 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7146 times.reserve(nsamples);
7147 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7148 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7151 FloatDuration<Clock>(mean(times.begin(), times.end())),
7152 classify_outliers(times.begin(), times.end()),
7156 template <typename Clock>
7157 Environment<FloatDuration<Clock>> measure_environment() {
7158 static Environment<FloatDuration<Clock>>* env = nullptr;
7163 auto iters = Detail::warmup<Clock>();
7164 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7165 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7167 env = new Environment<FloatDuration<Clock>>{ resolution, cost };
7170 } // namespace Detail
7171 } // namespace Benchmark
7172 } // namespace Catch
7174 // end catch_estimate_clock.hpp
7175 // start catch_analyse.hpp
7177 // Run and analyse one benchmark
7180 // start catch_sample_analysis.hpp
7182 // Benchmark results
7185 #include <algorithm>
7191 namespace Benchmark {
7192 template <typename Duration>
7193 struct SampleAnalysis {
7194 std::vector<Duration> samples;
7195 Estimate<Duration> mean;
7196 Estimate<Duration> standard_deviation;
7197 OutlierClassification outliers;
7198 double outlier_variance;
7200 template <typename Duration2>
7201 operator SampleAnalysis<Duration2>() const {
7202 std::vector<Duration2> samples2;
7203 samples2.reserve(samples.size());
7204 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7206 std::move(samples2),
7214 } // namespace Benchmark
7215 } // namespace Catch
7217 // end catch_sample_analysis.hpp
7218 #include <algorithm>
7223 namespace Benchmark {
7225 template <typename Duration, typename Iterator>
7226 SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7227 if (!cfg.benchmarkNoAnalysis()) {
7228 std::vector<double> samples;
7229 samples.reserve(last - first);
7230 std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7232 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7233 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7235 auto wrap_estimate = [](Estimate<double> e) {
7236 return Estimate<Duration> {
7238 Duration(e.lower_bound),
7239 Duration(e.upper_bound),
7240 e.confidence_interval,
7243 std::vector<Duration> samples2;
7244 samples2.reserve(samples.size());
7245 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7247 std::move(samples2),
7248 wrap_estimate(analysis.mean),
7249 wrap_estimate(analysis.standard_deviation),
7251 analysis.outlier_variance,
7254 std::vector<Duration> samples;
7255 samples.reserve(last - first);
7257 Duration mean = Duration(0);
7259 for (auto it = first; it < last; ++it, ++i) {
7260 samples.push_back(Duration(*it));
7261 mean += Duration(*it);
7267 Estimate<Duration>{mean, mean, mean, 0.0},
7268 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7269 OutlierClassification{},
7274 } // namespace Detail
7275 } // namespace Benchmark
7276 } // namespace Catch
7278 // end catch_analyse.hpp
7279 #include <algorithm>
7280 #include <functional>
7286 namespace Benchmark {
7288 Benchmark(std::string &&name)
7289 : name(std::move(name)) {}
7291 template <class FUN>
7292 Benchmark(std::string &&name, FUN &&func)
7293 : fun(std::move(func)), name(std::move(name)) {}
7295 template <typename Clock>
7296 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7297 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7298 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7299 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7300 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7301 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7304 template <typename Clock = default_clock>
7306 IConfigPtr cfg = getCurrentContext().getConfig();
7308 auto env = Detail::measure_environment<Clock>();
7310 getResultCapture().benchmarkPreparing(name);
7312 auto plan = user_code([&] {
7313 return prepare<Clock>(*cfg, env);
7316 BenchmarkInfo info {
7318 plan.estimated_duration.count(),
7319 plan.iterations_per_sample,
7320 cfg->benchmarkSamples(),
7321 cfg->benchmarkResamples(),
7322 env.clock_resolution.mean.count(),
7323 env.clock_cost.mean.count()
7326 getResultCapture().benchmarkStarting(info);
7328 auto samples = user_code([&] {
7329 return plan.template run<Clock>(*cfg, env);
7332 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7333 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7334 getResultCapture().benchmarkEnded(stats);
7337 if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7338 std::rethrow_exception(std::current_exception());
7342 // sets lambda to be used in fun *and* executes benchmark!
7343 template <typename Fun,
7344 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
7345 Benchmark & operator=(Fun func) {
7346 fun = Detail::BenchmarkFunction(func);
7351 explicit operator bool() {
7356 Detail::BenchmarkFunction fun;
7360 } // namespace Catch
7362 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7363 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7365 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7366 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7367 BenchmarkName = [&](int benchmarkIndex)
7369 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7370 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7373 // end catch_benchmark.hpp
7374 // start catch_constructor.hpp
7376 // Constructor and destructor helpers
7379 #include <type_traits>
7382 namespace Benchmark {
7384 template <typename T, bool Destruct>
7385 struct ObjectStorage
7387 using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7389 ObjectStorage() : data() {}
7391 ObjectStorage(const ObjectStorage& other)
7393 new(&data) T(other.stored_object());
7396 ObjectStorage(ObjectStorage&& other)
7398 new(&data) T(std::move(other.stored_object()));
7401 ~ObjectStorage() { destruct_on_exit<T>(); }
7403 template <typename... Args>
7404 void construct(Args&&... args)
7406 new (&data) T(std::forward<Args>(args)...);
7409 template <bool AllowManualDestruction = !Destruct>
7410 typename std::enable_if<AllowManualDestruction>::type destruct()
7412 stored_object().~T();
7416 // If this is a constructor benchmark, destruct the underlying object
7417 template <typename U>
7418 void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7420 template <typename U>
7421 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
7423 T& stored_object() {
7424 return *static_cast<T*>(static_cast<void*>(&data));
7427 T const& stored_object() const {
7428 return *static_cast<T*>(static_cast<void*>(&data));
7435 template <typename T>
7436 using storage_for = Detail::ObjectStorage<T, true>;
7438 template <typename T>
7439 using destructable_object = Detail::ObjectStorage<T, false>;
7443 // end catch_constructor.hpp
7444 // end catch_benchmarking_all.hpp
7447 #endif // ! CATCH_CONFIG_IMPL_ONLY
7450 // start catch_impl.hpp
7453 #pragma clang diagnostic push
7454 #pragma clang diagnostic ignored "-Wweak-vtables"
7457 // Keep these here for external reporters
7458 // start catch_test_case_tracker.h
7465 namespace TestCaseTracking {
7467 struct NameAndLocation {
7469 SourceLineInfo location;
7471 NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
7472 friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7473 return lhs.name == rhs.name
7474 && lhs.location == rhs.location;
7480 using ITrackerPtr = std::shared_ptr<ITracker>;
7483 NameAndLocation m_nameAndLocation;
7486 ITracker(NameAndLocation const& nameAndLoc) :
7487 m_nameAndLocation(nameAndLoc)
7491 NameAndLocation const& nameAndLocation() const {
7492 return m_nameAndLocation;
7495 virtual ~ITracker();
7498 virtual bool isComplete() const = 0; // Successfully completed or failed
7499 virtual bool isSuccessfullyCompleted() const = 0;
7500 virtual bool isOpen() const = 0; // Started but not complete
7501 virtual bool hasChildren() const = 0;
7502 virtual bool hasStarted() const = 0;
7504 virtual ITracker& parent() = 0;
7507 virtual void close() = 0; // Successfully complete
7508 virtual void fail() = 0;
7509 virtual void markAsNeedingAnotherRun() = 0;
7511 virtual void addChild( ITrackerPtr const& child ) = 0;
7512 virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7513 virtual void openChild() = 0;
7516 virtual bool isSectionTracker() const = 0;
7517 virtual bool isGeneratorTracker() const = 0;
7520 class TrackerContext {
7528 ITrackerPtr m_rootTracker;
7529 ITracker* m_currentTracker = nullptr;
7530 RunState m_runState = NotStarted;
7534 ITracker& startRun();
7538 void completeCycle();
7540 bool completedCycle() const;
7541 ITracker& currentTracker();
7542 void setCurrentTracker( ITracker* tracker );
7545 class TrackerBase : public ITracker {
7552 CompletedSuccessfully,
7556 using Children = std::vector<ITrackerPtr>;
7557 TrackerContext& m_ctx;
7559 Children m_children;
7560 CycleState m_runState = NotStarted;
7563 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7565 bool isComplete() const override;
7566 bool isSuccessfullyCompleted() const override;
7567 bool isOpen() const override;
7568 bool hasChildren() const override;
7569 bool hasStarted() const override {
7570 return m_runState != NotStarted;
7573 void addChild( ITrackerPtr const& child ) override;
7575 ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7576 ITracker& parent() override;
7578 void openChild() override;
7580 bool isSectionTracker() const override;
7581 bool isGeneratorTracker() const override;
7585 void close() override;
7586 void fail() override;
7587 void markAsNeedingAnotherRun() override;
7590 void moveToParent();
7594 class SectionTracker : public TrackerBase {
7595 std::vector<std::string> m_filters;
7596 std::string m_trimmed_name;
7598 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7600 bool isSectionTracker() const override;
7602 bool isComplete() const override;
7604 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7608 void addInitialFilters( std::vector<std::string> const& filters );
7609 void addNextFilters( std::vector<std::string> const& filters );
7610 //! Returns filters active in this tracker
7611 std::vector<std::string> const& getFilters() const;
7612 //! Returns whitespace-trimmed name of the tracked section
7613 std::string const& trimmedName() const;
7616 } // namespace TestCaseTracking
7618 using TestCaseTracking::ITracker;
7619 using TestCaseTracking::TrackerContext;
7620 using TestCaseTracking::SectionTracker;
7622 } // namespace Catch
7624 // end catch_test_case_tracker.h
7626 // start catch_leak_detector.h
7630 struct LeakDetector {
7636 // end catch_leak_detector.h
7637 // Cpp files will be included in the single-header file here
7638 // start catch_stats.cpp
7640 // Statistical analysis tools
7642 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7647 #if defined(CATCH_CONFIG_USE_ASYNC)
7652 double erf_inv(double x) {
7653 // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7656 w = -log((1.0 - x) * (1.0 + x));
7660 p = -3.6444120640178196996e-21;
7661 p = -1.685059138182016589e-19 + p * w;
7662 p = 1.2858480715256400167e-18 + p * w;
7663 p = 1.115787767802518096e-17 + p * w;
7664 p = -1.333171662854620906e-16 + p * w;
7665 p = 2.0972767875968561637e-17 + p * w;
7666 p = 6.6376381343583238325e-15 + p * w;
7667 p = -4.0545662729752068639e-14 + p * w;
7668 p = -8.1519341976054721522e-14 + p * w;
7669 p = 2.6335093153082322977e-12 + p * w;
7670 p = -1.2975133253453532498e-11 + p * w;
7671 p = -5.4154120542946279317e-11 + p * w;
7672 p = 1.051212273321532285e-09 + p * w;
7673 p = -4.1126339803469836976e-09 + p * w;
7674 p = -2.9070369957882005086e-08 + p * w;
7675 p = 4.2347877827932403518e-07 + p * w;
7676 p = -1.3654692000834678645e-06 + p * w;
7677 p = -1.3882523362786468719e-05 + p * w;
7678 p = 0.0001867342080340571352 + p * w;
7679 p = -0.00074070253416626697512 + p * w;
7680 p = -0.0060336708714301490533 + p * w;
7681 p = 0.24015818242558961693 + p * w;
7682 p = 1.6536545626831027356 + p * w;
7683 } else if (w < 16.000000) {
7684 w = sqrt(w) - 3.250000;
7685 p = 2.2137376921775787049e-09;
7686 p = 9.0756561938885390979e-08 + p * w;
7687 p = -2.7517406297064545428e-07 + p * w;
7688 p = 1.8239629214389227755e-08 + p * w;
7689 p = 1.5027403968909827627e-06 + p * w;
7690 p = -4.013867526981545969e-06 + p * w;
7691 p = 2.9234449089955446044e-06 + p * w;
7692 p = 1.2475304481671778723e-05 + p * w;
7693 p = -4.7318229009055733981e-05 + p * w;
7694 p = 6.8284851459573175448e-05 + p * w;
7695 p = 2.4031110387097893999e-05 + p * w;
7696 p = -0.0003550375203628474796 + p * w;
7697 p = 0.00095328937973738049703 + p * w;
7698 p = -0.0016882755560235047313 + p * w;
7699 p = 0.0024914420961078508066 + p * w;
7700 p = -0.0037512085075692412107 + p * w;
7701 p = 0.005370914553590063617 + p * w;
7702 p = 1.0052589676941592334 + p * w;
7703 p = 3.0838856104922207635 + p * w;
7705 w = sqrt(w) - 5.000000;
7706 p = -2.7109920616438573243e-11;
7707 p = -2.5556418169965252055e-10 + p * w;
7708 p = 1.5076572693500548083e-09 + p * w;
7709 p = -3.7894654401267369937e-09 + p * w;
7710 p = 7.6157012080783393804e-09 + p * w;
7711 p = -1.4960026627149240478e-08 + p * w;
7712 p = 2.9147953450901080826e-08 + p * w;
7713 p = -6.7711997758452339498e-08 + p * w;
7714 p = 2.2900482228026654717e-07 + p * w;
7715 p = -9.9298272942317002539e-07 + p * w;
7716 p = 4.5260625972231537039e-06 + p * w;
7717 p = -1.9681778105531670567e-05 + p * w;
7718 p = 7.5995277030017761139e-05 + p * w;
7719 p = -0.00021503011930044477347 + p * w;
7720 p = -0.00013871931833623122026 + p * w;
7721 p = 1.0103004648645343977 + p * w;
7722 p = 4.8499064014085844221 + p * w;
7727 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7728 auto m = Catch::Benchmark::Detail::mean(first, last);
7729 double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7730 double diff = b - m;
7731 return a + diff * diff;
7732 }) / (last - first);
7733 return std::sqrt(variance);
7739 namespace Benchmark {
7742 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7743 auto count = last - first;
7744 double idx = (count - 1) * k / static_cast<double>(q);
7745 int j = static_cast<int>(idx);
7747 std::nth_element(first, first + j, last);
7749 if (g == 0) return xj;
7751 auto xj1 = *std::min_element(first + (j + 1), last);
7752 return xj + g * (xj1 - xj);
7755 double erfc_inv(double x) {
7756 return erf_inv(1.0 - x);
7759 double normal_quantile(double p) {
7760 static const double ROOT_TWO = std::sqrt(2.0);
7762 double result = 0.0;
7763 assert(p >= 0 && p <= 1);
7764 if (p < 0 || p > 1) {
7768 result = -erfc_inv(2.0 * p);
7769 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7770 result *= /*sd * */ ROOT_TWO;
7771 // result += normal disttribution mean (0)
7775 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7776 double sb = stddev.point;
7777 double mn = mean.point / n;
7778 double mg_min = mn / 2.;
7779 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7780 double sg2 = sg * sg;
7781 double sb2 = sb * sb;
7783 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7787 double k0 = -n * nd;
7788 double k1 = sb2 - n * sg2 + nd;
7789 double det = k1 * k1 - 4 * sg2 * k0;
7790 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7793 auto var_out = [n, sb2, sg2](double c) {
7795 return (nc / n) * (sb2 - nc * sg2);
7798 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7801 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7802 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7803 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7804 static std::random_device entropy;
7805 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7807 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7809 auto mean = &Detail::mean<std::vector<double>::iterator>;
7810 auto stddev = &standard_deviation;
7812 #if defined(CATCH_CONFIG_USE_ASYNC)
7813 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7814 auto seed = entropy();
7815 return std::async(std::launch::async, [=] {
7816 std::mt19937 rng(seed);
7817 auto resampled = resample(rng, n_resamples, first, last, f);
7818 return bootstrap(confidence_level, first, last, resampled, f);
7822 auto mean_future = Estimate(mean);
7823 auto stddev_future = Estimate(stddev);
7825 auto mean_estimate = mean_future.get();
7826 auto stddev_estimate = stddev_future.get();
7828 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7829 auto seed = entropy();
7830 std::mt19937 rng(seed);
7831 auto resampled = resample(rng, n_resamples, first, last, f);
7832 return bootstrap(confidence_level, first, last, resampled, f);
7835 auto mean_estimate = Estimate(mean);
7836 auto stddev_estimate = Estimate(stddev);
7837 #endif // CATCH_USE_ASYNC
7839 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7841 return { mean_estimate, stddev_estimate, outlier_variance };
7843 } // namespace Detail
7844 } // namespace Benchmark
7845 } // namespace Catch
7847 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7848 // end catch_stats.cpp
7849 // start catch_approx.cpp
7856 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7857 // But without the subtraction to allow for INFINITY in comparison
7858 bool marginComparison(double lhs, double rhs, double margin) {
7859 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7867 Approx::Approx ( double value )
7868 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7874 Approx Approx::custom() {
7878 Approx Approx::operator-() const {
7880 temp.m_value = -temp.m_value;
7884 std::string Approx::toString() const {
7885 ReusableStringStream rss;
7886 rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7890 bool Approx::equalityComparisonImpl(const double other) const {
7891 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7892 // Thanks to Richard Harris for his help refining the scaled margin value
7893 return marginComparison(m_value, other, m_margin)
7894 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7897 void Approx::setMargin(double newMargin) {
7898 CATCH_ENFORCE(newMargin >= 0,
7899 "Invalid Approx::margin: " << newMargin << '.'
7900 << " Approx::Margin has to be non-negative.");
7901 m_margin = newMargin;
7904 void Approx::setEpsilon(double newEpsilon) {
7905 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7906 "Invalid Approx::epsilon: " << newEpsilon << '.'
7907 << " Approx::epsilon has to be in [0, 1]");
7908 m_epsilon = newEpsilon;
7911 } // end namespace Detail
7913 namespace literals {
7914 Detail::Approx operator "" _a(long double val) {
7915 return Detail::Approx(val);
7917 Detail::Approx operator "" _a(unsigned long long val) {
7918 return Detail::Approx(val);
7920 } // end namespace literals
7922 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
7923 return value.toString();
7926 } // end namespace Catch
7927 // end catch_approx.cpp
7928 // start catch_assertionhandler.cpp
7930 // start catch_debugger.h
7933 bool isDebuggerActive();
7936 #ifdef CATCH_PLATFORM_MAC
7938 #if defined(__i386__) || defined(__x86_64__)
7939 #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7940 #elif defined(__aarch64__)
7941 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7944 #elif defined(CATCH_PLATFORM_IPHONE)
7946 // use inline assembler
7947 #if defined(__i386__) || defined(__x86_64__)
7948 #define CATCH_TRAP() __asm__("int $3")
7949 #elif defined(__aarch64__)
7950 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7951 #elif defined(__arm__) && !defined(__thumb__)
7952 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7953 #elif defined(__arm__) && defined(__thumb__)
7954 #define CATCH_TRAP() __asm__(".inst 0xde01")
7957 #elif defined(CATCH_PLATFORM_LINUX)
7958 // If we can use inline assembler, do it because this allows us to break
7959 // directly at the location of the failing check instead of breaking inside
7960 // raise() called from it, i.e. one stack frame below.
7961 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7962 #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7963 #else // Fall back to the generic way.
7966 #define CATCH_TRAP() raise(SIGTRAP)
7968 #elif defined(_MSC_VER)
7969 #define CATCH_TRAP() __debugbreak()
7970 #elif defined(__MINGW32__)
7971 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7972 #define CATCH_TRAP() DebugBreak()
7975 #ifndef CATCH_BREAK_INTO_DEBUGGER
7977 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7979 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7983 // end catch_debugger.h
7984 // start catch_run_context.h
7986 // start catch_fatal_condition.h
7992 // Wrapper for platform-specific fatal error (signals/SEH) handlers
7994 // Tries to be cooperative with other handlers, and not step over
7995 // other handlers. This means that unknown structured exceptions
7996 // are passed on, previous signal handlers are called, and so on.
7998 // Can only be instantiated once, and assumes that once a signal
7999 // is caught, the binary will end up terminating. Thus, there
8000 class FatalConditionHandler {
8001 bool m_started = false;
8003 // Install/disengage implementation for specific platform.
8004 // Should be if-defed to work on current platform, can assume
8005 // engage-disengage 1:1 pairing.
8006 void engage_platform();
8007 void disengage_platform();
8009 // Should also have platform-specific implementations as needed
8010 FatalConditionHandler();
8011 ~FatalConditionHandler();
8014 assert(!m_started && "Handler cannot be installed twice.");
8020 assert(m_started && "Handler cannot be uninstalled without being installed first");
8022 disengage_platform();
8026 //! Simple RAII guard for (dis)engaging the FatalConditionHandler
8027 class FatalConditionHandlerGuard {
8028 FatalConditionHandler* m_handler;
8030 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8031 m_handler(handler) {
8032 m_handler->engage();
8034 ~FatalConditionHandlerGuard() {
8035 m_handler->disengage();
8039 } // end namespace Catch
8041 // end catch_fatal_condition.h
8046 struct IMutableContext;
8048 ///////////////////////////////////////////////////////////////////////////
8050 class RunContext : public IResultCapture, public IRunner {
8053 RunContext( RunContext const& ) = delete;
8054 RunContext& operator =( RunContext const& ) = delete;
8056 explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8058 ~RunContext() override;
8060 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8061 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8063 Totals runTest(TestCase const& testCase);
8065 IConfigPtr config() const;
8066 IStreamingReporter& reporter() const;
8068 public: // IResultCapture
8070 // Assertion handlers
8072 ( AssertionInfo const& info,
8073 ITransientExpression const& expr,
8074 AssertionReaction& reaction ) override;
8076 ( AssertionInfo const& info,
8077 ResultWas::OfType resultType,
8078 StringRef const& message,
8079 AssertionReaction& reaction ) override;
8080 void handleUnexpectedExceptionNotThrown
8081 ( AssertionInfo const& info,
8082 AssertionReaction& reaction ) override;
8083 void handleUnexpectedInflightException
8084 ( AssertionInfo const& info,
8085 std::string const& message,
8086 AssertionReaction& reaction ) override;
8087 void handleIncomplete
8088 ( AssertionInfo const& info ) override;
8090 ( AssertionInfo const &info,
8091 ResultWas::OfType resultType,
8092 AssertionReaction &reaction ) override;
8094 bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
8096 void sectionEnded( SectionEndInfo const& endInfo ) override;
8097 void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
8099 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
8101 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8102 void benchmarkPreparing( std::string const& name ) override;
8103 void benchmarkStarting( BenchmarkInfo const& info ) override;
8104 void benchmarkEnded( BenchmarkStats<> const& stats ) override;
8105 void benchmarkFailed( std::string const& error ) override;
8106 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8108 void pushScopedMessage( MessageInfo const& message ) override;
8109 void popScopedMessage( MessageInfo const& message ) override;
8111 void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
8113 std::string getCurrentTestName() const override;
8115 const AssertionResult* getLastResult() const override;
8117 void exceptionEarlyReported() override;
8119 void handleFatalErrorCondition( StringRef message ) override;
8121 bool lastAssertionPassed() override;
8123 void assertionPassed() override;
8126 // !TBD We need to do this another way!
8127 bool aborting() const final;
8131 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8132 void invokeActiveTestCase();
8134 void resetAssertionInfo();
8135 bool testForMissingAssertions( Counts& assertions );
8137 void assertionEnded( AssertionResult const& result );
8139 ( AssertionInfo const &info,
8140 ResultWas::OfType resultType,
8141 ITransientExpression const *expr,
8144 void populateReaction( AssertionReaction& reaction );
8148 void handleUnfinishedSections();
8150 TestRunInfo m_runInfo;
8151 IMutableContext& m_context;
8152 TestCase const* m_activeTestCase = nullptr;
8153 ITracker* m_testCaseTracker = nullptr;
8154 Option<AssertionResult> m_lastResult;
8156 IConfigPtr m_config;
8158 IStreamingReporterPtr m_reporter;
8159 std::vector<MessageInfo> m_messages;
8160 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8161 AssertionInfo m_lastAssertionInfo;
8162 std::vector<SectionEndInfo> m_unfinishedSections;
8163 std::vector<ITracker*> m_activeSections;
8164 TrackerContext m_trackerContext;
8165 FatalConditionHandler m_fatalConditionhandler;
8166 bool m_lastAssertionPassed = false;
8167 bool m_shouldReportUnexpected = true;
8168 bool m_includeSuccessfulResults;
8171 void seedRng(IConfig const& config);
8172 unsigned int rngSeed();
8173 } // end namespace Catch
8175 // end catch_run_context.h
8179 auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
8180 expr.streamReconstructedExpression( os );
8185 LazyExpression::LazyExpression( bool isNegated )
8186 : m_isNegated( isNegated )
8189 LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
8191 LazyExpression::operator bool() const {
8192 return m_transientExpression != nullptr;
8195 auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
8196 if( lazyExpr.m_isNegated )
8200 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8201 os << "(" << *lazyExpr.m_transientExpression << ")";
8203 os << *lazyExpr.m_transientExpression;
8206 os << "{** error - unchecked empty expression requested **}";
8211 AssertionHandler::AssertionHandler
8212 ( StringRef const& macroName,
8213 SourceLineInfo const& lineInfo,
8214 StringRef capturedExpression,
8215 ResultDisposition::Flags resultDisposition )
8216 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8217 m_resultCapture( getResultCapture() )
8220 void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
8221 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8223 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8224 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8227 auto AssertionHandler::allowThrows() const -> bool {
8228 return getCurrentContext().getConfig()->allowThrows();
8231 void AssertionHandler::complete() {
8233 if( m_reaction.shouldDebugBreak ) {
8235 // If you find your debugger stopping you here then go one level up on the
8236 // call-stack for the code that caused it (typically a failed assertion)
8238 // (To go back to the test and change execution, jump over the throw, next)
8239 CATCH_BREAK_INTO_DEBUGGER();
8241 if (m_reaction.shouldThrow) {
8242 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8243 throw Catch::TestFailureException();
8245 CATCH_ERROR( "Test failure requires aborting test!" );
8249 void AssertionHandler::setCompleted() {
8253 void AssertionHandler::handleUnexpectedInflightException() {
8254 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8257 void AssertionHandler::handleExceptionThrownAsExpected() {
8258 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8260 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8261 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8264 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8265 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8268 void AssertionHandler::handleThrowingCallSkipped() {
8269 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8272 // This is the overload that takes a string and infers the Equals matcher from it
8273 // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
8274 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
8275 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8278 } // namespace Catch
8279 // end catch_assertionhandler.cpp
8280 // start catch_assertionresult.cpp
8283 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
8284 lazyExpression(_lazyExpression),
8285 resultType(_resultType) {}
8287 std::string AssertionResultData::reconstructExpression() const {
8289 if( reconstructedExpression.empty() ) {
8290 if( lazyExpression ) {
8291 ReusableStringStream rss;
8292 rss << lazyExpression;
8293 reconstructedExpression = rss.str();
8296 return reconstructedExpression;
8299 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8301 m_resultData( data )
8304 // Result was a success
8305 bool AssertionResult::succeeded() const {
8306 return Catch::isOk( m_resultData.resultType );
8309 // Result was a success, or failure is suppressed
8310 bool AssertionResult::isOk() const {
8311 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8314 ResultWas::OfType AssertionResult::getResultType() const {
8315 return m_resultData.resultType;
8318 bool AssertionResult::hasExpression() const {
8319 return !m_info.capturedExpression.empty();
8322 bool AssertionResult::hasMessage() const {
8323 return !m_resultData.message.empty();
8326 std::string AssertionResult::getExpression() const {
8327 // Possibly overallocating by 3 characters should be basically free
8328 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8329 if (isFalseTest(m_info.resultDisposition)) {
8332 expr += m_info.capturedExpression;
8333 if (isFalseTest(m_info.resultDisposition)) {
8339 std::string AssertionResult::getExpressionInMacro() const {
8341 if( m_info.macroName.empty() )
8342 expr = static_cast<std::string>(m_info.capturedExpression);
8344 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8345 expr += m_info.macroName;
8347 expr += m_info.capturedExpression;
8353 bool AssertionResult::hasExpandedExpression() const {
8354 return hasExpression() && getExpandedExpression() != getExpression();
8357 std::string AssertionResult::getExpandedExpression() const {
8358 std::string expr = m_resultData.reconstructExpression();
8364 std::string AssertionResult::getMessage() const {
8365 return m_resultData.message;
8367 SourceLineInfo AssertionResult::getSourceInfo() const {
8368 return m_info.lineInfo;
8371 StringRef AssertionResult::getTestMacroName() const {
8372 return m_info.macroName;
8375 } // end namespace Catch
8376 // end catch_assertionresult.cpp
8377 // start catch_capture_matchers.cpp
8381 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8383 // This is the general overload that takes a any string matcher
8384 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8385 // the Equals matcher (so the header does not mention matchers)
8386 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
8387 std::string exceptionMessage = Catch::translateActiveException();
8388 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8389 handler.handleExpr( expr );
8392 } // namespace Catch
8393 // end catch_capture_matchers.cpp
8394 // start catch_commandline.cpp
8396 // start catch_commandline.h
8398 // start catch_clara.h
8400 // Use Catch's value for console width (store Clara's off to the side, if present)
8401 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8402 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8403 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8405 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8408 #pragma clang diagnostic push
8409 #pragma clang diagnostic ignored "-Wweak-vtables"
8410 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8411 #pragma clang diagnostic ignored "-Wshadow"
8415 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8417 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8418 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8420 // See https://github.com/philsquared/Clara for more details
8425 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8426 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8429 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8430 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8433 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8434 #ifdef __has_include
8435 #if __has_include(<optional>) && __cplusplus >= 201703L
8437 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8442 // ----------- #included from clara_textflow.hpp -----------
8446 // A single-header library for wrapping and laying out basic text, by Phil Nash
8448 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8449 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8451 // This project is hosted at https://github.com/philsquared/textflowcpp
8459 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8460 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8465 namespace TextFlow {
8467 inline auto isWhitespace(char c) -> bool {
8468 static std::string chars = " \t\n\r";
8469 return chars.find(c) != std::string::npos;
8471 inline auto isBreakableBefore(char c) -> bool {
8472 static std::string chars = "[({<|";
8473 return chars.find(c) != std::string::npos;
8475 inline auto isBreakableAfter(char c) -> bool {
8476 static std::string chars = "])}>.,:;*+-=&/\\";
8477 return chars.find(c) != std::string::npos;
8483 std::vector<std::string> m_strings;
8484 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8485 size_t m_indent = 0;
8486 size_t m_initialIndent = std::string::npos;
8492 Column const& m_column;
8493 size_t m_stringIndex = 0;
8498 bool m_suffix = false;
8500 iterator(Column const& column, size_t stringIndex)
8502 m_stringIndex(stringIndex) {}
8504 auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8506 auto isBoundary(size_t at) const -> bool {
8508 assert(at <= line().size());
8510 return at == line().size() ||
8511 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8512 isBreakableBefore(line()[at]) ||
8513 isBreakableAfter(line()[at - 1]);
8517 assert(m_stringIndex < m_column.m_strings.size());
8520 auto width = m_column.m_width - indent();
8522 if (line()[m_pos] == '\n') {
8525 while (m_end < line().size() && line()[m_end] != '\n')
8528 if (m_end < m_pos + width) {
8529 m_len = m_end - m_pos;
8532 while (len > 0 && !isBoundary(m_pos + len))
8534 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8546 auto indent() const -> size_t {
8547 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8548 return initial == std::string::npos ? m_column.m_indent : initial;
8551 auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8552 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8556 using difference_type = std::ptrdiff_t;
8557 using value_type = std::string;
8558 using pointer = value_type * ;
8559 using reference = value_type & ;
8560 using iterator_category = std::forward_iterator_tag;
8562 explicit iterator(Column const& column) : m_column(column) {
8563 assert(m_column.m_width > m_column.m_indent);
8564 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8567 m_stringIndex++; // Empty string
8570 auto operator *() const -> std::string {
8571 assert(m_stringIndex < m_column.m_strings.size());
8572 assert(m_pos <= m_end);
8573 return addIndentAndSuffix(line().substr(m_pos, m_len));
8576 auto operator ++() -> iterator& {
8578 if (m_pos < line().size() && line()[m_pos] == '\n')
8581 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8584 if (m_pos == line().size()) {
8588 if (m_stringIndex < m_column.m_strings.size())
8592 auto operator ++(int) -> iterator {
8593 iterator prev(*this);
8598 auto operator ==(iterator const& other) const -> bool {
8600 m_pos == other.m_pos &&
8601 m_stringIndex == other.m_stringIndex &&
8602 &m_column == &other.m_column;
8604 auto operator !=(iterator const& other) const -> bool {
8605 return !operator==(other);
8608 using const_iterator = iterator;
8610 explicit Column(std::string const& text) { m_strings.push_back(text); }
8612 auto width(size_t newWidth) -> Column& {
8613 assert(newWidth > 0);
8617 auto indent(size_t newIndent) -> Column& {
8618 m_indent = newIndent;
8621 auto initialIndent(size_t newIndent) -> Column& {
8622 m_initialIndent = newIndent;
8626 auto width() const -> size_t { return m_width; }
8627 auto begin() const -> iterator { return iterator(*this); }
8628 auto end() const -> iterator { return { *this, m_strings.size() }; }
8630 inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8632 for (auto line : col) {
8642 auto operator + (Column const& other)->Columns;
8644 auto toString() const -> std::string {
8645 std::ostringstream oss;
8651 class Spacer : public Column {
8654 explicit Spacer(size_t spaceWidth) : Column("") {
8660 std::vector<Column> m_columns;
8668 std::vector<Column> const& m_columns;
8669 std::vector<Column::iterator> m_iterators;
8670 size_t m_activeIterators;
8672 iterator(Columns const& columns, EndTag)
8673 : m_columns(columns.m_columns),
8674 m_activeIterators(0) {
8675 m_iterators.reserve(m_columns.size());
8677 for (auto const& col : m_columns)
8678 m_iterators.push_back(col.end());
8682 using difference_type = std::ptrdiff_t;
8683 using value_type = std::string;
8684 using pointer = value_type * ;
8685 using reference = value_type & ;
8686 using iterator_category = std::forward_iterator_tag;
8688 explicit iterator(Columns const& columns)
8689 : m_columns(columns.m_columns),
8690 m_activeIterators(m_columns.size()) {
8691 m_iterators.reserve(m_columns.size());
8693 for (auto const& col : m_columns)
8694 m_iterators.push_back(col.begin());
8697 auto operator ==(iterator const& other) const -> bool {
8698 return m_iterators == other.m_iterators;
8700 auto operator !=(iterator const& other) const -> bool {
8701 return m_iterators != other.m_iterators;
8703 auto operator *() const -> std::string {
8704 std::string row, padding;
8706 for (size_t i = 0; i < m_columns.size(); ++i) {
8707 auto width = m_columns[i].width();
8708 if (m_iterators[i] != m_columns[i].end()) {
8709 std::string col = *m_iterators[i];
8710 row += padding + col;
8711 if (col.size() < width)
8712 padding = std::string(width - col.size(), ' ');
8716 padding += std::string(width, ' ');
8721 auto operator ++() -> iterator& {
8722 for (size_t i = 0; i < m_columns.size(); ++i) {
8723 if (m_iterators[i] != m_columns[i].end())
8728 auto operator ++(int) -> iterator {
8729 iterator prev(*this);
8734 using const_iterator = iterator;
8736 auto begin() const -> iterator { return iterator(*this); }
8737 auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8739 auto operator += (Column const& col) -> Columns& {
8740 m_columns.push_back(col);
8743 auto operator + (Column const& col) -> Columns {
8744 Columns combined = *this;
8749 inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8752 for (auto line : cols) {
8762 auto toString() const -> std::string {
8763 std::ostringstream oss;
8769 inline auto Column::operator + (Column const& other) -> Columns {
8780 // ----------- end of #include from clara_textflow.hpp -----------
8781 // ........... back in clara.hpp
8787 #include <algorithm>
8789 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8790 #define CATCH_PLATFORM_WINDOWS
8793 namespace Catch { namespace clara {
8796 // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8797 template<typename L>
8798 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8800 template<typename ClassT, typename ReturnT, typename... Args>
8801 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8802 static const bool isValid = false;
8805 template<typename ClassT, typename ReturnT, typename ArgT>
8806 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8807 static const bool isValid = true;
8808 using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8809 using ReturnType = ReturnT;
8814 // Transport for raw args (copied from main args, or supplied via init list for testing)
8817 std::string m_exeName;
8818 std::vector<std::string> m_args;
8821 Args( int argc, char const* const* argv )
8822 : m_exeName(argv[0]),
8823 m_args(argv + 1, argv + argc) {}
8825 Args( std::initializer_list<std::string> args )
8826 : m_exeName( *args.begin() ),
8827 m_args( args.begin()+1, args.end() )
8830 auto exeName() const -> std::string {
8835 // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8836 // may encode an option + its argument if the : or = form is used
8837 enum class TokenType {
8845 inline auto isOptPrefix( char c ) -> bool {
8847 #ifdef CATCH_PLATFORM_WINDOWS
8853 // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8855 using Iterator = std::vector<std::string>::const_iterator;
8858 std::vector<Token> m_tokenBuffer;
8861 m_tokenBuffer.resize( 0 );
8863 // Skip any empty strings
8864 while( it != itEnd && it->empty() )
8868 auto const &next = *it;
8869 if( isOptPrefix( next[0] ) ) {
8870 auto delimiterPos = next.find_first_of( " :=" );
8871 if( delimiterPos != std::string::npos ) {
8872 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8873 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8875 if( next[1] != '-' && next.size() > 2 ) {
8876 std::string opt = "- ";
8877 for( size_t i = 1; i < next.size(); ++i ) {
8879 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8882 m_tokenBuffer.push_back( { TokenType::Option, next } );
8886 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8892 explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8894 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8898 explicit operator bool() const {
8899 return !m_tokenBuffer.empty() || it != itEnd;
8902 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8904 auto operator*() const -> Token {
8905 assert( !m_tokenBuffer.empty() );
8906 return m_tokenBuffer.front();
8909 auto operator->() const -> Token const * {
8910 assert( !m_tokenBuffer.empty() );
8911 return &m_tokenBuffer.front();
8914 auto operator++() -> TokenStream & {
8915 if( m_tokenBuffer.size() >= 2 ) {
8916 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8929 Ok, LogicError, RuntimeError
8933 ResultBase( Type type ) : m_type( type ) {}
8934 virtual ~ResultBase() = default;
8936 virtual void enforceOk() const = 0;
8941 template<typename T>
8942 class ResultValueBase : public ResultBase {
8944 auto value() const -> T const & {
8950 ResultValueBase( Type type ) : ResultBase( type ) {}
8952 ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8953 if( m_type == ResultBase::Ok )
8954 new( &m_value ) T( other.m_value );
8957 ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8958 new( &m_value ) T( value );
8961 auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8962 if( m_type == ResultBase::Ok )
8964 ResultBase::operator=(other);
8965 if( m_type == ResultBase::Ok )
8966 new( &m_value ) T( other.m_value );
8970 ~ResultValueBase() override {
8981 class ResultValueBase<void> : public ResultBase {
8983 using ResultBase::ResultBase;
8986 template<typename T = void>
8987 class BasicResult : public ResultValueBase<T> {
8989 template<typename U>
8990 explicit BasicResult( BasicResult<U> const &other )
8991 : ResultValueBase<T>( other.type() ),
8992 m_errorMessage( other.errorMessage() )
8994 assert( type() != ResultBase::Ok );
8997 template<typename U>
8998 static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
8999 static auto ok() -> BasicResult { return { ResultBase::Ok }; }
9000 static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
9001 static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
9003 explicit operator bool() const { return m_type == ResultBase::Ok; }
9004 auto type() const -> ResultBase::Type { return m_type; }
9005 auto errorMessage() const -> std::string { return m_errorMessage; }
9008 void enforceOk() const override {
9010 // Errors shouldn't reach this point, but if they do
9011 // the actual error message will be in m_errorMessage
9012 assert( m_type != ResultBase::LogicError );
9013 assert( m_type != ResultBase::RuntimeError );
9014 if( m_type != ResultBase::Ok )
9018 std::string m_errorMessage; // Only populated if resultType is an error
9020 BasicResult( ResultBase::Type type, std::string const &message )
9021 : ResultValueBase<T>(type),
9022 m_errorMessage(message)
9024 assert( m_type != ResultBase::Ok );
9027 using ResultValueBase<T>::ResultValueBase;
9028 using ResultBase::m_type;
9031 enum class ParseResultType {
9032 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9038 ParseState( ParseResultType type, TokenStream const &remainingTokens )
9040 m_remainingTokens( remainingTokens )
9043 auto type() const -> ParseResultType { return m_type; }
9044 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9047 ParseResultType m_type;
9048 TokenStream m_remainingTokens;
9051 using Result = BasicResult<void>;
9052 using ParserResult = BasicResult<ParseResultType>;
9053 using InternalParseResult = BasicResult<ParseState>;
9055 struct HelpColumns {
9060 template<typename T>
9061 inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
9062 std::stringstream ss;
9066 return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
9068 return ParserResult::ok( ParseResultType::Matched );
9070 inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
9072 return ParserResult::ok( ParseResultType::Matched );
9074 inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
9075 std::string srcLC = source;
9076 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9077 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9079 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
9082 return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
9083 return ParserResult::ok( ParseResultType::Matched );
9085 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9086 template<typename T>
9087 inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9089 auto result = convertInto( source, temp );
9091 target = std::move(temp);
9094 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9096 struct NonCopyable {
9097 NonCopyable() = default;
9098 NonCopyable( NonCopyable const & ) = delete;
9099 NonCopyable( NonCopyable && ) = delete;
9100 NonCopyable &operator=( NonCopyable const & ) = delete;
9101 NonCopyable &operator=( NonCopyable && ) = delete;
9104 struct BoundRef : NonCopyable {
9105 virtual ~BoundRef() = default;
9106 virtual auto isContainer() const -> bool { return false; }
9107 virtual auto isFlag() const -> bool { return false; }
9109 struct BoundValueRefBase : BoundRef {
9110 virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
9112 struct BoundFlagRefBase : BoundRef {
9113 virtual auto setFlag( bool flag ) -> ParserResult = 0;
9114 virtual auto isFlag() const -> bool { return true; }
9117 template<typename T>
9118 struct BoundValueRef : BoundValueRefBase {
9121 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9123 auto setValue( std::string const &arg ) -> ParserResult override {
9124 return convertInto( arg, m_ref );
9128 template<typename T>
9129 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9130 std::vector<T> &m_ref;
9132 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9134 auto isContainer() const -> bool override { return true; }
9136 auto setValue( std::string const &arg ) -> ParserResult override {
9138 auto result = convertInto( arg, temp );
9140 m_ref.push_back( temp );
9145 struct BoundFlagRef : BoundFlagRefBase {
9148 explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
9150 auto setFlag( bool flag ) -> ParserResult override {
9152 return ParserResult::ok( ParseResultType::Matched );
9156 template<typename ReturnType>
9157 struct LambdaInvoker {
9158 static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
9160 template<typename L, typename ArgType>
9161 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9162 return lambda( arg );
9167 struct LambdaInvoker<void> {
9168 template<typename L, typename ArgType>
9169 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9171 return ParserResult::ok( ParseResultType::Matched );
9175 template<typename ArgType, typename L>
9176 inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
9178 auto result = convertInto( arg, temp );
9181 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9184 template<typename L>
9185 struct BoundLambda : BoundValueRefBase {
9188 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9189 explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
9191 auto setValue( std::string const &arg ) -> ParserResult override {
9192 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9196 template<typename L>
9197 struct BoundFlagLambda : BoundFlagRefBase {
9200 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9201 static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
9203 explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
9205 auto setFlag( bool flag ) -> ParserResult override {
9206 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9210 enum class Optionality { Optional, Required };
9216 virtual ~ParserBase() = default;
9217 virtual auto validate() const -> Result { return Result::ok(); }
9218 virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
9219 virtual auto cardinality() const -> size_t { return 1; }
9221 auto parse( Args const &args ) const -> InternalParseResult {
9222 return parse( args.exeName(), TokenStream( args ) );
9226 template<typename DerivedT>
9227 class ComposableParserImpl : public ParserBase {
9229 template<typename T>
9230 auto operator|( T const &other ) const -> Parser;
9232 template<typename T>
9233 auto operator+( T const &other ) const -> Parser;
9236 // Common code and state for Args and Opts
9237 template<typename DerivedT>
9238 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9240 Optionality m_optionality = Optionality::Optional;
9241 std::shared_ptr<BoundRef> m_ref;
9243 std::string m_description;
9245 explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
9248 template<typename T>
9249 ParserRefImpl( T &ref, std::string const &hint )
9250 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9254 template<typename LambdaT>
9255 ParserRefImpl( LambdaT const &ref, std::string const &hint )
9256 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9260 auto operator()( std::string const &description ) -> DerivedT & {
9261 m_description = description;
9262 return static_cast<DerivedT &>( *this );
9265 auto optional() -> DerivedT & {
9266 m_optionality = Optionality::Optional;
9267 return static_cast<DerivedT &>( *this );
9270 auto required() -> DerivedT & {
9271 m_optionality = Optionality::Required;
9272 return static_cast<DerivedT &>( *this );
9275 auto isOptional() const -> bool {
9276 return m_optionality == Optionality::Optional;
9279 auto cardinality() const -> size_t override {
9280 if( m_ref->isContainer() )
9286 auto hint() const -> std::string { return m_hint; }
9289 class ExeName : public ComposableParserImpl<ExeName> {
9290 std::shared_ptr<std::string> m_name;
9291 std::shared_ptr<BoundValueRefBase> m_ref;
9293 template<typename LambdaT>
9294 static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9295 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9299 ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
9301 explicit ExeName( std::string &ref ) : ExeName() {
9302 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9305 template<typename LambdaT>
9306 explicit ExeName( LambdaT const& lambda ) : ExeName() {
9307 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9310 // The exe name is not parsed out of the normal tokens, but is handled specially
9311 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9312 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9315 auto name() const -> std::string { return *m_name; }
9316 auto set( std::string const& newName ) -> ParserResult {
9318 auto lastSlash = newName.find_last_of( "\\/" );
9319 auto filename = ( lastSlash == std::string::npos )
9321 : newName.substr( lastSlash+1 );
9325 return m_ref->setValue( filename );
9327 return ParserResult::ok( ParseResultType::Matched );
9331 class Arg : public ParserRefImpl<Arg> {
9333 using ParserRefImpl::ParserRefImpl;
9335 auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9336 auto validationResult = validate();
9337 if( !validationResult )
9338 return InternalParseResult( validationResult );
9340 auto remainingTokens = tokens;
9341 auto const &token = *remainingTokens;
9342 if( token.type != TokenType::Argument )
9343 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9345 assert( !m_ref->isFlag() );
9346 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9348 auto result = valueRef->setValue( remainingTokens->token );
9350 return InternalParseResult( result );
9352 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9356 inline auto normaliseOpt( std::string const &optName ) -> std::string {
9357 #ifdef CATCH_PLATFORM_WINDOWS
9358 if( optName[0] == '/' )
9359 return "-" + optName.substr( 1 );
9365 class Opt : public ParserRefImpl<Opt> {
9367 std::vector<std::string> m_optNames;
9370 template<typename LambdaT>
9371 explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9373 explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9375 template<typename LambdaT>
9376 Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9378 template<typename T>
9379 Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9381 auto operator[]( std::string const &optName ) -> Opt & {
9382 m_optNames.push_back( optName );
9386 auto getHelpColumns() const -> std::vector<HelpColumns> {
9387 std::ostringstream oss;
9389 for( auto const &opt : m_optNames ) {
9396 if( !m_hint.empty() )
9397 oss << " <" << m_hint << ">";
9398 return { { oss.str(), m_description } };
9401 auto isMatch( std::string const &optToken ) const -> bool {
9402 auto normalisedToken = normaliseOpt( optToken );
9403 for( auto const &name : m_optNames ) {
9404 if( normaliseOpt( name ) == normalisedToken )
9410 using ParserBase::parse;
9412 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9413 auto validationResult = validate();
9414 if( !validationResult )
9415 return InternalParseResult( validationResult );
9417 auto remainingTokens = tokens;
9418 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9419 auto const &token = *remainingTokens;
9420 if( isMatch(token.token ) ) {
9421 if( m_ref->isFlag() ) {
9422 auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9423 auto result = flagRef->setFlag( true );
9425 return InternalParseResult( result );
9426 if( result.value() == ParseResultType::ShortCircuitAll )
9427 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9429 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9431 if( !remainingTokens )
9432 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9433 auto const &argToken = *remainingTokens;
9434 if( argToken.type != TokenType::Argument )
9435 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9436 auto result = valueRef->setValue( argToken.token );
9438 return InternalParseResult( result );
9439 if( result.value() == ParseResultType::ShortCircuitAll )
9440 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9442 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9445 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9448 auto validate() const -> Result override {
9449 if( m_optNames.empty() )
9450 return Result::logicError( "No options supplied to Opt" );
9451 for( auto const &name : m_optNames ) {
9453 return Result::logicError( "Option name cannot be empty" );
9454 #ifdef CATCH_PLATFORM_WINDOWS
9455 if( name[0] != '-' && name[0] != '/' )
9456 return Result::logicError( "Option name must begin with '-' or '/'" );
9458 if( name[0] != '-' )
9459 return Result::logicError( "Option name must begin with '-'" );
9462 return ParserRefImpl::validate();
9467 Help( bool &showHelpFlag )
9468 : Opt([&]( bool flag ) {
9469 showHelpFlag = flag;
9470 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9473 static_cast<Opt &>( *this )
9474 ("display usage information")
9475 ["-?"]["-h"]["--help"]
9480 struct Parser : ParserBase {
9482 mutable ExeName m_exeName;
9483 std::vector<Opt> m_options;
9484 std::vector<Arg> m_args;
9486 auto operator|=( ExeName const &exeName ) -> Parser & {
9487 m_exeName = exeName;
9491 auto operator|=( Arg const &arg ) -> Parser & {
9492 m_args.push_back(arg);
9496 auto operator|=( Opt const &opt ) -> Parser & {
9497 m_options.push_back(opt);
9501 auto operator|=( Parser const &other ) -> Parser & {
9502 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9503 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9507 template<typename T>
9508 auto operator|( T const &other ) const -> Parser {
9509 return Parser( *this ) |= other;
9512 // Forward deprecated interface with '+' instead of '|'
9513 template<typename T>
9514 auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9515 template<typename T>
9516 auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9518 auto getHelpColumns() const -> std::vector<HelpColumns> {
9519 std::vector<HelpColumns> cols;
9520 for (auto const &o : m_options) {
9521 auto childCols = o.getHelpColumns();
9522 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9527 void writeToStream( std::ostream &os ) const {
9528 if (!m_exeName.name().empty()) {
9529 os << "usage:\n" << " " << m_exeName.name() << " ";
9530 bool required = true, first = true;
9531 for( auto const &arg : m_args ) {
9536 if( arg.isOptional() && required ) {
9540 os << "<" << arg.hint() << ">";
9541 if( arg.cardinality() == 0 )
9546 if( !m_options.empty() )
9548 os << "\n\nwhere options are:" << std::endl;
9551 auto rows = getHelpColumns();
9552 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9553 size_t optWidth = 0;
9554 for( auto const &cols : rows )
9555 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9557 optWidth = (std::min)(optWidth, consoleWidth/2);
9559 for( auto const &cols : rows ) {
9561 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9562 TextFlow::Spacer(4) +
9563 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9564 os << row << std::endl;
9568 friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9569 parser.writeToStream( os );
9573 auto validate() const -> Result override {
9574 for( auto const &opt : m_options ) {
9575 auto result = opt.validate();
9579 for( auto const &arg : m_args ) {
9580 auto result = arg.validate();
9584 return Result::ok();
9587 using ParserBase::parse;
9589 auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9592 ParserBase const* parser = nullptr;
9595 const size_t totalParsers = m_options.size() + m_args.size();
9596 assert( totalParsers < 512 );
9597 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9598 ParserInfo parseInfos[512];
9602 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9603 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9606 m_exeName.set( exeName );
9608 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9609 while( result.value().remainingTokens() ) {
9610 bool tokenParsed = false;
9612 for( size_t i = 0; i < totalParsers; ++i ) {
9613 auto& parseInfo = parseInfos[i];
9614 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9615 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9618 if (result.value().type() != ParseResultType::NoMatch) {
9626 if( result.value().type() == ParseResultType::ShortCircuitAll )
9629 return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9631 // !TBD Check missing required options
9636 template<typename DerivedT>
9637 template<typename T>
9638 auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9639 return Parser() | static_cast<DerivedT const &>( *this ) | other;
9641 } // namespace detail
9643 // A Combined parser
9644 using detail::Parser;
9646 // A parser for options
9649 // A parser for arguments
9652 // Wrapper for argc, argv from main()
9655 // Specifies the name of the executable
9656 using detail::ExeName;
9658 // Convenience wrapper for option parser that specifies the help option
9661 // enum of result types from a parse
9662 using detail::ParseResultType;
9664 // Result type for parser operation
9665 using detail::ParserResult;
9667 }} // namespace Catch::clara
9671 #pragma clang diagnostic pop
9674 // Restore Clara's value for console width, if present
9675 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9676 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9677 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9680 // end catch_clara.h
9683 clara::Parser makeCommandLineParser( ConfigData& config );
9685 } // end namespace Catch
9687 // end catch_commandline.h
9693 clara::Parser makeCommandLineParser( ConfigData& config ) {
9695 using namespace clara;
9697 auto const setWarning = [&]( std::string const& warning ) {
9698 auto warningSet = [&]() {
9699 if( warning == "NoAssertions" )
9700 return WarnAbout::NoAssertions;
9702 if ( warning == "NoTests" )
9703 return WarnAbout::NoTests;
9705 return WarnAbout::Nothing;
9708 if (warningSet == WarnAbout::Nothing)
9709 return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9710 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9711 return ParserResult::ok( ParseResultType::Matched );
9713 auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9714 std::ifstream f( filename.c_str() );
9716 return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9719 while( std::getline( f, line ) ) {
9721 if( !line.empty() && !startsWith( line, '#' ) ) {
9722 if( !startsWith( line, '"' ) )
9723 line = '"' + line + '"';
9724 config.testsOrTags.push_back( line );
9725 config.testsOrTags.emplace_back( "," );
9728 //Remove comma in the end
9729 if(!config.testsOrTags.empty())
9730 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9732 return ParserResult::ok( ParseResultType::Matched );
9734 auto const setTestOrder = [&]( std::string const& order ) {
9735 if( startsWith( "declared", order ) )
9736 config.runOrder = RunTests::InDeclarationOrder;
9737 else if( startsWith( "lexical", order ) )
9738 config.runOrder = RunTests::InLexicographicalOrder;
9739 else if( startsWith( "random", order ) )
9740 config.runOrder = RunTests::InRandomOrder;
9742 return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9743 return ParserResult::ok( ParseResultType::Matched );
9745 auto const setRngSeed = [&]( std::string const& seed ) {
9746 if( seed != "time" )
9747 return clara::detail::convertInto( seed, config.rngSeed );
9748 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9749 return ParserResult::ok( ParseResultType::Matched );
9751 auto const setColourUsage = [&]( std::string const& useColour ) {
9752 auto mode = toLower( useColour );
9755 config.useColour = UseColour::Yes;
9756 else if( mode == "no" )
9757 config.useColour = UseColour::No;
9758 else if( mode == "auto" )
9759 config.useColour = UseColour::Auto;
9761 return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9762 return ParserResult::ok( ParseResultType::Matched );
9764 auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9765 auto keypressLc = toLower( keypress );
9766 if (keypressLc == "never")
9767 config.waitForKeypress = WaitForKeypress::Never;
9768 else if( keypressLc == "start" )
9769 config.waitForKeypress = WaitForKeypress::BeforeStart;
9770 else if( keypressLc == "exit" )
9771 config.waitForKeypress = WaitForKeypress::BeforeExit;
9772 else if( keypressLc == "both" )
9773 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9775 return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
9776 return ParserResult::ok( ParseResultType::Matched );
9778 auto const setVerbosity = [&]( std::string const& verbosity ) {
9779 auto lcVerbosity = toLower( verbosity );
9780 if( lcVerbosity == "quiet" )
9781 config.verbosity = Verbosity::Quiet;
9782 else if( lcVerbosity == "normal" )
9783 config.verbosity = Verbosity::Normal;
9784 else if( lcVerbosity == "high" )
9785 config.verbosity = Verbosity::High;
9787 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9788 return ParserResult::ok( ParseResultType::Matched );
9790 auto const setReporter = [&]( std::string const& reporter ) {
9791 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9793 auto lcReporter = toLower( reporter );
9794 auto result = factories.find( lcReporter );
9796 if( factories.end() != result )
9797 config.reporterName = lcReporter;
9799 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9800 return ParserResult::ok( ParseResultType::Matched );
9804 = ExeName( config.processName )
9805 | Help( config.showHelp )
9806 | Opt( config.listTests )
9807 ["-l"]["--list-tests"]
9808 ( "list all/matching test cases" )
9809 | Opt( config.listTags )
9810 ["-t"]["--list-tags"]
9811 ( "list all/matching tags" )
9812 | Opt( config.showSuccessfulTests )
9814 ( "include successful tests in output" )
9815 | Opt( config.shouldDebugBreak )
9817 ( "break into debugger on failure" )
9818 | Opt( config.noThrow )
9820 ( "skip exception tests" )
9821 | Opt( config.showInvisibles )
9822 ["-i"]["--invisibles"]
9823 ( "show invisibles (tabs, newlines)" )
9824 | Opt( config.outputFilename, "filename" )
9826 ( "output filename" )
9827 | Opt( setReporter, "name" )
9828 ["-r"]["--reporter"]
9829 ( "reporter to use (defaults to console)" )
9830 | Opt( config.name, "name" )
9833 | Opt( [&]( bool ){ config.abortAfter = 1; } )
9835 ( "abort at first failure" )
9836 | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9838 ( "abort after x failures" )
9839 | Opt( setWarning, "warning name" )
9841 ( "enable warnings" )
9842 | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9843 ["-d"]["--durations"]
9844 ( "show test durations" )
9845 | Opt( config.minDuration, "seconds" )
9846 ["-D"]["--min-duration"]
9847 ( "show test durations for tests taking at least the given number of seconds" )
9848 | Opt( loadTestNamesFromFile, "filename" )
9849 ["-f"]["--input-file"]
9850 ( "load test names to run from a file" )
9851 | Opt( config.filenamesAsTags )
9852 ["-#"]["--filenames-as-tags"]
9853 ( "adds a tag for the filename" )
9854 | Opt( config.sectionsToRun, "section name" )
9856 ( "specify section to run" )
9857 | Opt( setVerbosity, "quiet|normal|high" )
9858 ["-v"]["--verbosity"]
9859 ( "set output verbosity" )
9860 | Opt( config.listTestNamesOnly )
9861 ["--list-test-names-only"]
9862 ( "list all/matching test cases names only" )
9863 | Opt( config.listReporters )
9864 ["--list-reporters"]
9865 ( "list all reporters" )
9866 | Opt( setTestOrder, "decl|lex|rand" )
9868 ( "test case order (defaults to decl)" )
9869 | Opt( setRngSeed, "'time'|number" )
9871 ( "set a specific seed for random numbers" )
9872 | Opt( setColourUsage, "yes|no" )
9874 ( "should output be colourised" )
9875 | Opt( config.libIdentify )
9877 ( "report name and version according to libidentify standard" )
9878 | Opt( setWaitForKeypress, "never|start|exit|both" )
9879 ["--wait-for-keypress"]
9880 ( "waits for a keypress before exiting" )
9881 | Opt( config.benchmarkSamples, "samples" )
9882 ["--benchmark-samples"]
9883 ( "number of samples to collect (default: 100)" )
9884 | Opt( config.benchmarkResamples, "resamples" )
9885 ["--benchmark-resamples"]
9886 ( "number of resamples for the bootstrap (default: 100000)" )
9887 | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9888 ["--benchmark-confidence-interval"]
9889 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9890 | Opt( config.benchmarkNoAnalysis )
9891 ["--benchmark-no-analysis"]
9892 ( "perform only measurements; do not perform any analysis" )
9893 | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
9894 ["--benchmark-warmup-time"]
9895 ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
9896 | Arg( config.testsOrTags, "test name|pattern|tags" )
9897 ( "which test or tests to use" );
9902 } // end namespace Catch
9903 // end catch_commandline.cpp
9904 // start catch_common.cpp
9911 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9912 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9914 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9915 // We can assume that the same file will usually have the same pointer.
9916 // Thus, if the pointers are the same, there is no point in calling the strcmp
9917 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9920 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9922 os << info.file << '(' << info.line << ')';
9924 os << info.file << ':' << info.line;
9929 std::string StreamEndStop::operator+() const {
9930 return std::string();
9933 NonCopyable::NonCopyable() = default;
9934 NonCopyable::~NonCopyable() = default;
9937 // end catch_common.cpp
9938 // start catch_config.cpp
9942 Config::Config( ConfigData const& data )
9944 m_stream( openStream() )
9946 // We need to trim filter specs to avoid trouble with superfluous
9947 // whitespace (esp. important for bdd macros, as those are manually
9948 // aligned with whitespace).
9950 for (auto& elem : m_data.testsOrTags) {
9953 for (auto& elem : m_data.sectionsToRun) {
9957 TestSpecParser parser(ITagAliasRegistry::get());
9958 if (!m_data.testsOrTags.empty()) {
9959 m_hasTestFilters = true;
9960 for (auto const& testOrTags : m_data.testsOrTags) {
9961 parser.parse(testOrTags);
9964 m_testSpec = parser.testSpec();
9967 std::string const& Config::getFilename() const {
9968 return m_data.outputFilename ;
9971 bool Config::listTests() const { return m_data.listTests; }
9972 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
9973 bool Config::listTags() const { return m_data.listTags; }
9974 bool Config::listReporters() const { return m_data.listReporters; }
9976 std::string Config::getProcessName() const { return m_data.processName; }
9977 std::string const& Config::getReporterName() const { return m_data.reporterName; }
9979 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
9980 std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
9982 TestSpec const& Config::testSpec() const { return m_testSpec; }
9983 bool Config::hasTestFilters() const { return m_hasTestFilters; }
9985 bool Config::showHelp() const { return m_data.showHelp; }
9987 // IConfig interface
9988 bool Config::allowThrows() const { return !m_data.noThrow; }
9989 std::ostream& Config::stream() const { return m_stream->stream(); }
9990 std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
9991 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
9992 bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
9993 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
9994 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
9995 double Config::minDuration() const { return m_data.minDuration; }
9996 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
9997 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
9998 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
9999 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
10000 int Config::abortAfter() const { return m_data.abortAfter; }
10001 bool Config::showInvisibles() const { return m_data.showInvisibles; }
10002 Verbosity Config::verbosity() const { return m_data.verbosity; }
10004 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
10005 int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
10006 double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
10007 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
10008 std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10010 IStream const* Config::openStream() {
10011 return Catch::makeStream(m_data.outputFilename);
10014 } // end namespace Catch
10015 // end catch_config.cpp
10016 // start catch_console_colour.cpp
10018 #if defined(__clang__)
10019 # pragma clang diagnostic push
10020 # pragma clang diagnostic ignored "-Wexit-time-destructors"
10023 // start catch_errno_guard.h
10037 // end catch_errno_guard.h
10038 // start catch_windows_h_proxy.h
10041 #if defined(CATCH_PLATFORM_WINDOWS)
10043 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10044 # define CATCH_DEFINED_NOMINMAX
10047 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10048 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10049 # define WIN32_LEAN_AND_MEAN
10053 #include <AfxWin.h>
10055 #include <windows.h>
10058 #ifdef CATCH_DEFINED_NOMINMAX
10061 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10062 # undef WIN32_LEAN_AND_MEAN
10065 #endif // defined(CATCH_PLATFORM_WINDOWS)
10067 // end catch_windows_h_proxy.h
10073 struct IColourImpl {
10074 virtual ~IColourImpl() = default;
10075 virtual void use( Colour::Code _colourCode ) = 0;
10078 struct NoColourImpl : IColourImpl {
10079 void use( Colour::Code ) override {}
10081 static IColourImpl* instance() {
10082 static NoColourImpl s_instance;
10083 return &s_instance;
10087 } // anon namespace
10088 } // namespace Catch
10090 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10091 # ifdef CATCH_PLATFORM_WINDOWS
10092 # define CATCH_CONFIG_COLOUR_WINDOWS
10094 # define CATCH_CONFIG_COLOUR_ANSI
10098 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
10103 class Win32ColourImpl : public IColourImpl {
10105 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10107 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10108 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10109 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10110 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10113 void use( Colour::Code _colourCode ) override {
10114 switch( _colourCode ) {
10115 case Colour::None: return setTextAttribute( originalForegroundAttributes );
10116 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10117 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
10118 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
10119 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
10120 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10121 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10122 case Colour::Grey: return setTextAttribute( 0 );
10124 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
10125 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10126 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10127 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10128 case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10130 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10133 CATCH_ERROR( "Unknown colour requested" );
10138 void setTextAttribute( WORD _textAttribute ) {
10139 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10141 HANDLE stdoutHandle;
10142 WORD originalForegroundAttributes;
10143 WORD originalBackgroundAttributes;
10146 IColourImpl* platformColourInstance() {
10147 static Win32ColourImpl s_instance;
10149 IConfigPtr config = getCurrentContext().getConfig();
10150 UseColour::YesOrNo colourMode = config
10151 ? config->useColour()
10153 if( colourMode == UseColour::Auto )
10154 colourMode = UseColour::Yes;
10155 return colourMode == UseColour::Yes
10157 : NoColourImpl::instance();
10160 } // end anon namespace
10161 } // end namespace Catch
10163 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
10165 #include <unistd.h>
10170 // use POSIX/ ANSI console terminal codes
10171 // Thanks to Adam Strzelecki for original contribution
10172 // (http://github.com/nanoant)
10173 // https://github.com/philsquared/Catch/pull/131
10174 class PosixColourImpl : public IColourImpl {
10176 void use( Colour::Code _colourCode ) override {
10177 switch( _colourCode ) {
10179 case Colour::White: return setColour( "[0m" );
10180 case Colour::Red: return setColour( "[0;31m" );
10181 case Colour::Green: return setColour( "[0;32m" );
10182 case Colour::Blue: return setColour( "[0;34m" );
10183 case Colour::Cyan: return setColour( "[0;36m" );
10184 case Colour::Yellow: return setColour( "[0;33m" );
10185 case Colour::Grey: return setColour( "[1;30m" );
10187 case Colour::LightGrey: return setColour( "[0;37m" );
10188 case Colour::BrightRed: return setColour( "[1;31m" );
10189 case Colour::BrightGreen: return setColour( "[1;32m" );
10190 case Colour::BrightWhite: return setColour( "[1;37m" );
10191 case Colour::BrightYellow: return setColour( "[1;33m" );
10193 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10194 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
10197 static IColourImpl* instance() {
10198 static PosixColourImpl s_instance;
10199 return &s_instance;
10203 void setColour( const char* _escapeCode ) {
10204 getCurrentContext().getConfig()->stream()
10205 << '\033' << _escapeCode;
10209 bool useColourOnPlatform() {
10211 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10212 !isDebuggerActive() &&
10214 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10215 isatty(STDOUT_FILENO)
10221 IColourImpl* platformColourInstance() {
10223 IConfigPtr config = getCurrentContext().getConfig();
10224 UseColour::YesOrNo colourMode = config
10225 ? config->useColour()
10227 if( colourMode == UseColour::Auto )
10228 colourMode = useColourOnPlatform()
10231 return colourMode == UseColour::Yes
10232 ? PosixColourImpl::instance()
10233 : NoColourImpl::instance();
10236 } // end anon namespace
10237 } // end namespace Catch
10239 #else // not Windows or ANSI ///////////////////////////////////////////////
10243 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10245 } // end namespace Catch
10247 #endif // Windows/ ANSI/ None
10251 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10252 Colour::Colour( Colour&& other ) noexcept {
10253 m_moved = other.m_moved;
10254 other.m_moved = true;
10256 Colour& Colour::operator=( Colour&& other ) noexcept {
10257 m_moved = other.m_moved;
10258 other.m_moved = true;
10262 Colour::~Colour(){ if( !m_moved ) use( None ); }
10264 void Colour::use( Code _colourCode ) {
10265 static IColourImpl* impl = platformColourInstance();
10266 // Strictly speaking, this cannot possibly happen.
10267 // However, under some conditions it does happen (see #1626),
10268 // and this change is small enough that we can let practicality
10269 // triumph over purity in this case.
10270 if (impl != nullptr) {
10271 impl->use( _colourCode );
10275 std::ostream& operator << ( std::ostream& os, Colour const& ) {
10279 } // end namespace Catch
10281 #if defined(__clang__)
10282 # pragma clang diagnostic pop
10285 // end catch_console_colour.cpp
10286 // start catch_context.cpp
10290 class Context : public IMutableContext, NonCopyable {
10292 public: // IContext
10293 IResultCapture* getResultCapture() override {
10294 return m_resultCapture;
10296 IRunner* getRunner() override {
10300 IConfigPtr const& getConfig() const override {
10304 ~Context() override;
10306 public: // IMutableContext
10307 void setResultCapture( IResultCapture* resultCapture ) override {
10308 m_resultCapture = resultCapture;
10310 void setRunner( IRunner* runner ) override {
10313 void setConfig( IConfigPtr const& config ) override {
10317 friend IMutableContext& getCurrentMutableContext();
10320 IConfigPtr m_config;
10321 IRunner* m_runner = nullptr;
10322 IResultCapture* m_resultCapture = nullptr;
10325 IMutableContext *IMutableContext::currentContext = nullptr;
10327 void IMutableContext::createContext()
10329 currentContext = new Context();
10332 void cleanUpContext() {
10333 delete IMutableContext::currentContext;
10334 IMutableContext::currentContext = nullptr;
10336 IContext::~IContext() = default;
10337 IMutableContext::~IMutableContext() = default;
10338 Context::~Context() = default;
10340 SimplePcg32& rng() {
10341 static SimplePcg32 s_rng;
10346 // end catch_context.cpp
10347 // start catch_debug_console.cpp
10349 // start catch_debug_console.h
10354 void writeToDebugConsole( std::string const& text );
10357 // end catch_debug_console.h
10358 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10359 #include <android/log.h>
10362 void writeToDebugConsole( std::string const& text ) {
10363 __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
10367 #elif defined(CATCH_PLATFORM_WINDOWS)
10370 void writeToDebugConsole( std::string const& text ) {
10371 ::OutputDebugStringA( text.c_str() );
10378 void writeToDebugConsole( std::string const& text ) {
10379 // !TBD: Need a version for Mac/ XCode and other IDEs
10380 Catch::cout() << text;
10385 // end catch_debug_console.cpp
10386 // start catch_debugger.cpp
10388 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10390 # include <cassert>
10391 # include <sys/types.h>
10392 # include <unistd.h>
10393 # include <cstddef>
10394 # include <ostream>
10396 #ifdef __apple_build_version__
10397 // These headers will only compile with AppleClang (XCode)
10398 // For other compilers (Clang, GCC, ... ) we need to exclude them
10399 # include <sys/sysctl.h>
10403 #ifdef __apple_build_version__
10404 // The following function is taken directly from the following technical note:
10405 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10407 // Returns true if the current process is being debugged (either
10408 // running under the debugger or has a debugger attached post facto).
10409 bool isDebuggerActive(){
10411 struct kinfo_proc info;
10414 // Initialize the flags so that, if sysctl fails for some bizarre
10415 // reason, we get a predictable result.
10417 info.kp_proc.p_flag = 0;
10419 // Initialize mib, which tells sysctl the info we want, in this case
10420 // we're looking for information about a specific process ID.
10423 mib[1] = KERN_PROC;
10424 mib[2] = KERN_PROC_PID;
10429 size = sizeof(info);
10430 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10431 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10435 // We're being debugged if the P_TRACED flag is set.
10437 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10440 bool isDebuggerActive() {
10441 // We need to find another way to determine this for non-appleclang compilers on macOS
10445 } // namespace Catch
10447 #elif defined(CATCH_PLATFORM_LINUX)
10452 // The standard POSIX way of detecting a debugger is to attempt to
10453 // ptrace() the process, but this needs to be done from a child and not
10454 // this process itself to still allow attaching to this process later
10455 // if wanted, so is rather heavy. Under Linux we have the PID of the
10456 // "debugger" (which doesn't need to be gdb, of course, it could also
10457 // be strace, for example) in /proc/$PID/status, so just get it from
10459 bool isDebuggerActive(){
10460 // Libstdc++ has a bug, where std::ifstream sets errno to 0
10461 // This way our users can properly assert over errno values
10463 std::ifstream in("/proc/self/status");
10464 for( std::string line; std::getline(in, line); ) {
10465 static const int PREFIX_LEN = 11;
10466 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10467 // We're traced if the PID is not 0 and no other PID starts
10468 // with 0 digit, so it's enough to check for just a single
10470 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10476 } // namespace Catch
10477 #elif defined(_MSC_VER)
10478 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10480 bool isDebuggerActive() {
10481 return IsDebuggerPresent() != 0;
10484 #elif defined(__MINGW32__)
10485 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10487 bool isDebuggerActive() {
10488 return IsDebuggerPresent() != 0;
10493 bool isDebuggerActive() { return false; }
10496 // end catch_debugger.cpp
10497 // start catch_decomposer.cpp
10501 ITransientExpression::~ITransientExpression() = default;
10503 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10504 if( lhs.size() + rhs.size() < 40 &&
10505 lhs.find('\n') == std::string::npos &&
10506 rhs.find('\n') == std::string::npos )
10507 os << lhs << " " << op << " " << rhs;
10509 os << lhs << "\n" << op << "\n" << rhs;
10512 // end catch_decomposer.cpp
10513 // start catch_enforce.cpp
10515 #include <stdexcept>
10518 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10520 void throw_exception(std::exception const& e) {
10521 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10522 << "The message was: " << e.what() << '\n';
10528 void throw_logic_error(std::string const& msg) {
10529 throw_exception(std::logic_error(msg));
10533 void throw_domain_error(std::string const& msg) {
10534 throw_exception(std::domain_error(msg));
10538 void throw_runtime_error(std::string const& msg) {
10539 throw_exception(std::runtime_error(msg));
10542 } // namespace Catch;
10543 // end catch_enforce.cpp
10544 // start catch_enum_values_registry.cpp
10545 // start catch_enum_values_registry.h
10554 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10556 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10558 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10560 EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10563 std::vector<StringRef> parseEnums( StringRef enums );
10569 // end catch_enum_values_registry.h
10576 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10581 // Extracts the actual name part of an enum instance
10582 // In other words, it returns the Blue part of Bikeshed::Colour::Blue
10583 StringRef extractInstanceName(StringRef enumInstance) {
10584 // Find last occurrence of ":"
10585 size_t name_start = enumInstance.size();
10586 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
10589 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10593 std::vector<StringRef> parseEnums( StringRef enums ) {
10594 auto enumValues = splitStringRef( enums, ',' );
10595 std::vector<StringRef> parsed;
10596 parsed.reserve( enumValues.size() );
10597 for( auto const& enumValue : enumValues ) {
10598 parsed.push_back(trim(extractInstanceName(enumValue)));
10603 EnumInfo::~EnumInfo() {}
10605 StringRef EnumInfo::lookup( int value ) const {
10606 for( auto const& valueToName : m_values ) {
10607 if( valueToName.first == value )
10608 return valueToName.second;
10610 return "{** unexpected enum value **}"_sr;
10613 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10614 std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10615 enumInfo->m_name = enumName;
10616 enumInfo->m_values.reserve( values.size() );
10618 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10619 assert( valueNames.size() == values.size() );
10621 for( auto value : values )
10622 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10627 EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10628 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10629 return *m_enumInfos.back();
10635 // end catch_enum_values_registry.cpp
10636 // start catch_errno_guard.cpp
10641 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10642 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10644 // end catch_errno_guard.cpp
10645 // start catch_exception_translator_registry.cpp
10647 // start catch_exception_translator_registry.h
10655 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10657 ~ExceptionTranslatorRegistry();
10658 virtual void registerTranslator( const IExceptionTranslator* translator );
10659 std::string translateActiveException() const override;
10660 std::string tryTranslators() const;
10663 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10667 // end catch_exception_translator_registry.h
10669 #import "Foundation/Foundation.h"
10674 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10677 void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10678 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10681 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10682 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10685 // In Objective-C try objective-c exceptions first
10687 return tryTranslators();
10689 @catch (NSException *exception) {
10690 return Catch::Detail::stringify( [exception description] );
10693 // Compiling a mixed mode project with MSVC means that CLR
10694 // exceptions will be caught in (...) as well. However, these
10695 // do not fill-in std::current_exception and thus lead to crash
10696 // when attempting rethrow.
10697 // /EHa switch also causes structured exceptions to be caught
10698 // here, but they fill-in current_exception properly, so
10699 // at worst the output should be a little weird, instead of
10700 // causing a crash.
10701 if (std::current_exception() == nullptr) {
10702 return "Non C++ exception. Possibly a CLR exception.";
10704 return tryTranslators();
10707 catch( TestFailureException& ) {
10708 std::rethrow_exception(std::current_exception());
10710 catch( std::exception& ex ) {
10713 catch( std::string& msg ) {
10716 catch( const char* msg ) {
10720 return "Unknown exception";
10724 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10725 if (m_translators.empty()) {
10726 std::rethrow_exception(std::current_exception());
10728 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10732 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
10733 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10734 CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10737 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10738 CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10743 // end catch_exception_translator_registry.cpp
10744 // start catch_fatal_condition.cpp
10746 #include <algorithm>
10748 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
10752 // If neither SEH nor signal handling is required, the handler impls
10753 // do not have to do anything, and can be empty.
10754 void FatalConditionHandler::engage_platform() {}
10755 void FatalConditionHandler::disengage_platform() {}
10756 FatalConditionHandler::FatalConditionHandler() = default;
10757 FatalConditionHandler::~FatalConditionHandler() = default;
10759 } // end namespace Catch
10761 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
10763 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
10764 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10765 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
10767 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10770 //! Signals fatal error message to the run context
10771 void reportFatal( char const * const message ) {
10772 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10775 //! Minimal size Catch2 needs for its own fatal error handling.
10776 //! Picked anecdotally, so it might not be sufficient on all
10777 //! platforms, and for all configurations.
10778 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10779 } // end unnamed namespace
10781 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
10783 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10787 struct SignalDefs { DWORD id; const char* name; };
10789 // There is no 1-1 mapping between signals and windows exceptions.
10790 // Windows can easily distinguish between SO and SigSegV,
10791 // but SigInt, SigTerm, etc are handled differently.
10792 static SignalDefs signalDefs[] = {
10793 { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
10794 { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10795 { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10796 { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10799 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10800 for (auto const& def : signalDefs) {
10801 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10802 reportFatal(def.name);
10805 // If its not an exception we care about, pass it along.
10806 // This stops us from eating debugger breaks etc.
10807 return EXCEPTION_CONTINUE_SEARCH;
10810 // Since we do not support multiple instantiations, we put these
10811 // into global variables and rely on cleaning them up in outlined
10812 // constructors/destructors
10813 static PVOID exceptionHandlerHandle = nullptr;
10815 // For MSVC, we reserve part of the stack memory for handling
10816 // memory overflow structured exception.
10817 FatalConditionHandler::FatalConditionHandler() {
10818 ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
10819 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10820 // We do not want to fully error out, because needing
10821 // the stack reserve should be rare enough anyway.
10823 << "Failed to reserve piece of stack."
10824 << " Stack overflows will not be reported successfully.";
10828 // We do not attempt to unset the stack guarantee, because
10829 // Windows does not support lowering the stack size guarantee.
10830 FatalConditionHandler::~FatalConditionHandler() = default;
10832 void FatalConditionHandler::engage_platform() {
10833 // Register as first handler in current chain
10834 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10835 if (!exceptionHandlerHandle) {
10836 CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
10840 void FatalConditionHandler::disengage_platform() {
10841 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10842 CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
10844 exceptionHandlerHandle = nullptr;
10847 } // end namespace Catch
10849 #endif // CATCH_CONFIG_WINDOWS_SEH
10851 #if defined( CATCH_CONFIG_POSIX_SIGNALS )
10853 #include <signal.h>
10857 struct SignalDefs {
10862 static SignalDefs signalDefs[] = {
10863 { SIGINT, "SIGINT - Terminal interrupt signal" },
10864 { SIGILL, "SIGILL - Illegal instruction signal" },
10865 { SIGFPE, "SIGFPE - Floating point error signal" },
10866 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10867 { SIGTERM, "SIGTERM - Termination request signal" },
10868 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10871 // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
10872 // which is zero initialization, but not explicit. We want to avoid
10874 #if defined(__GNUC__)
10875 # pragma GCC diagnostic push
10876 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10879 static char* altStackMem = nullptr;
10880 static std::size_t altStackSize = 0;
10881 static stack_t oldSigStack{};
10882 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10884 static void restorePreviousSignalHandlers() {
10885 // We set signal handlers back to the previous ones. Hopefully
10886 // nobody overwrote them in the meantime, and doesn't expect
10887 // their signal handlers to live past ours given that they
10888 // installed them after ours..
10889 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
10890 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10892 // Return the old stack
10893 sigaltstack(&oldSigStack, nullptr);
10896 static void handleSignal( int sig ) {
10897 char const * name = "<unknown signal>";
10898 for (auto const& def : signalDefs) {
10899 if (sig == def.id) {
10904 // We need to restore previous signal handlers and let them do
10905 // their thing, so that the users can have the debugger break
10906 // when a signal is raised, and so on.
10907 restorePreviousSignalHandlers();
10908 reportFatal( name );
10912 FatalConditionHandler::FatalConditionHandler() {
10913 assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
10914 if (altStackSize == 0) {
10915 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10917 altStackMem = new char[altStackSize]();
10920 FatalConditionHandler::~FatalConditionHandler() {
10921 delete[] altStackMem;
10922 // We signal that another instance can be constructed by zeroing
10923 // out the pointer.
10924 altStackMem = nullptr;
10927 void FatalConditionHandler::engage_platform() {
10929 sigStack.ss_sp = altStackMem;
10930 sigStack.ss_size = altStackSize;
10931 sigStack.ss_flags = 0;
10932 sigaltstack(&sigStack, &oldSigStack);
10933 struct sigaction sa = { };
10935 sa.sa_handler = handleSignal;
10936 sa.sa_flags = SA_ONSTACK;
10937 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10938 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10942 #if defined(__GNUC__)
10943 # pragma GCC diagnostic pop
10946 void FatalConditionHandler::disengage_platform() {
10947 restorePreviousSignalHandlers();
10950 } // end namespace Catch
10952 #endif // CATCH_CONFIG_POSIX_SIGNALS
10953 // end catch_fatal_condition.cpp
10954 // start catch_generators.cpp
10961 IGeneratorTracker::~IGeneratorTracker() {}
10963 const char* GeneratorException::what() const noexcept {
10967 namespace Generators {
10969 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10971 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10972 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10975 } // namespace Generators
10976 } // namespace Catch
10977 // end catch_generators.cpp
10978 // start catch_interfaces_capture.cpp
10981 IResultCapture::~IResultCapture() = default;
10983 // end catch_interfaces_capture.cpp
10984 // start catch_interfaces_config.cpp
10987 IConfig::~IConfig() = default;
10989 // end catch_interfaces_config.cpp
10990 // start catch_interfaces_exception.cpp
10993 IExceptionTranslator::~IExceptionTranslator() = default;
10994 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
10996 // end catch_interfaces_exception.cpp
10997 // start catch_interfaces_registry_hub.cpp
11000 IRegistryHub::~IRegistryHub() = default;
11001 IMutableRegistryHub::~IMutableRegistryHub() = default;
11003 // end catch_interfaces_registry_hub.cpp
11004 // start catch_interfaces_reporter.cpp
11006 // start catch_reporter_listening.h
11010 class ListeningReporter : public IStreamingReporter {
11011 using Reporters = std::vector<IStreamingReporterPtr>;
11012 Reporters m_listeners;
11013 IStreamingReporterPtr m_reporter = nullptr;
11014 ReporterPreferences m_preferences;
11017 ListeningReporter();
11019 void addListener( IStreamingReporterPtr&& listener );
11020 void addReporter( IStreamingReporterPtr&& reporter );
11022 public: // IStreamingReporter
11024 ReporterPreferences getPreferences() const override;
11026 void noMatchingTestCases( std::string const& spec ) override;
11028 void reportInvalidArguments(std::string const&arg) override;
11030 static std::set<Verbosity> getSupportedVerbosities();
11032 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11033 void benchmarkPreparing(std::string const& name) override;
11034 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
11035 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11036 void benchmarkFailed(std::string const&) override;
11037 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11039 void testRunStarting( TestRunInfo const& testRunInfo ) override;
11040 void testGroupStarting( GroupInfo const& groupInfo ) override;
11041 void testCaseStarting( TestCaseInfo const& testInfo ) override;
11042 void sectionStarting( SectionInfo const& sectionInfo ) override;
11043 void assertionStarting( AssertionInfo const& assertionInfo ) override;
11045 // The return value indicates if the messages buffer should be cleared:
11046 bool assertionEnded( AssertionStats const& assertionStats ) override;
11047 void sectionEnded( SectionStats const& sectionStats ) override;
11048 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11049 void testGroupEnded( TestGroupStats const& testGroupStats ) override;
11050 void testRunEnded( TestRunStats const& testRunStats ) override;
11052 void skipTest( TestCaseInfo const& testInfo ) override;
11053 bool isMulti() const override;
11057 } // end namespace Catch
11059 // end catch_reporter_listening.h
11062 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
11063 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11065 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
11066 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11068 std::ostream& ReporterConfig::stream() const { return *m_stream; }
11069 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11071 TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
11073 GroupInfo::GroupInfo( std::string const& _name,
11074 std::size_t _groupIndex,
11075 std::size_t _groupsCount )
11077 groupIndex( _groupIndex ),
11078 groupsCounts( _groupsCount )
11081 AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
11082 std::vector<MessageInfo> const& _infoMessages,
11083 Totals const& _totals )
11084 : assertionResult( _assertionResult ),
11085 infoMessages( _infoMessages ),
11088 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11090 if( assertionResult.hasMessage() ) {
11091 // Copy message into messages list.
11092 // !TBD This should have been done earlier, somewhere
11093 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11094 builder << assertionResult.getMessage();
11095 builder.m_info.message = builder.m_stream.str();
11097 infoMessages.push_back( builder.m_info );
11101 AssertionStats::~AssertionStats() = default;
11103 SectionStats::SectionStats( SectionInfo const& _sectionInfo,
11104 Counts const& _assertions,
11105 double _durationInSeconds,
11106 bool _missingAssertions )
11107 : sectionInfo( _sectionInfo ),
11108 assertions( _assertions ),
11109 durationInSeconds( _durationInSeconds ),
11110 missingAssertions( _missingAssertions )
11113 SectionStats::~SectionStats() = default;
11115 TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
11116 Totals const& _totals,
11117 std::string const& _stdOut,
11118 std::string const& _stdErr,
11120 : testInfo( _testInfo ),
11124 aborting( _aborting )
11127 TestCaseStats::~TestCaseStats() = default;
11129 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
11130 Totals const& _totals,
11132 : groupInfo( _groupInfo ),
11134 aborting( _aborting )
11137 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
11138 : groupInfo( _groupInfo ),
11142 TestGroupStats::~TestGroupStats() = default;
11144 TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
11145 Totals const& _totals,
11147 : runInfo( _runInfo ),
11149 aborting( _aborting )
11152 TestRunStats::~TestRunStats() = default;
11154 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
11155 bool IStreamingReporter::isMulti() const { return false; }
11157 IReporterFactory::~IReporterFactory() = default;
11158 IReporterRegistry::~IReporterRegistry() = default;
11160 } // end namespace Catch
11161 // end catch_interfaces_reporter.cpp
11162 // start catch_interfaces_runner.cpp
11165 IRunner::~IRunner() = default;
11167 // end catch_interfaces_runner.cpp
11168 // start catch_interfaces_testcase.cpp
11171 ITestInvoker::~ITestInvoker() = default;
11172 ITestCaseRegistry::~ITestCaseRegistry() = default;
11174 // end catch_interfaces_testcase.cpp
11175 // start catch_leak_detector.cpp
11177 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11178 #include <crtdbg.h>
11182 LeakDetector::LeakDetector() {
11183 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11184 flag |= _CRTDBG_LEAK_CHECK_DF;
11185 flag |= _CRTDBG_ALLOC_MEM_DF;
11186 _CrtSetDbgFlag(flag);
11187 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11188 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11189 // Change this to leaking allocation's number to break there
11190 _CrtSetBreakAlloc(-1);
11196 Catch::LeakDetector::LeakDetector() {}
11200 Catch::LeakDetector::~LeakDetector() {
11203 // end catch_leak_detector.cpp
11204 // start catch_list.cpp
11206 // start catch_list.h
11212 std::size_t listTests( Config const& config );
11214 std::size_t listTestsNamesOnly( Config const& config );
11217 void add( std::string const& spelling );
11218 std::string all() const;
11220 std::set<std::string> spellings;
11221 std::size_t count = 0;
11224 std::size_t listTags( Config const& config );
11226 std::size_t listReporters();
11228 Option<std::size_t> list( std::shared_ptr<Config> const& config );
11230 } // end namespace Catch
11232 // end catch_list.h
11233 // start catch_text.h
11236 using namespace clara::TextFlow;
11239 // end catch_text.h
11241 #include <algorithm>
11246 std::size_t listTests( Config const& config ) {
11247 TestSpec const& testSpec = config.testSpec();
11248 if( config.hasTestFilters() )
11249 Catch::cout() << "Matching test cases:\n";
11251 Catch::cout() << "All available test cases:\n";
11254 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11255 for( auto const& testCaseInfo : matchedTestCases ) {
11256 Colour::Code colour = testCaseInfo.isHidden()
11257 ? Colour::SecondaryText
11259 Colour colourGuard( colour );
11261 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
11262 if( config.verbosity() >= Verbosity::High ) {
11263 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11264 std::string description = testCaseInfo.description;
11265 if( description.empty() )
11266 description = "(NO DESCRIPTION)";
11267 Catch::cout() << Column( description ).indent(4) << std::endl;
11269 if( !testCaseInfo.tags.empty() )
11270 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
11273 if( !config.hasTestFilters() )
11274 Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
11276 Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
11277 return matchedTestCases.size();
11280 std::size_t listTestsNamesOnly( Config const& config ) {
11281 TestSpec const& testSpec = config.testSpec();
11282 std::size_t matchedTests = 0;
11283 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11284 for( auto const& testCaseInfo : matchedTestCases ) {
11286 if( startsWith( testCaseInfo.name, '#' ) )
11287 Catch::cout() << '"' << testCaseInfo.name << '"';
11289 Catch::cout() << testCaseInfo.name;
11290 if ( config.verbosity() >= Verbosity::High )
11291 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11292 Catch::cout() << std::endl;
11294 return matchedTests;
11297 void TagInfo::add( std::string const& spelling ) {
11299 spellings.insert( spelling );
11302 std::string TagInfo::all() const {
11304 for (auto const& spelling : spellings) {
11305 // Add 2 for the brackes
11306 size += spelling.size() + 2;
11309 std::string out; out.reserve(size);
11310 for (auto const& spelling : spellings) {
11318 std::size_t listTags( Config const& config ) {
11319 TestSpec const& testSpec = config.testSpec();
11320 if( config.hasTestFilters() )
11321 Catch::cout() << "Tags for matching test cases:\n";
11323 Catch::cout() << "All available tags:\n";
11326 std::map<std::string, TagInfo> tagCounts;
11328 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11329 for( auto const& testCase : matchedTestCases ) {
11330 for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
11331 std::string lcaseTagName = toLower( tagName );
11332 auto countIt = tagCounts.find( lcaseTagName );
11333 if( countIt == tagCounts.end() )
11334 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11335 countIt->second.add( tagName );
11339 for( auto const& tagCount : tagCounts ) {
11340 ReusableStringStream rss;
11341 rss << " " << std::setw(2) << tagCount.second.count << " ";
11342 auto str = rss.str();
11343 auto wrapper = Column( tagCount.second.all() )
11344 .initialIndent( 0 )
11345 .indent( str.size() )
11346 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11347 Catch::cout() << str << wrapper << '\n';
11349 Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
11350 return tagCounts.size();
11353 std::size_t listReporters() {
11354 Catch::cout() << "Available reporters:\n";
11355 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
11356 std::size_t maxNameLen = 0;
11357 for( auto const& factoryKvp : factories )
11358 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11360 for( auto const& factoryKvp : factories ) {
11362 << Column( factoryKvp.first + ":" )
11364 .width( 5+maxNameLen )
11365 + Column( factoryKvp.second->getDescription() )
11368 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11371 Catch::cout() << std::endl;
11372 return factories.size();
11375 Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
11376 Option<std::size_t> listedCount;
11377 getCurrentMutableContext().setConfig( config );
11378 if( config->listTests() )
11379 listedCount = listedCount.valueOr(0) + listTests( *config );
11380 if( config->listTestNamesOnly() )
11381 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11382 if( config->listTags() )
11383 listedCount = listedCount.valueOr(0) + listTags( *config );
11384 if( config->listReporters() )
11385 listedCount = listedCount.valueOr(0) + listReporters();
11386 return listedCount;
11389 } // end namespace Catch
11390 // end catch_list.cpp
11391 // start catch_matchers.cpp
11394 namespace Matchers {
11397 std::string MatcherUntypedBase::toString() const {
11398 if( m_cachedToString.empty() )
11399 m_cachedToString = describe();
11400 return m_cachedToString;
11403 MatcherUntypedBase::~MatcherUntypedBase() = default;
11405 } // namespace Impl
11406 } // namespace Matchers
11408 using namespace Matchers;
11409 using Matchers::Impl::MatcherBase;
11411 } // namespace Catch
11412 // end catch_matchers.cpp
11413 // start catch_matchers_exception.cpp
11416 namespace Matchers {
11417 namespace Exception {
11419 bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11420 return ex.what() == m_message;
11423 std::string ExceptionMessageMatcher::describe() const {
11424 return "exception message matches \"" + m_message + "\"";
11428 Exception::ExceptionMessageMatcher Message(std::string const& message) {
11429 return Exception::ExceptionMessageMatcher(message);
11432 // namespace Exception
11433 } // namespace Matchers
11434 } // namespace Catch
11435 // end catch_matchers_exception.cpp
11436 // start catch_matchers_floating.cpp
11438 // start catch_polyfills.hpp
11441 bool isnan(float f);
11442 bool isnan(double d);
11445 // end catch_polyfills.hpp
11446 // start catch_to_string.hpp
11451 template <typename T>
11452 std::string to_string(T const& t) {
11453 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11454 return std::to_string(t);
11456 ReusableStringStream rss;
11461 } // end namespace Catch
11463 // end catch_to_string.hpp
11464 #include <algorithm>
11470 #include <type_traits>
11477 int32_t convert(float f) {
11478 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
11480 std::memcpy(&i, &f, sizeof(f));
11484 int64_t convert(double d) {
11485 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
11487 std::memcpy(&i, &d, sizeof(d));
11491 template <typename FP>
11492 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11493 // Comparison with NaN should always be false.
11494 // This way we can rule it out before getting into the ugly details
11495 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11499 auto lc = convert(lhs);
11500 auto rc = convert(rhs);
11502 if ((lc < 0) != (rc < 0)) {
11503 // Potentially we can have +0 and -0
11507 // static cast as a workaround for IBM XLC
11508 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11509 return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11512 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11514 float nextafter(float x, float y) {
11515 return ::nextafterf(x, y);
11518 double nextafter(double x, double y) {
11519 return ::nextafter(x, y);
11522 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11524 template <typename FP>
11525 FP step(FP start, FP direction, uint64_t steps) {
11526 for (uint64_t i = 0; i < steps; ++i) {
11527 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11528 start = Catch::nextafter(start, direction);
11530 start = std::nextafter(start, direction);
11536 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11537 // But without the subtraction to allow for INFINITY in comparison
11538 bool marginComparison(double lhs, double rhs, double margin) {
11539 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11542 template <typename FloatingPoint>
11543 void write(std::ostream& out, FloatingPoint num) {
11544 out << std::scientific
11545 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11549 } // end anonymous namespace
11551 namespace Matchers {
11552 namespace Floating {
11554 enum class FloatingPointKind : uint8_t {
11559 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11560 :m_target{ target }, m_margin{ margin } {
11561 CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11562 << " Margin has to be non-negative.");
11565 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11566 // But without the subtraction to allow for INFINITY in comparison
11567 bool WithinAbsMatcher::match(double const& matchee) const {
11568 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11571 std::string WithinAbsMatcher::describe() const {
11572 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11575 WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
11576 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11577 CATCH_ENFORCE(m_type == FloatingPointKind::Double
11578 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11579 "Provided ULP is impossibly large for a float comparison.");
11582 #if defined(__clang__)
11583 #pragma clang diagnostic push
11584 // Clang <3.5 reports on the default branch in the switch below
11585 #pragma clang diagnostic ignored "-Wunreachable-code"
11588 bool WithinUlpsMatcher::match(double const& matchee) const {
11590 case FloatingPointKind::Float:
11591 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11592 case FloatingPointKind::Double:
11593 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11595 CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11599 #if defined(__clang__)
11600 #pragma clang diagnostic pop
11603 std::string WithinUlpsMatcher::describe() const {
11604 std::stringstream ret;
11606 ret << "is within " << m_ulps << " ULPs of ";
11608 if (m_type == FloatingPointKind::Float) {
11609 write(ret, static_cast<float>(m_target));
11612 write(ret, m_target);
11616 if (m_type == FloatingPointKind::Double) {
11617 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11619 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11621 // We have to cast INFINITY to float because of MinGW, see #1782
11622 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11624 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11631 WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
11633 m_epsilon(epsilon){
11634 CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
11635 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
11638 bool WithinRelMatcher::match(double const& matchee) const {
11639 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11640 return marginComparison(matchee, m_target,
11641 std::isinf(relMargin)? 0 : relMargin);
11644 std::string WithinRelMatcher::describe() const {
11645 Catch::ReusableStringStream sstr;
11646 sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
11650 }// namespace Floating
11652 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11653 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11656 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11657 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11660 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11661 return Floating::WithinAbsMatcher(target, margin);
11664 Floating::WithinRelMatcher WithinRel(double target, double eps) {
11665 return Floating::WithinRelMatcher(target, eps);
11668 Floating::WithinRelMatcher WithinRel(double target) {
11669 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11672 Floating::WithinRelMatcher WithinRel(float target, float eps) {
11673 return Floating::WithinRelMatcher(target, eps);
11676 Floating::WithinRelMatcher WithinRel(float target) {
11677 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11680 } // namespace Matchers
11681 } // namespace Catch
11682 // end catch_matchers_floating.cpp
11683 // start catch_matchers_generic.cpp
11685 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11686 if (desc.empty()) {
11687 return "matches undescribed predicate";
11689 return "matches predicate: \"" + desc + '"';
11692 // end catch_matchers_generic.cpp
11693 // start catch_matchers_string.cpp
11698 namespace Matchers {
11700 namespace StdString {
11702 CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11703 : m_caseSensitivity( caseSensitivity ),
11704 m_str( adjustString( str ) )
11706 std::string CasedString::adjustString( std::string const& str ) const {
11707 return m_caseSensitivity == CaseSensitive::No
11711 std::string CasedString::caseSensitivitySuffix() const {
11712 return m_caseSensitivity == CaseSensitive::No
11713 ? " (case insensitive)"
11717 StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11718 : m_comparator( comparator ),
11719 m_operation( operation ) {
11722 std::string StringMatcherBase::describe() const {
11723 std::string description;
11724 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11725 m_comparator.caseSensitivitySuffix().size());
11726 description += m_operation;
11727 description += ": \"";
11728 description += m_comparator.m_str;
11729 description += "\"";
11730 description += m_comparator.caseSensitivitySuffix();
11731 return description;
11734 EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11736 bool EqualsMatcher::match( std::string const& source ) const {
11737 return m_comparator.adjustString( source ) == m_comparator.m_str;
11740 ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11742 bool ContainsMatcher::match( std::string const& source ) const {
11743 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11746 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11748 bool StartsWithMatcher::match( std::string const& source ) const {
11749 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11752 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11754 bool EndsWithMatcher::match( std::string const& source ) const {
11755 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11758 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11760 bool RegexMatcher::match(std::string const& matchee) const {
11761 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11762 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11763 flags |= std::regex::icase;
11765 auto reg = std::regex(m_regex, flags);
11766 return std::regex_match(matchee, reg);
11769 std::string RegexMatcher::describe() const {
11770 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11773 } // namespace StdString
11775 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11776 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11778 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11779 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11781 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11782 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11784 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11785 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11788 StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11789 return StdString::RegexMatcher(regex, caseSensitivity);
11792 } // namespace Matchers
11793 } // namespace Catch
11794 // end catch_matchers_string.cpp
11795 // start catch_message.cpp
11797 // start catch_uncaught_exceptions.h
11800 bool uncaught_exceptions();
11801 } // end namespace Catch
11803 // end catch_uncaught_exceptions.h
11809 MessageInfo::MessageInfo( StringRef const& _macroName,
11810 SourceLineInfo const& _lineInfo,
11811 ResultWas::OfType _type )
11812 : macroName( _macroName ),
11813 lineInfo( _lineInfo ),
11815 sequence( ++globalCount )
11818 bool MessageInfo::operator==( MessageInfo const& other ) const {
11819 return sequence == other.sequence;
11822 bool MessageInfo::operator<( MessageInfo const& other ) const {
11823 return sequence < other.sequence;
11826 // This may need protecting if threading support is added
11827 unsigned int MessageInfo::globalCount = 0;
11829 ////////////////////////////////////////////////////////////////////////////
11831 Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11832 SourceLineInfo const& lineInfo,
11833 ResultWas::OfType type )
11834 :m_info(macroName, lineInfo, type) {}
11836 ////////////////////////////////////////////////////////////////////////////
11838 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11839 : m_info( builder.m_info ), m_moved()
11841 m_info.message = builder.m_stream.str();
11842 getResultCapture().pushScopedMessage( m_info );
11845 ScopedMessage::ScopedMessage( ScopedMessage&& old )
11846 : m_info( old.m_info ), m_moved()
11848 old.m_moved = true;
11851 ScopedMessage::~ScopedMessage() {
11852 if ( !uncaught_exceptions() && !m_moved ){
11853 getResultCapture().popScopedMessage(m_info);
11857 Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11858 auto trimmed = [&] (size_t start, size_t end) {
11859 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
11862 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
11865 return names.substr(start, end - start + 1);
11867 auto skipq = [&] (size_t start, char quote) {
11868 for (auto i = start + 1; i < names.size() ; ++i) {
11869 if (names[i] == quote)
11871 if (names[i] == '\\')
11874 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11878 std::stack<char> openings;
11879 for (size_t pos = 0; pos < names.size(); ++pos) {
11880 char c = names[pos];
11885 // It is basically impossible to disambiguate between
11886 // comparison and start of template args in this context
11898 pos = skipq(pos, c);
11901 if (start != pos && openings.empty()) {
11902 m_messages.emplace_back(macroName, lineInfo, resultType);
11903 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
11904 m_messages.back().message += " := ";
11909 assert(openings.empty() && "Mismatched openings");
11910 m_messages.emplace_back(macroName, lineInfo, resultType);
11911 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
11912 m_messages.back().message += " := ";
11914 Capturer::~Capturer() {
11915 if ( !uncaught_exceptions() ){
11916 assert( m_captured == m_messages.size() );
11917 for( size_t i = 0; i < m_captured; ++i )
11918 m_resultCapture.popScopedMessage( m_messages[i] );
11922 void Capturer::captureValue( size_t index, std::string const& value ) {
11923 assert( index < m_messages.size() );
11924 m_messages[index].message += value;
11925 m_resultCapture.pushScopedMessage( m_messages[index] );
11929 } // end namespace Catch
11930 // end catch_message.cpp
11931 // start catch_output_redirect.cpp
11933 // start catch_output_redirect.h
11934 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11935 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11943 class RedirectedStream {
11944 std::ostream& m_originalStream;
11945 std::ostream& m_redirectionStream;
11946 std::streambuf* m_prevBuf;
11949 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11950 ~RedirectedStream();
11953 class RedirectedStdOut {
11954 ReusableStringStream m_rss;
11955 RedirectedStream m_cout;
11957 RedirectedStdOut();
11958 auto str() const -> std::string;
11961 // StdErr has two constituent streams in C++, std::cerr and std::clog
11962 // This means that we need to redirect 2 streams into 1 to keep proper
11964 class RedirectedStdErr {
11965 ReusableStringStream m_rss;
11966 RedirectedStream m_cerr;
11967 RedirectedStream m_clog;
11969 RedirectedStdErr();
11970 auto str() const -> std::string;
11973 class RedirectedStreams {
11975 RedirectedStreams(RedirectedStreams const&) = delete;
11976 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11977 RedirectedStreams(RedirectedStreams&&) = delete;
11978 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11980 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11981 ~RedirectedStreams();
11983 std::string& m_redirectedCout;
11984 std::string& m_redirectedCerr;
11985 RedirectedStdOut m_redirectedStdOut;
11986 RedirectedStdErr m_redirectedStdErr;
11989 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11991 // Windows's implementation of std::tmpfile is terrible (it tries
11992 // to create a file inside system folder, thus requiring elevated
11993 // privileges for the binary), so we have to use tmpnam(_s) and
11994 // create the file ourselves there.
11997 TempFile(TempFile const&) = delete;
11998 TempFile& operator=(TempFile const&) = delete;
11999 TempFile(TempFile&&) = delete;
12000 TempFile& operator=(TempFile&&) = delete;
12005 std::FILE* getFile();
12006 std::string getContents();
12009 std::FILE* m_file = nullptr;
12010 #if defined(_MSC_VER)
12011 char m_buffer[L_tmpnam] = { 0 };
12015 class OutputRedirect {
12017 OutputRedirect(OutputRedirect const&) = delete;
12018 OutputRedirect& operator=(OutputRedirect const&) = delete;
12019 OutputRedirect(OutputRedirect&&) = delete;
12020 OutputRedirect& operator=(OutputRedirect&&) = delete;
12022 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12026 int m_originalStdout = -1;
12027 int m_originalStderr = -1;
12028 TempFile m_stdoutFile;
12029 TempFile m_stderrFile;
12030 std::string& m_stdoutDest;
12031 std::string& m_stderrDest;
12036 } // end namespace Catch
12038 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12039 // end catch_output_redirect.h
12044 #include <stdexcept>
12046 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12047 #if defined(_MSC_VER)
12048 #include <io.h> //_dup and _dup2
12051 #define fileno _fileno
12053 #include <unistd.h> // dup and dup2
12059 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12060 : m_originalStream( originalStream ),
12061 m_redirectionStream( redirectionStream ),
12062 m_prevBuf( m_originalStream.rdbuf() )
12064 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12067 RedirectedStream::~RedirectedStream() {
12068 m_originalStream.rdbuf( m_prevBuf );
12071 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
12072 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12074 RedirectedStdErr::RedirectedStdErr()
12075 : m_cerr( Catch::cerr(), m_rss.get() ),
12076 m_clog( Catch::clog(), m_rss.get() )
12078 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12080 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12081 : m_redirectedCout(redirectedCout),
12082 m_redirectedCerr(redirectedCerr)
12085 RedirectedStreams::~RedirectedStreams() {
12086 m_redirectedCout += m_redirectedStdOut.str();
12087 m_redirectedCerr += m_redirectedStdErr.str();
12090 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12092 #if defined(_MSC_VER)
12093 TempFile::TempFile() {
12094 if (tmpnam_s(m_buffer)) {
12095 CATCH_RUNTIME_ERROR("Could not get a temp filename");
12097 if (fopen_s(&m_file, m_buffer, "w+")) {
12099 if (strerror_s(buffer, errno)) {
12100 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12102 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
12106 TempFile::TempFile() {
12107 m_file = std::tmpfile();
12109 CATCH_RUNTIME_ERROR("Could not create a temp file.");
12115 TempFile::~TempFile() {
12116 // TBD: What to do about errors here?
12117 std::fclose(m_file);
12118 // We manually create the file on Windows only, on Linux
12119 // it will be autodeleted
12120 #if defined(_MSC_VER)
12121 std::remove(m_buffer);
12125 FILE* TempFile::getFile() {
12129 std::string TempFile::getContents() {
12130 std::stringstream sstr;
12131 char buffer[100] = {};
12132 std::rewind(m_file);
12133 while (std::fgets(buffer, sizeof(buffer), m_file)) {
12139 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12140 m_originalStdout(dup(1)),
12141 m_originalStderr(dup(2)),
12142 m_stdoutDest(stdout_dest),
12143 m_stderrDest(stderr_dest) {
12144 dup2(fileno(m_stdoutFile.getFile()), 1);
12145 dup2(fileno(m_stderrFile.getFile()), 2);
12148 OutputRedirect::~OutputRedirect() {
12149 Catch::cout() << std::flush;
12151 // Since we support overriding these streams, we flush cerr
12152 // even though std::cerr is unbuffered
12153 Catch::cerr() << std::flush;
12154 Catch::clog() << std::flush;
12157 dup2(m_originalStdout, 1);
12158 dup2(m_originalStderr, 2);
12160 m_stdoutDest += m_stdoutFile.getContents();
12161 m_stderrDest += m_stderrFile.getContents();
12164 #endif // CATCH_CONFIG_NEW_CAPTURE
12166 } // namespace Catch
12168 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12169 #if defined(_MSC_VER)
12175 // end catch_output_redirect.cpp
12176 // start catch_polyfills.cpp
12182 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12183 bool isnan(float f) {
12184 return std::isnan(f);
12186 bool isnan(double d) {
12187 return std::isnan(d);
12190 // For now we only use this for embarcadero
12191 bool isnan(float f) {
12192 return std::_isnan(f);
12194 bool isnan(double d) {
12195 return std::_isnan(d);
12199 } // end namespace Catch
12200 // end catch_polyfills.cpp
12201 // start catch_random_number_generator.cpp
12207 #if defined(_MSC_VER)
12208 #pragma warning(push)
12209 #pragma warning(disable:4146) // we negate uint32 during the rotate
12211 // Safe rotr implementation thanks to John Regehr
12212 uint32_t rotate_right(uint32_t val, uint32_t count) {
12213 const uint32_t mask = 31;
12215 return (val >> count) | (val << (-count & mask));
12218 #if defined(_MSC_VER)
12219 #pragma warning(pop)
12224 SimplePcg32::SimplePcg32(result_type seed_) {
12228 void SimplePcg32::seed(result_type seed_) {
12235 void SimplePcg32::discard(uint64_t skip) {
12236 // We could implement this to run in O(log n) steps, but this
12237 // should suffice for our use case.
12238 for (uint64_t s = 0; s < skip; ++s) {
12239 static_cast<void>((*this)());
12243 SimplePcg32::result_type SimplePcg32::operator()() {
12244 // prepare the output value
12245 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12246 const auto output = rotate_right(xorshifted, m_state >> 59u);
12249 m_state = m_state * 6364136223846793005ULL + s_inc;
12254 bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12255 return lhs.m_state == rhs.m_state;
12258 bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12259 return lhs.m_state != rhs.m_state;
12262 // end catch_random_number_generator.cpp
12263 // start catch_registry_hub.cpp
12265 // start catch_test_case_registry_impl.h
12269 #include <algorithm>
12277 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
12279 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
12280 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
12282 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
12284 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
12285 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
12287 class TestRegistry : public ITestCaseRegistry {
12289 virtual ~TestRegistry() = default;
12291 virtual void registerTest( TestCase const& testCase );
12293 std::vector<TestCase> const& getAllTests() const override;
12294 std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
12297 std::vector<TestCase> m_functions;
12298 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12299 mutable std::vector<TestCase> m_sortedFunctions;
12300 std::size_t m_unnamedCount = 0;
12301 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12304 ///////////////////////////////////////////////////////////////////////////
12306 class TestInvokerAsFunction : public ITestInvoker {
12307 void(*m_testAsFunction)();
12309 TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
12311 void invoke() const override;
12314 std::string extractClassName( StringRef const& classOrQualifiedMethodName );
12316 ///////////////////////////////////////////////////////////////////////////
12318 } // end namespace Catch
12320 // end catch_test_case_registry_impl.h
12321 // start catch_reporter_registry.h
12327 class ReporterRegistry : public IReporterRegistry {
12331 ~ReporterRegistry() override;
12333 IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
12335 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
12336 void registerListener( IReporterFactoryPtr const& factory );
12338 FactoryMap const& getFactories() const override;
12339 Listeners const& getListeners() const override;
12342 FactoryMap m_factories;
12343 Listeners m_listeners;
12347 // end catch_reporter_registry.h
12348 // start catch_tag_alias_registry.h
12350 // start catch_tag_alias.h
12357 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12360 SourceLineInfo lineInfo;
12363 } // end namespace Catch
12365 // end catch_tag_alias.h
12370 class TagAliasRegistry : public ITagAliasRegistry {
12372 ~TagAliasRegistry() override;
12373 TagAlias const* find( std::string const& alias ) const override;
12374 std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
12375 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
12378 std::map<std::string, TagAlias> m_registry;
12381 } // end namespace Catch
12383 // end catch_tag_alias_registry.h
12384 // start catch_startup_exception_registry.h
12387 #include <exception>
12391 class StartupExceptionRegistry {
12392 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12394 void add(std::exception_ptr const& exception) noexcept;
12395 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12397 std::vector<std::exception_ptr> m_exceptions;
12401 } // end namespace Catch
12403 // end catch_startup_exception_registry.h
12404 // start catch_singletons.hpp
12408 struct ISingleton {
12409 virtual ~ISingleton();
12412 void addSingleton( ISingleton* singleton );
12413 void cleanupSingletons();
12415 template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
12416 class Singleton : SingletonImplT, public ISingleton {
12418 static auto getInternal() -> Singleton* {
12419 static Singleton* s_instance = nullptr;
12420 if( !s_instance ) {
12421 s_instance = new Singleton;
12422 addSingleton( s_instance );
12428 static auto get() -> InterfaceT const& {
12429 return *getInternal();
12431 static auto getMutable() -> MutableInterfaceT& {
12432 return *getInternal();
12436 } // namespace Catch
12438 // end catch_singletons.hpp
12443 class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
12444 private NonCopyable {
12446 public: // IRegistryHub
12447 RegistryHub() = default;
12448 IReporterRegistry const& getReporterRegistry() const override {
12449 return m_reporterRegistry;
12451 ITestCaseRegistry const& getTestCaseRegistry() const override {
12452 return m_testCaseRegistry;
12454 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12455 return m_exceptionTranslatorRegistry;
12457 ITagAliasRegistry const& getTagAliasRegistry() const override {
12458 return m_tagAliasRegistry;
12460 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12461 return m_exceptionRegistry;
12464 public: // IMutableRegistryHub
12465 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
12466 m_reporterRegistry.registerReporter( name, factory );
12468 void registerListener( IReporterFactoryPtr const& factory ) override {
12469 m_reporterRegistry.registerListener( factory );
12471 void registerTest( TestCase const& testInfo ) override {
12472 m_testCaseRegistry.registerTest( testInfo );
12474 void registerTranslator( const IExceptionTranslator* translator ) override {
12475 m_exceptionTranslatorRegistry.registerTranslator( translator );
12477 void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
12478 m_tagAliasRegistry.add( alias, tag, lineInfo );
12480 void registerStartupException() noexcept override {
12481 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12482 m_exceptionRegistry.add(std::current_exception());
12484 CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12487 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12488 return m_enumValuesRegistry;
12492 TestRegistry m_testCaseRegistry;
12493 ReporterRegistry m_reporterRegistry;
12494 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12495 TagAliasRegistry m_tagAliasRegistry;
12496 StartupExceptionRegistry m_exceptionRegistry;
12497 Detail::EnumValuesRegistry m_enumValuesRegistry;
12501 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12503 IRegistryHub const& getRegistryHub() {
12504 return RegistryHubSingleton::get();
12506 IMutableRegistryHub& getMutableRegistryHub() {
12507 return RegistryHubSingleton::getMutable();
12510 cleanupSingletons();
12513 std::string translateActiveException() {
12514 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12517 } // end namespace Catch
12518 // end catch_registry_hub.cpp
12519 // start catch_reporter_registry.cpp
12523 ReporterRegistry::~ReporterRegistry() = default;
12525 IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
12526 auto it = m_factories.find( name );
12527 if( it == m_factories.end() )
12529 return it->second->create( ReporterConfig( config ) );
12532 void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
12533 m_factories.emplace(name, factory);
12535 void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12536 m_listeners.push_back( factory );
12539 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12540 return m_factories;
12542 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12543 return m_listeners;
12547 // end catch_reporter_registry.cpp
12548 // start catch_result_type.cpp
12552 bool isOk( ResultWas::OfType resultType ) {
12553 return ( resultType & ResultWas::FailureBit ) == 0;
12555 bool isJustInfo( int flags ) {
12556 return flags == ResultWas::Info;
12559 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12560 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12563 bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
12564 bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12566 } // end namespace Catch
12567 // end catch_result_type.cpp
12568 // start catch_run_context.cpp
12571 #include <algorithm>
12576 namespace Generators {
12577 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12578 GeneratorBasePtr m_generator;
12580 GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12581 : TrackerBase( nameAndLocation, ctx, parent )
12583 ~GeneratorTracker();
12585 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12586 std::shared_ptr<GeneratorTracker> tracker;
12588 ITracker& currentTracker = ctx.currentTracker();
12589 // Under specific circumstances, the generator we want
12590 // to acquire is also the current tracker. If this is
12591 // the case, we have to avoid looking through current
12592 // tracker's children, and instead return the current
12594 // A case where this check is important is e.g.
12595 // for (int i = 0; i < 5; ++i) {
12596 // int n = GENERATE(1, 2);
12599 // without it, the code above creates 5 nested generators.
12600 if (currentTracker.nameAndLocation() == nameAndLocation) {
12601 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12602 assert(thisTracker);
12603 assert(thisTracker->isGeneratorTracker());
12604 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12605 } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12606 assert( childTracker );
12607 assert( childTracker->isGeneratorTracker() );
12608 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12610 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12611 currentTracker.addChild( tracker );
12614 if( !tracker->isComplete() ) {
12621 // TrackerBase interface
12622 bool isGeneratorTracker() const override { return true; }
12623 auto hasGenerator() const -> bool override {
12624 return !!m_generator;
12626 void close() override {
12627 TrackerBase::close();
12628 // If a generator has a child (it is followed by a section)
12629 // and none of its children have started, then we must wait
12630 // until later to start consuming its values.
12631 // This catches cases where `GENERATE` is placed between two
12633 // **The check for m_children.empty cannot be removed**.
12634 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
12635 const bool should_wait_for_child = [&]() {
12636 // No children -> nobody to wait for
12637 if ( m_children.empty() ) {
12640 // If at least one child started executing, don't wait
12642 m_children.begin(),
12644 []( TestCaseTracking::ITrackerPtr tracker ) {
12645 return tracker->hasStarted();
12646 } ) != m_children.end() ) {
12650 // No children have started. We need to check if they _can_
12651 // start, and thus we should wait for them, or they cannot
12652 // start (due to filters), and we shouldn't wait for them
12653 auto* parent = m_parent;
12654 // This is safe: there is always at least one section
12655 // tracker in a test case tracking tree
12656 while ( !parent->isSectionTracker() ) {
12657 parent = &( parent->parent() );
12660 "Missing root (test case) level section" );
12662 auto const& parentSection =
12663 static_cast<SectionTracker&>( *parent );
12664 auto const& filters = parentSection.getFilters();
12665 // No filters -> no restrictions on running sections
12666 if ( filters.empty() ) {
12670 for ( auto const& child : m_children ) {
12671 if ( child->isSectionTracker() &&
12672 std::find( filters.begin(),
12674 static_cast<SectionTracker&>( *child )
12675 .trimmedName() ) !=
12683 // This check is a bit tricky, because m_generator->next()
12684 // has a side-effect, where it consumes generator's current
12685 // value, but we do not want to invoke the side-effect if
12686 // this generator is still waiting for any child to start.
12687 if ( should_wait_for_child ||
12688 ( m_runState == CompletedSuccessfully &&
12689 m_generator->next() ) ) {
12690 m_children.clear();
12691 m_runState = Executing;
12695 // IGeneratorTracker interface
12696 auto getGenerator() const -> GeneratorBasePtr const& override {
12697 return m_generator;
12699 void setGenerator( GeneratorBasePtr&& generator ) override {
12700 m_generator = std::move( generator );
12703 GeneratorTracker::~GeneratorTracker() {}
12706 RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12707 : m_runInfo(_config->name()),
12708 m_context(getCurrentMutableContext()),
12710 m_reporter(std::move(reporter)),
12711 m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12712 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12714 m_context.setRunner(this);
12715 m_context.setConfig(m_config);
12716 m_context.setResultCapture(this);
12717 m_reporter->testRunStarting(m_runInfo);
12720 RunContext::~RunContext() {
12721 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12724 void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12725 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12728 void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12729 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12732 Totals RunContext::runTest(TestCase const& testCase) {
12733 Totals prevTotals = m_totals;
12735 std::string redirectedCout;
12736 std::string redirectedCerr;
12738 auto const& testInfo = testCase.getTestCaseInfo();
12740 m_reporter->testCaseStarting(testInfo);
12742 m_activeTestCase = &testCase;
12744 ITracker& rootTracker = m_trackerContext.startRun();
12745 assert(rootTracker.isSectionTracker());
12746 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12748 m_trackerContext.startCycle();
12749 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12750 runCurrentTest(redirectedCout, redirectedCerr);
12751 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12753 Totals deltaTotals = m_totals.delta(prevTotals);
12754 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12755 deltaTotals.assertions.failed++;
12756 deltaTotals.testCases.passed--;
12757 deltaTotals.testCases.failed++;
12759 m_totals.testCases += deltaTotals.testCases;
12760 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12766 m_activeTestCase = nullptr;
12767 m_testCaseTracker = nullptr;
12769 return deltaTotals;
12772 IConfigPtr RunContext::config() const {
12776 IStreamingReporter& RunContext::reporter() const {
12777 return *m_reporter;
12780 void RunContext::assertionEnded(AssertionResult const & result) {
12781 if (result.getResultType() == ResultWas::Ok) {
12782 m_totals.assertions.passed++;
12783 m_lastAssertionPassed = true;
12784 } else if (!result.isOk()) {
12785 m_lastAssertionPassed = false;
12786 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12787 m_totals.assertions.failedButOk++;
12789 m_totals.assertions.failed++;
12792 m_lastAssertionPassed = true;
12795 // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12796 // and should be let to clear themselves out.
12797 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12799 if (result.getResultType() != ResultWas::Warning)
12800 m_messageScopes.clear();
12802 // Reset working state
12803 resetAssertionInfo();
12804 m_lastResult = result;
12806 void RunContext::resetAssertionInfo() {
12807 m_lastAssertionInfo.macroName = StringRef();
12808 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12811 bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12812 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12813 if (!sectionTracker.isOpen())
12815 m_activeSections.push_back(§ionTracker);
12817 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12819 m_reporter->sectionStarting(sectionInfo);
12821 assertions = m_totals.assertions;
12825 auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12826 using namespace Generators;
12827 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12828 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12829 m_lastAssertionInfo.lineInfo = lineInfo;
12833 bool RunContext::testForMissingAssertions(Counts& assertions) {
12834 if (assertions.total() != 0)
12836 if (!m_config->warnAboutMissingAssertions())
12838 if (m_trackerContext.currentTracker().hasChildren())
12840 m_totals.assertions.failed++;
12841 assertions.failed++;
12845 void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12846 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12847 bool missingAssertions = testForMissingAssertions(assertions);
12849 if (!m_activeSections.empty()) {
12850 m_activeSections.back()->close();
12851 m_activeSections.pop_back();
12854 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12855 m_messages.clear();
12856 m_messageScopes.clear();
12859 void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12860 if (m_unfinishedSections.empty())
12861 m_activeSections.back()->fail();
12863 m_activeSections.back()->close();
12864 m_activeSections.pop_back();
12866 m_unfinishedSections.push_back(endInfo);
12869 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12870 void RunContext::benchmarkPreparing(std::string const& name) {
12871 m_reporter->benchmarkPreparing(name);
12873 void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12874 m_reporter->benchmarkStarting( info );
12876 void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12877 m_reporter->benchmarkEnded( stats );
12879 void RunContext::benchmarkFailed(std::string const & error) {
12880 m_reporter->benchmarkFailed(error);
12882 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12884 void RunContext::pushScopedMessage(MessageInfo const & message) {
12885 m_messages.push_back(message);
12888 void RunContext::popScopedMessage(MessageInfo const & message) {
12889 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12892 void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12893 m_messageScopes.emplace_back( builder );
12896 std::string RunContext::getCurrentTestName() const {
12897 return m_activeTestCase
12898 ? m_activeTestCase->getTestCaseInfo().name
12902 const AssertionResult * RunContext::getLastResult() const {
12903 return &(*m_lastResult);
12906 void RunContext::exceptionEarlyReported() {
12907 m_shouldReportUnexpected = false;
12910 void RunContext::handleFatalErrorCondition( StringRef message ) {
12911 // First notify reporter that bad things happened
12912 m_reporter->fatalErrorEncountered(message);
12914 // Don't rebuild the result -- the stringification itself can cause more fatal errors
12915 // Instead, fake a result data.
12916 AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12917 tempResult.message = static_cast<std::string>(message);
12918 AssertionResult result(m_lastAssertionInfo, tempResult);
12920 assertionEnded(result);
12922 handleUnfinishedSections();
12924 // Recreate section for test case (as we will lose the one that was in scope)
12925 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12926 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12929 assertions.failed = 1;
12930 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12931 m_reporter->sectionEnded(testCaseSectionStats);
12933 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12935 Totals deltaTotals;
12936 deltaTotals.testCases.failed = 1;
12937 deltaTotals.assertions.failed = 1;
12938 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12943 m_totals.testCases.failed++;
12944 testGroupEnded(std::string(), m_totals, 1, 1);
12945 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12948 bool RunContext::lastAssertionPassed() {
12949 return m_lastAssertionPassed;
12952 void RunContext::assertionPassed() {
12953 m_lastAssertionPassed = true;
12954 ++m_totals.assertions.passed;
12955 resetAssertionInfo();
12956 m_messageScopes.clear();
12959 bool RunContext::aborting() const {
12960 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12963 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12964 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12965 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12966 m_reporter->sectionStarting(testCaseSection);
12967 Counts prevAssertions = m_totals.assertions;
12968 double duration = 0;
12969 m_shouldReportUnexpected = true;
12970 m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12972 seedRng(*m_config);
12976 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12977 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12978 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12981 invokeActiveTestCase();
12983 OutputRedirect r(redirectedCout, redirectedCerr);
12985 invokeActiveTestCase();
12989 invokeActiveTestCase();
12991 duration = timer.getElapsedSeconds();
12992 } CATCH_CATCH_ANON (TestFailureException&) {
12993 // This just means the test was aborted due to failure
12994 } CATCH_CATCH_ALL {
12995 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
12996 // are reported without translation at the point of origin.
12997 if( m_shouldReportUnexpected ) {
12998 AssertionReaction dummyReaction;
12999 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
13002 Counts assertions = m_totals.assertions - prevAssertions;
13003 bool missingAssertions = testForMissingAssertions(assertions);
13005 m_testCaseTracker->close();
13006 handleUnfinishedSections();
13007 m_messages.clear();
13008 m_messageScopes.clear();
13010 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13011 m_reporter->sectionEnded(testCaseSectionStats);
13014 void RunContext::invokeActiveTestCase() {
13015 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13016 m_activeTestCase->invoke();
13019 void RunContext::handleUnfinishedSections() {
13020 // If sections ended prematurely due to an exception we stored their
13021 // infos here so we can tear them down outside the unwind process.
13022 for (auto it = m_unfinishedSections.rbegin(),
13023 itEnd = m_unfinishedSections.rend();
13027 m_unfinishedSections.clear();
13030 void RunContext::handleExpr(
13031 AssertionInfo const& info,
13032 ITransientExpression const& expr,
13033 AssertionReaction& reaction
13035 m_reporter->assertionStarting( info );
13037 bool negated = isFalseTest( info.resultDisposition );
13038 bool result = expr.getResult() != negated;
13041 if (!m_includeSuccessfulResults) {
13045 reportExpr(info, ResultWas::Ok, &expr, negated);
13049 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
13050 populateReaction( reaction );
13053 void RunContext::reportExpr(
13054 AssertionInfo const &info,
13055 ResultWas::OfType resultType,
13056 ITransientExpression const *expr,
13059 m_lastAssertionInfo = info;
13060 AssertionResultData data( resultType, LazyExpression( negated ) );
13062 AssertionResult assertionResult{ info, data };
13063 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13065 assertionEnded( assertionResult );
13068 void RunContext::handleMessage(
13069 AssertionInfo const& info,
13070 ResultWas::OfType resultType,
13071 StringRef const& message,
13072 AssertionReaction& reaction
13074 m_reporter->assertionStarting( info );
13076 m_lastAssertionInfo = info;
13078 AssertionResultData data( resultType, LazyExpression( false ) );
13079 data.message = static_cast<std::string>(message);
13080 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13081 assertionEnded( assertionResult );
13082 if( !assertionResult.isOk() )
13083 populateReaction( reaction );
13085 void RunContext::handleUnexpectedExceptionNotThrown(
13086 AssertionInfo const& info,
13087 AssertionReaction& reaction
13089 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13092 void RunContext::handleUnexpectedInflightException(
13093 AssertionInfo const& info,
13094 std::string const& message,
13095 AssertionReaction& reaction
13097 m_lastAssertionInfo = info;
13099 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13100 data.message = message;
13101 AssertionResult assertionResult{ info, data };
13102 assertionEnded( assertionResult );
13103 populateReaction( reaction );
13106 void RunContext::populateReaction( AssertionReaction& reaction ) {
13107 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13108 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13111 void RunContext::handleIncomplete(
13112 AssertionInfo const& info
13114 m_lastAssertionInfo = info;
13116 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13117 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13118 AssertionResult assertionResult{ info, data };
13119 assertionEnded( assertionResult );
13121 void RunContext::handleNonExpr(
13122 AssertionInfo const &info,
13123 ResultWas::OfType resultType,
13124 AssertionReaction &reaction
13126 m_lastAssertionInfo = info;
13128 AssertionResultData data( resultType, LazyExpression( false ) );
13129 AssertionResult assertionResult{ info, data };
13130 assertionEnded( assertionResult );
13132 if( !assertionResult.isOk() )
13133 populateReaction( reaction );
13136 IResultCapture& getResultCapture() {
13137 if (auto* capture = getCurrentContext().getResultCapture())
13140 CATCH_INTERNAL_ERROR("No result capture instance");
13143 void seedRng(IConfig const& config) {
13144 if (config.rngSeed() != 0) {
13145 std::srand(config.rngSeed());
13146 rng().seed(config.rngSeed());
13150 unsigned int rngSeed() {
13151 return getCurrentContext().getConfig()->rngSeed();
13155 // end catch_run_context.cpp
13156 // start catch_section.cpp
13160 Section::Section( SectionInfo const& info )
13162 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13167 Section::~Section() {
13168 if( m_sectionIncluded ) {
13169 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13170 if( uncaught_exceptions() )
13171 getResultCapture().sectionEndedEarly( endInfo );
13173 getResultCapture().sectionEnded( endInfo );
13177 // This indicates whether the section should be executed or not
13178 Section::operator bool() const {
13179 return m_sectionIncluded;
13182 } // end namespace Catch
13183 // end catch_section.cpp
13184 // start catch_section_info.cpp
13188 SectionInfo::SectionInfo
13189 ( SourceLineInfo const& _lineInfo,
13190 std::string const& _name )
13192 lineInfo( _lineInfo )
13195 } // end namespace Catch
13196 // end catch_section_info.cpp
13197 // start catch_session.cpp
13199 // start catch_session.h
13205 class Session : NonCopyable {
13209 ~Session() override;
13211 void showHelp() const;
13212 void libIdentify();
13214 int applyCommandLine( int argc, char const * const * argv );
13215 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13216 int applyCommandLine( int argc, wchar_t const * const * argv );
13219 void useConfigData( ConfigData const& configData );
13221 template<typename CharT>
13222 int run(int argc, CharT const * const argv[]) {
13223 if (m_startupExceptions)
13225 int returnCode = applyCommandLine(argc, argv);
13226 if (returnCode == 0)
13227 returnCode = run();
13233 clara::Parser const& cli() const;
13234 void cli( clara::Parser const& newParser );
13235 ConfigData& configData();
13240 clara::Parser m_cli;
13241 ConfigData m_configData;
13242 std::shared_ptr<Config> m_config;
13243 bool m_startupExceptions = false;
13246 } // end namespace Catch
13248 // end catch_session.h
13249 // start catch_version.h
13255 // Versioning information
13257 Version( Version const& ) = delete;
13258 Version& operator=( Version const& ) = delete;
13259 Version( unsigned int _majorVersion,
13260 unsigned int _minorVersion,
13261 unsigned int _patchNumber,
13262 char const * const _branchName,
13263 unsigned int _buildNumber );
13265 unsigned int const majorVersion;
13266 unsigned int const minorVersion;
13267 unsigned int const patchNumber;
13269 // buildNumber is only used if branchName is not null
13270 char const * const branchName;
13271 unsigned int const buildNumber;
13273 friend std::ostream& operator << ( std::ostream& os, Version const& version );
13276 Version const& libraryVersion();
13279 // end catch_version.h
13283 #include <iterator>
13288 const int MaxExitCode = 255;
13290 IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
13291 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13292 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13297 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13298 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13299 return createReporter(config->getReporterName(), config);
13302 // On older platforms, returning std::unique_ptr<ListeningReporter>
13303 // when the return type is std::unique_ptr<IStreamingReporter>
13304 // doesn't compile without a std::move call. However, this causes
13305 // a warning on newer platforms. Thus, we have to work around
13306 // it a bit and downcast the pointer manually.
13307 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13308 auto& multi = static_cast<ListeningReporter&>(*ret);
13309 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13310 for (auto const& listener : listeners) {
13311 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13313 multi.addReporter(createReporter(config->getReporterName(), config));
13319 explicit TestGroup(std::shared_ptr<Config> const& config)
13321 , m_context{config, makeReporter(config)}
13323 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13324 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13325 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13327 if (m_matches.empty() && invalidArgs.empty()) {
13328 for (auto const& test : allTestCases)
13329 if (!test.isHidden())
13330 m_tests.emplace(&test);
13332 for (auto const& match : m_matches)
13333 m_tests.insert(match.tests.begin(), match.tests.end());
13338 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13340 m_context.testGroupStarting(m_config->name(), 1, 1);
13341 for (auto const& testCase : m_tests) {
13342 if (!m_context.aborting())
13343 totals += m_context.runTest(*testCase);
13345 m_context.reporter().skipTest(*testCase);
13348 for (auto const& match : m_matches) {
13349 if (match.tests.empty()) {
13350 m_context.reporter().noMatchingTestCases(match.name);
13355 if (!invalidArgs.empty()) {
13356 for (auto const& invalidArg: invalidArgs)
13357 m_context.reporter().reportInvalidArguments(invalidArg);
13360 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13365 using Tests = std::set<TestCase const*>;
13367 std::shared_ptr<Config> m_config;
13368 RunContext m_context;
13370 TestSpec::Matches m_matches;
13373 void applyFilenamesAsTags(Catch::IConfig const& config) {
13374 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13375 for (auto& testCase : tests) {
13376 auto tags = testCase.tags;
13378 std::string filename = testCase.lineInfo.file;
13379 auto lastSlash = filename.find_last_of("\\/");
13380 if (lastSlash != std::string::npos) {
13381 filename.erase(0, lastSlash);
13385 auto lastDot = filename.find_last_of('.');
13386 if (lastDot != std::string::npos) {
13387 filename.erase(lastDot);
13390 tags.push_back(std::move(filename));
13391 setTags(testCase, tags);
13395 } // anon namespace
13397 Session::Session() {
13398 static bool alreadyInstantiated = false;
13399 if( alreadyInstantiated ) {
13400 CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
13401 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13404 // There cannot be exceptions at startup in no-exception mode.
13405 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13406 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13407 if ( !exceptions.empty() ) {
13409 getCurrentMutableContext().setConfig(m_config);
13411 m_startupExceptions = true;
13412 Colour colourGuard( Colour::Red );
13413 Catch::cerr() << "Errors occurred during startup!" << '\n';
13414 // iterate over all exceptions and notify user
13415 for ( const auto& ex_ptr : exceptions ) {
13417 std::rethrow_exception(ex_ptr);
13418 } catch ( std::exception const& ex ) {
13419 Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
13425 alreadyInstantiated = true;
13426 m_cli = makeCommandLineParser( m_configData );
13428 Session::~Session() {
13432 void Session::showHelp() const {
13434 << "\nCatch v" << libraryVersion() << "\n"
13435 << m_cli << std::endl
13436 << "For more detailed usage please see the project docs\n" << std::endl;
13438 void Session::libIdentify() {
13440 << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
13441 << std::left << std::setw(16) << "category: " << "testframework\n"
13442 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
13443 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13446 int Session::applyCommandLine( int argc, char const * const * argv ) {
13447 if( m_startupExceptions )
13450 auto result = m_cli.parse( clara::Args( argc, argv ) );
13453 getCurrentMutableContext().setConfig(m_config);
13455 << Colour( Colour::Red )
13456 << "\nError(s) in input:\n"
13457 << Column( result.errorMessage() ).indent( 2 )
13459 Catch::cerr() << "Run with -? for usage\n" << std::endl;
13460 return MaxExitCode;
13463 if( m_configData.showHelp )
13465 if( m_configData.libIdentify )
13471 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13472 int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
13474 char **utf8Argv = new char *[ argc ];
13476 for ( int i = 0; i < argc; ++i ) {
13477 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
13479 utf8Argv[ i ] = new char[ bufSize ];
13481 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
13484 int returnCode = applyCommandLine( argc, utf8Argv );
13486 for ( int i = 0; i < argc; ++i )
13487 delete [] utf8Argv[ i ];
13489 delete [] utf8Argv;
13495 void Session::useConfigData( ConfigData const& configData ) {
13496 m_configData = configData;
13500 int Session::run() {
13501 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13502 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13503 static_cast<void>(std::getchar());
13505 int exitCode = runInternal();
13506 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13507 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13508 static_cast<void>(std::getchar());
13513 clara::Parser const& Session::cli() const {
13516 void Session::cli( clara::Parser const& newParser ) {
13519 ConfigData& Session::configData() {
13520 return m_configData;
13522 Config& Session::config() {
13524 m_config = std::make_shared<Config>( m_configData );
13528 int Session::runInternal() {
13529 if( m_startupExceptions )
13532 if (m_configData.showHelp || m_configData.libIdentify) {
13537 config(); // Force config to be constructed
13539 seedRng( *m_config );
13541 if( m_configData.filenamesAsTags )
13542 applyFilenamesAsTags( *m_config );
13544 // Handle list request
13545 if( Option<std::size_t> listed = list( m_config ) )
13546 return static_cast<int>( *listed );
13548 TestGroup tests { m_config };
13549 auto const totals = tests.execute();
13551 if( m_config->warnAboutNoTests() && totals.error == -1 )
13554 // Note that on unices only the lower 8 bits are usually used, clamping
13555 // the return value to 255 prevents false negative when some multiple
13556 // of 256 tests has failed
13557 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13559 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13560 catch( std::exception& ex ) {
13561 Catch::cerr() << ex.what() << std::endl;
13562 return MaxExitCode;
13567 } // end namespace Catch
13568 // end catch_session.cpp
13569 // start catch_singletons.cpp
13576 static auto getSingletons() -> std::vector<ISingleton*>*& {
13577 static std::vector<ISingleton*>* g_singletons = nullptr;
13578 if( !g_singletons )
13579 g_singletons = new std::vector<ISingleton*>();
13580 return g_singletons;
13584 ISingleton::~ISingleton() {}
13586 void addSingleton(ISingleton* singleton ) {
13587 getSingletons()->push_back( singleton );
13589 void cleanupSingletons() {
13590 auto& singletons = getSingletons();
13591 for( auto singleton : *singletons )
13594 singletons = nullptr;
13597 } // namespace Catch
13598 // end catch_singletons.cpp
13599 // start catch_startup_exception_registry.cpp
13601 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13603 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
13605 m_exceptions.push_back(exception);
13606 } CATCH_CATCH_ALL {
13607 // If we run out of memory during start-up there's really not a lot more we can do about it
13612 std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
13613 return m_exceptions;
13616 } // end namespace Catch
13618 // end catch_startup_exception_registry.cpp
13619 // start catch_stream.cpp
13622 #include <iostream>
13630 Catch::IStream::~IStream() = default;
13632 namespace Detail { namespace {
13633 template<typename WriterF, std::size_t bufferSize=256>
13634 class StreamBufImpl : public std::streambuf {
13635 char data[bufferSize];
13640 setp( data, data + sizeof(data) );
13643 ~StreamBufImpl() noexcept {
13644 StreamBufImpl::sync();
13648 int overflow( int c ) override {
13652 if( pbase() == epptr() )
13653 m_writer( std::string( 1, static_cast<char>( c ) ) );
13655 sputc( static_cast<char>( c ) );
13660 int sync() override {
13661 if( pbase() != pptr() ) {
13662 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13663 setp( pbase(), epptr() );
13669 ///////////////////////////////////////////////////////////////////////////
13671 struct OutputDebugWriter {
13673 void operator()( std::string const&str ) {
13674 writeToDebugConsole( str );
13678 ///////////////////////////////////////////////////////////////////////////
13680 class FileStream : public IStream {
13681 mutable std::ofstream m_ofs;
13683 FileStream( StringRef filename ) {
13684 m_ofs.open( filename.c_str() );
13685 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13687 ~FileStream() override = default;
13689 std::ostream& stream() const override {
13694 ///////////////////////////////////////////////////////////////////////////
13696 class CoutStream : public IStream {
13697 mutable std::ostream m_os;
13699 // Store the streambuf from cout up-front because
13700 // cout may get redirected when running tests
13701 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13702 ~CoutStream() override = default;
13705 std::ostream& stream() const override { return m_os; }
13708 ///////////////////////////////////////////////////////////////////////////
13710 class DebugOutStream : public IStream {
13711 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13712 mutable std::ostream m_os;
13715 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13716 m_os( m_streamBuf.get() )
13719 ~DebugOutStream() override = default;
13722 std::ostream& stream() const override { return m_os; }
13725 }} // namespace anon::detail
13727 ///////////////////////////////////////////////////////////////////////////
13729 auto makeStream( StringRef const &filename ) -> IStream const* {
13730 if( filename.empty() )
13731 return new Detail::CoutStream();
13732 else if( filename[0] == '%' ) {
13733 if( filename == "%debug" )
13734 return new Detail::DebugOutStream();
13736 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13739 return new Detail::FileStream( filename );
13742 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13743 struct StringStreams {
13744 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13745 std::vector<std::size_t> m_unused;
13746 std::ostringstream m_referenceStream; // Used for copy state/ flags from
13748 auto add() -> std::size_t {
13749 if( m_unused.empty() ) {
13750 m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13751 return m_streams.size()-1;
13754 auto index = m_unused.back();
13755 m_unused.pop_back();
13760 void release( std::size_t index ) {
13761 m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13762 m_unused.push_back(index);
13766 ReusableStringStream::ReusableStringStream()
13767 : m_index( Singleton<StringStreams>::getMutable().add() ),
13768 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13771 ReusableStringStream::~ReusableStringStream() {
13772 static_cast<std::ostringstream*>( m_oss )->str("");
13774 Singleton<StringStreams>::getMutable().release( m_index );
13777 auto ReusableStringStream::str() const -> std::string {
13778 return static_cast<std::ostringstream*>( m_oss )->str();
13781 ///////////////////////////////////////////////////////////////////////////
13783 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
13784 std::ostream& cout() { return std::cout; }
13785 std::ostream& cerr() { return std::cerr; }
13786 std::ostream& clog() { return std::clog; }
13789 // end catch_stream.cpp
13790 // start catch_string_manip.cpp
13792 #include <algorithm>
13801 char toLowerCh(char c) {
13802 return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13806 bool startsWith( std::string const& s, std::string const& prefix ) {
13807 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13809 bool startsWith( std::string const& s, char prefix ) {
13810 return !s.empty() && s[0] == prefix;
13812 bool endsWith( std::string const& s, std::string const& suffix ) {
13813 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13815 bool endsWith( std::string const& s, char suffix ) {
13816 return !s.empty() && s[s.size()-1] == suffix;
13818 bool contains( std::string const& s, std::string const& infix ) {
13819 return s.find( infix ) != std::string::npos;
13821 void toLowerInPlace( std::string& s ) {
13822 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13824 std::string toLower( std::string const& s ) {
13825 std::string lc = s;
13826 toLowerInPlace( lc );
13829 std::string trim( std::string const& str ) {
13830 static char const* whitespaceChars = "\n\r\t ";
13831 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13832 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13834 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13837 StringRef trim(StringRef ref) {
13838 const auto is_ws = [](char c) {
13839 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
13841 size_t real_begin = 0;
13842 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13843 size_t real_end = ref.size();
13844 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13846 return ref.substr(real_begin, real_end - real_begin);
13849 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13850 bool replaced = false;
13851 std::size_t i = str.find( replaceThis );
13852 while( i != std::string::npos ) {
13854 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13855 if( i < str.size()-withThis.size() )
13856 i = str.find( replaceThis, i+withThis.size() );
13858 i = std::string::npos;
13863 std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13864 std::vector<StringRef> subStrings;
13865 std::size_t start = 0;
13866 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13867 if( str[pos] == delimiter ) {
13868 if( pos - start > 1 )
13869 subStrings.push_back( str.substr( start, pos-start ) );
13873 if( start < str.size() )
13874 subStrings.push_back( str.substr( start, str.size()-start ) );
13878 pluralise::pluralise( std::size_t count, std::string const& label )
13879 : m_count( count ),
13883 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13884 os << pluraliser.m_count << ' ' << pluraliser.m_label;
13885 if( pluraliser.m_count != 1 )
13891 // end catch_string_manip.cpp
13892 // start catch_stringref.cpp
13894 #include <algorithm>
13900 StringRef::StringRef( char const* rawChars ) noexcept
13901 : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13904 auto StringRef::c_str() const -> char const* {
13905 CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
13908 auto StringRef::data() const noexcept -> char const* {
13912 auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13913 if (start < m_size) {
13914 return StringRef(m_start + start, (std::min)(m_size - start, size));
13916 return StringRef();
13919 auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13920 return m_size == other.m_size
13921 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13924 auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13925 return os.write(str.data(), str.size());
13928 auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13929 lhs.append(rhs.data(), rhs.size());
13933 } // namespace Catch
13934 // end catch_stringref.cpp
13935 // start catch_tag_alias.cpp
13938 TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13940 // end catch_tag_alias.cpp
13941 // start catch_tag_alias_autoregistrar.cpp
13945 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13947 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13948 } CATCH_CATCH_ALL {
13949 // Do not throw when constructing global objects, instead register the exception to be processed later
13950 getMutableRegistryHub().registerStartupException();
13955 // end catch_tag_alias_autoregistrar.cpp
13956 // start catch_tag_alias_registry.cpp
13962 TagAliasRegistry::~TagAliasRegistry() {}
13964 TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13965 auto it = m_registry.find( alias );
13966 if( it != m_registry.end() )
13967 return &(it->second);
13972 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13973 std::string expandedTestSpec = unexpandedTestSpec;
13974 for( auto const& registryKvp : m_registry ) {
13975 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13976 if( pos != std::string::npos ) {
13977 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13978 registryKvp.second.tag +
13979 expandedTestSpec.substr( pos + registryKvp.first.size() );
13982 return expandedTestSpec;
13985 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
13986 CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
13987 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
13989 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13990 "error: tag alias, '" << alias << "' already registered.\n"
13991 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
13992 << "\tRedefined at: " << lineInfo );
13995 ITagAliasRegistry::~ITagAliasRegistry() {}
13997 ITagAliasRegistry const& ITagAliasRegistry::get() {
13998 return getRegistryHub().getTagAliasRegistry();
14001 } // end namespace Catch
14002 // end catch_tag_alias_registry.cpp
14003 // start catch_test_case_info.cpp
14006 #include <exception>
14007 #include <algorithm>
14013 TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
14014 if( startsWith( tag, '.' ) ||
14016 return TestCaseInfo::IsHidden;
14017 else if( tag == "!throws" )
14018 return TestCaseInfo::Throws;
14019 else if( tag == "!shouldfail" )
14020 return TestCaseInfo::ShouldFail;
14021 else if( tag == "!mayfail" )
14022 return TestCaseInfo::MayFail;
14023 else if( tag == "!nonportable" )
14024 return TestCaseInfo::NonPortable;
14025 else if( tag == "!benchmark" )
14026 return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
14028 return TestCaseInfo::None;
14030 bool isReservedTag( std::string const& tag ) {
14031 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
14033 void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
14034 CATCH_ENFORCE( !isReservedTag(tag),
14035 "Tag name: [" << tag << "] is not allowed.\n"
14036 << "Tag names starting with non alphanumeric characters are reserved\n"
14041 TestCase makeTestCase( ITestInvoker* _testCase,
14042 std::string const& _className,
14043 NameAndTags const& nameAndTags,
14044 SourceLineInfo const& _lineInfo )
14046 bool isHidden = false;
14049 std::vector<std::string> tags;
14050 std::string desc, tag;
14051 bool inTag = false;
14052 for (char c : nameAndTags.tags) {
14061 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14062 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14064 else if( prop == TestCaseInfo::None )
14065 enforceNotReservedTag( tag, _lineInfo );
14067 // Merged hide tags like `[.approvals]` should be added as
14068 // `[.][approvals]`. The `[.]` is added at later point, so
14069 // we only strip the prefix
14070 if (startsWith(tag, '.') && tag.size() > 1) {
14073 tags.push_back( tag );
14082 // Add all "hidden" tags to make them behave identically
14083 tags.insert( tags.end(), { ".", "!hide" } );
14086 TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
14087 return TestCase( _testCase, std::move(info) );
14090 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14091 std::sort(begin(tags), end(tags));
14092 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14093 testCaseInfo.lcaseTags.clear();
14095 for( auto const& tag : tags ) {
14096 std::string lcaseTag = toLower( tag );
14097 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14098 testCaseInfo.lcaseTags.push_back( lcaseTag );
14100 testCaseInfo.tags = std::move(tags);
14103 TestCaseInfo::TestCaseInfo( std::string const& _name,
14104 std::string const& _className,
14105 std::string const& _description,
14106 std::vector<std::string> const& _tags,
14107 SourceLineInfo const& _lineInfo )
14109 className( _className ),
14110 description( _description ),
14111 lineInfo( _lineInfo ),
14114 setTags( *this, _tags );
14117 bool TestCaseInfo::isHidden() const {
14118 return ( properties & IsHidden ) != 0;
14120 bool TestCaseInfo::throws() const {
14121 return ( properties & Throws ) != 0;
14123 bool TestCaseInfo::okToFail() const {
14124 return ( properties & (ShouldFail | MayFail ) ) != 0;
14126 bool TestCaseInfo::expectedToFail() const {
14127 return ( properties & (ShouldFail ) ) != 0;
14130 std::string TestCaseInfo::tagsAsString() const {
14132 // '[' and ']' per tag
14133 std::size_t full_size = 2 * tags.size();
14134 for (const auto& tag : tags) {
14135 full_size += tag.size();
14137 ret.reserve(full_size);
14138 for (const auto& tag : tags) {
14139 ret.push_back('[');
14141 ret.push_back(']');
14147 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
14149 TestCase TestCase::withName( std::string const& _newName ) const {
14150 TestCase other( *this );
14151 other.name = _newName;
14155 void TestCase::invoke() const {
14159 bool TestCase::operator == ( TestCase const& other ) const {
14160 return test.get() == other.test.get() &&
14161 name == other.name &&
14162 className == other.className;
14165 bool TestCase::operator < ( TestCase const& other ) const {
14166 return name < other.name;
14169 TestCaseInfo const& TestCase::getTestCaseInfo() const
14174 } // end namespace Catch
14175 // end catch_test_case_info.cpp
14176 // start catch_test_case_registry_impl.cpp
14178 #include <algorithm>
14184 struct TestHasher {
14185 using hash_t = uint64_t;
14187 explicit TestHasher( hash_t hashSuffix ):
14188 m_hashSuffix{ hashSuffix } {}
14190 uint32_t operator()( TestCase const& t ) const {
14191 // FNV-1a hash with multiplication fold.
14192 const hash_t prime = 1099511628211u;
14193 hash_t hash = 14695981039346656037u;
14194 for ( const char c : t.name ) {
14198 hash ^= m_hashSuffix;
14200 const uint32_t low{ static_cast<uint32_t>( hash ) };
14201 const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
14206 hash_t m_hashSuffix;
14208 } // end unnamed namespace
14210 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
14211 switch( config.runOrder() ) {
14212 case RunTests::InDeclarationOrder:
14213 // already in declaration order
14216 case RunTests::InLexicographicalOrder: {
14217 std::vector<TestCase> sorted = unsortedTestCases;
14218 std::sort( sorted.begin(), sorted.end() );
14222 case RunTests::InRandomOrder: {
14224 TestHasher h{ config.rngSeed() };
14226 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14227 std::vector<hashedTest> indexed_tests;
14228 indexed_tests.reserve( unsortedTestCases.size() );
14230 for (auto const& testCase : unsortedTestCases) {
14231 indexed_tests.emplace_back(h(testCase), &testCase);
14234 std::sort(indexed_tests.begin(), indexed_tests.end(),
14235 [](hashedTest const& lhs, hashedTest const& rhs) {
14236 if (lhs.first == rhs.first) {
14237 return lhs.second->name < rhs.second->name;
14239 return lhs.first < rhs.first;
14242 std::vector<TestCase> sorted;
14243 sorted.reserve( indexed_tests.size() );
14245 for (auto const& hashed : indexed_tests) {
14246 sorted.emplace_back(*hashed.second);
14252 return unsortedTestCases;
14255 bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
14256 return !testCase.throws() || config.allowThrows();
14259 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
14260 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14263 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
14264 std::set<TestCase> seenFunctions;
14265 for( auto const& function : functions ) {
14266 auto prev = seenFunctions.insert( function );
14267 CATCH_ENFORCE( prev.second,
14268 "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14269 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
14270 << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
14274 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
14275 std::vector<TestCase> filtered;
14276 filtered.reserve( testCases.size() );
14277 for (auto const& testCase : testCases) {
14278 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14279 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14280 filtered.push_back(testCase);
14285 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
14286 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14289 void TestRegistry::registerTest( TestCase const& testCase ) {
14290 std::string name = testCase.getTestCaseInfo().name;
14291 if( name.empty() ) {
14292 ReusableStringStream rss;
14293 rss << "Anonymous test case " << ++m_unnamedCount;
14294 return registerTest( testCase.withName( rss.str() ) );
14296 m_functions.push_back( testCase );
14299 std::vector<TestCase> const& TestRegistry::getAllTests() const {
14300 return m_functions;
14302 std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
14303 if( m_sortedFunctions.empty() )
14304 enforceNoDuplicateTestCases( m_functions );
14306 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14307 m_sortedFunctions = sortTests( config, m_functions );
14308 m_currentSortOrder = config.runOrder();
14310 return m_sortedFunctions;
14313 ///////////////////////////////////////////////////////////////////////////
14314 TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14316 void TestInvokerAsFunction::invoke() const {
14317 m_testAsFunction();
14320 std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
14321 std::string className(classOrQualifiedMethodName);
14322 if( startsWith( className, '&' ) )
14324 std::size_t lastColons = className.rfind( "::" );
14325 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
14326 if( penultimateColons == std::string::npos )
14327 penultimateColons = 1;
14328 className = className.substr( penultimateColons, lastColons-penultimateColons );
14333 } // end namespace Catch
14334 // end catch_test_case_registry_impl.cpp
14335 // start catch_test_case_tracker.cpp
14337 #include <algorithm>
14339 #include <stdexcept>
14343 #if defined(__clang__)
14344 # pragma clang diagnostic push
14345 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14349 namespace TestCaseTracking {
14351 NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
14353 location( _location )
14356 ITracker::~ITracker() = default;
14358 ITracker& TrackerContext::startRun() {
14359 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
14360 m_currentTracker = nullptr;
14361 m_runState = Executing;
14362 return *m_rootTracker;
14365 void TrackerContext::endRun() {
14366 m_rootTracker.reset();
14367 m_currentTracker = nullptr;
14368 m_runState = NotStarted;
14371 void TrackerContext::startCycle() {
14372 m_currentTracker = m_rootTracker.get();
14373 m_runState = Executing;
14375 void TrackerContext::completeCycle() {
14376 m_runState = CompletedCycle;
14379 bool TrackerContext::completedCycle() const {
14380 return m_runState == CompletedCycle;
14382 ITracker& TrackerContext::currentTracker() {
14383 return *m_currentTracker;
14385 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14386 m_currentTracker = tracker;
14389 TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14390 ITracker(nameAndLocation),
14395 bool TrackerBase::isComplete() const {
14396 return m_runState == CompletedSuccessfully || m_runState == Failed;
14398 bool TrackerBase::isSuccessfullyCompleted() const {
14399 return m_runState == CompletedSuccessfully;
14401 bool TrackerBase::isOpen() const {
14402 return m_runState != NotStarted && !isComplete();
14404 bool TrackerBase::hasChildren() const {
14405 return !m_children.empty();
14408 void TrackerBase::addChild( ITrackerPtr const& child ) {
14409 m_children.push_back( child );
14412 ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
14413 auto it = std::find_if( m_children.begin(), m_children.end(),
14414 [&nameAndLocation]( ITrackerPtr const& tracker ){
14416 tracker->nameAndLocation().location == nameAndLocation.location &&
14417 tracker->nameAndLocation().name == nameAndLocation.name;
14419 return( it != m_children.end() )
14423 ITracker& TrackerBase::parent() {
14424 assert( m_parent ); // Should always be non-null except for root
14428 void TrackerBase::openChild() {
14429 if( m_runState != ExecutingChildren ) {
14430 m_runState = ExecutingChildren;
14432 m_parent->openChild();
14436 bool TrackerBase::isSectionTracker() const { return false; }
14437 bool TrackerBase::isGeneratorTracker() const { return false; }
14439 void TrackerBase::open() {
14440 m_runState = Executing;
14443 m_parent->openChild();
14446 void TrackerBase::close() {
14448 // Close any still open children (e.g. generators)
14449 while( &m_ctx.currentTracker() != this )
14450 m_ctx.currentTracker().close();
14452 switch( m_runState ) {
14453 case NeedsAnotherRun:
14457 m_runState = CompletedSuccessfully;
14459 case ExecutingChildren:
14460 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
14461 m_runState = CompletedSuccessfully;
14465 case CompletedSuccessfully:
14467 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
14470 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
14473 m_ctx.completeCycle();
14475 void TrackerBase::fail() {
14476 m_runState = Failed;
14478 m_parent->markAsNeedingAnotherRun();
14480 m_ctx.completeCycle();
14482 void TrackerBase::markAsNeedingAnotherRun() {
14483 m_runState = NeedsAnotherRun;
14486 void TrackerBase::moveToParent() {
14487 assert( m_parent );
14488 m_ctx.setCurrentTracker( m_parent );
14490 void TrackerBase::moveToThis() {
14491 m_ctx.setCurrentTracker( this );
14494 SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14495 : TrackerBase( nameAndLocation, ctx, parent ),
14496 m_trimmed_name(trim(nameAndLocation.name))
14499 while( !parent->isSectionTracker() )
14500 parent = &parent->parent();
14502 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
14503 addNextFilters( parentSection.m_filters );
14507 bool SectionTracker::isComplete() const {
14508 bool complete = true;
14510 if (m_filters.empty()
14511 || m_filters[0] == ""
14512 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14513 complete = TrackerBase::isComplete();
14518 bool SectionTracker::isSectionTracker() const { return true; }
14520 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
14521 std::shared_ptr<SectionTracker> section;
14523 ITracker& currentTracker = ctx.currentTracker();
14524 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14525 assert( childTracker );
14526 assert( childTracker->isSectionTracker() );
14527 section = std::static_pointer_cast<SectionTracker>( childTracker );
14530 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14531 currentTracker.addChild( section );
14533 if( !ctx.completedCycle() )
14534 section->tryOpen();
14538 void SectionTracker::tryOpen() {
14539 if( !isComplete() )
14543 void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
14544 if( !filters.empty() ) {
14545 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14546 m_filters.emplace_back(""); // Root - should never be consulted
14547 m_filters.emplace_back(""); // Test Case - not a section filter
14548 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14551 void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
14552 if( filters.size() > 1 )
14553 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14556 std::vector<std::string> const& SectionTracker::getFilters() const {
14560 std::string const& SectionTracker::trimmedName() const {
14561 return m_trimmed_name;
14564 } // namespace TestCaseTracking
14566 using TestCaseTracking::ITracker;
14567 using TestCaseTracking::TrackerContext;
14568 using TestCaseTracking::SectionTracker;
14570 } // namespace Catch
14572 #if defined(__clang__)
14573 # pragma clang diagnostic pop
14575 // end catch_test_case_tracker.cpp
14576 // start catch_test_registry.cpp
14580 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14581 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14584 NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14586 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
14588 getMutableRegistryHub()
14592 extractClassName( classOrMethod ),
14595 } CATCH_CATCH_ALL {
14596 // Do not throw when constructing global objects, instead register the exception to be processed later
14597 getMutableRegistryHub().registerStartupException();
14601 AutoReg::~AutoReg() = default;
14603 // end catch_test_registry.cpp
14604 // start catch_test_spec.cpp
14606 #include <algorithm>
14613 TestSpec::Pattern::Pattern( std::string const& name )
14617 TestSpec::Pattern::~Pattern() = default;
14619 std::string const& TestSpec::Pattern::name() const {
14623 TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
14624 : Pattern( filterString )
14625 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14628 bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14629 return m_wildcardPattern.matches( testCase.name );
14632 TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14633 : Pattern( filterString )
14634 , m_tag( toLower( tag ) )
14637 bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14638 return std::find(begin(testCase.lcaseTags),
14639 end(testCase.lcaseTags),
14640 m_tag) != end(testCase.lcaseTags);
14643 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14644 : Pattern( underlyingPattern->name() )
14645 , m_underlyingPattern( underlyingPattern )
14648 bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14649 return !m_underlyingPattern->matches( testCase );
14652 bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14653 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14656 std::string TestSpec::Filter::name() const {
14658 for( auto const& p : m_patterns )
14663 bool TestSpec::hasFilters() const {
14664 return !m_filters.empty();
14667 bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14668 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14671 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14673 Matches matches( m_filters.size() );
14674 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14675 std::vector<TestCase const*> currentMatches;
14676 for( auto const& test : testCases )
14677 if( isThrowSafe( test, config ) && filter.matches( test ) )
14678 currentMatches.emplace_back( &test );
14679 return FilterMatch{ filter.name(), currentMatches };
14684 const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
14685 return (m_invalidArgs);
14689 // end catch_test_spec.cpp
14690 // start catch_test_spec_parser.cpp
14694 TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14696 TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14698 m_exclusion = false;
14699 m_arg = m_tagAliases->expandAliases( arg );
14700 m_escapeChars.clear();
14701 m_substring.reserve(m_arg.size());
14702 m_patternName.reserve(m_arg.size());
14703 m_realPatternPos = 0;
14705 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14706 //if visitChar fails
14707 if( !visitChar( m_arg[m_pos] ) ){
14708 m_testSpec.m_invalidArgs.push_back(arg);
14714 TestSpec TestSpecParser::testSpec() {
14718 bool TestSpecParser::visitChar( char c ) {
14719 if( (m_mode != EscapedName) && (c == '\\') ) {
14721 addCharToPattern(c);
14723 }else if((m_mode != EscapedName) && (c == ',') ) {
14729 if( processNoneChar( c ) )
14733 processNameChar( c );
14737 addCharToPattern(c);
14742 if( processOtherChar( c ) )
14748 if( !isControlChar( c ) ) {
14749 m_patternName += c;
14750 m_realPatternPos++;
14754 // Two of the processing methods return true to signal the caller to return
14755 // without adding the given character to the current pattern strings
14756 bool TestSpecParser::processNoneChar( char c ) {
14761 m_exclusion = true;
14764 startNewMode( Tag );
14767 startNewMode( QuotedName );
14770 startNewMode( Name );
14774 void TestSpecParser::processNameChar( char c ) {
14776 if( m_substring == "exclude:" )
14777 m_exclusion = true;
14780 startNewMode( Tag );
14783 bool TestSpecParser::processOtherChar( char c ) {
14784 if( !isControlChar( c ) )
14790 void TestSpecParser::startNewMode( Mode mode ) {
14793 void TestSpecParser::endMode() {
14797 return addNamePattern();
14799 return addTagPattern();
14801 revertBackToLastMode();
14805 return startNewMode( None );
14808 void TestSpecParser::escape() {
14810 m_mode = EscapedName;
14811 m_escapeChars.push_back(m_realPatternPos);
14813 bool TestSpecParser::isControlChar( char c ) const {
14826 return c == '[' || c == ']';
14830 void TestSpecParser::addFilter() {
14831 if( !m_currentFilter.m_patterns.empty() ) {
14832 m_testSpec.m_filters.push_back( m_currentFilter );
14833 m_currentFilter = TestSpec::Filter();
14837 void TestSpecParser::saveLastMode() {
14841 void TestSpecParser::revertBackToLastMode() {
14845 bool TestSpecParser::separate() {
14846 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14847 //invalid argument, signal failure to previous scope.
14849 m_pos = m_arg.size();
14850 m_substring.clear();
14851 m_patternName.clear();
14852 m_realPatternPos = 0;
14857 return true; //success
14860 std::string TestSpecParser::preprocessPattern() {
14861 std::string token = m_patternName;
14862 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14863 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14864 m_escapeChars.clear();
14865 if (startsWith(token, "exclude:")) {
14866 m_exclusion = true;
14867 token = token.substr(8);
14870 m_patternName.clear();
14871 m_realPatternPos = 0;
14876 void TestSpecParser::addNamePattern() {
14877 auto token = preprocessPattern();
14879 if (!token.empty()) {
14880 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14882 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14883 m_currentFilter.m_patterns.push_back(pattern);
14885 m_substring.clear();
14886 m_exclusion = false;
14890 void TestSpecParser::addTagPattern() {
14891 auto token = preprocessPattern();
14893 if (!token.empty()) {
14894 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
14895 // we have to create a separate hide tag and shorten the real one
14896 if (token.size() > 1 && token[0] == '.') {
14897 token.erase(token.begin());
14898 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
14900 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14902 m_currentFilter.m_patterns.push_back(pattern);
14905 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14908 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14910 m_currentFilter.m_patterns.push_back(pattern);
14912 m_substring.clear();
14913 m_exclusion = false;
14917 TestSpec parseTestSpec( std::string const& arg ) {
14918 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14921 } // namespace Catch
14922 // end catch_test_spec_parser.cpp
14923 // start catch_timer.cpp
14927 static const uint64_t nanosecondsInSecond = 1000000000;
14931 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14932 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14936 auto estimateClockResolution() -> uint64_t {
14938 static const uint64_t iterations = 1000000;
14940 auto startTime = getCurrentNanosecondsSinceEpoch();
14942 for( std::size_t i = 0; i < iterations; ++i ) {
14945 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14947 ticks = getCurrentNanosecondsSinceEpoch();
14948 } while( ticks == baseTicks );
14950 auto delta = ticks - baseTicks;
14953 // If we have been calibrating for over 3 seconds -- the clock
14954 // is terrible and we should move on.
14955 // TBD: How to signal that the measured resolution is probably wrong?
14956 if (ticks > startTime + 3 * nanosecondsInSecond) {
14957 return sum / ( i + 1u );
14961 // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14962 // - and potentially do more iterations if there's a high variance.
14963 return sum/iterations;
14966 auto getEstimatedClockResolution() -> uint64_t {
14967 static auto s_resolution = estimateClockResolution();
14968 return s_resolution;
14971 void Timer::start() {
14972 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14974 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14975 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14977 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14978 return getElapsedNanoseconds()/1000;
14980 auto Timer::getElapsedMilliseconds() const -> unsigned int {
14981 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14983 auto Timer::getElapsedSeconds() const -> double {
14984 return getElapsedMicroseconds()/1000000.0;
14987 } // namespace Catch
14988 // end catch_timer.cpp
14989 // start catch_tostring.cpp
14991 #if defined(__clang__)
14992 # pragma clang diagnostic push
14993 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14994 # pragma clang diagnostic ignored "-Wglobal-constructors"
14997 // Enable specific decls locally
14998 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14999 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15009 const std::string unprintableString = "{?}";
15012 const int hexThreshold = 255;
15014 struct Endianness {
15015 enum Arch { Big, Little };
15017 static Arch which() {
15019 // If the lowest byte we read is non-zero, we can assume
15020 // that little endian format is used.
15021 auto value = *reinterpret_cast<char*>(&one);
15022 return value ? Little : Big;
15027 std::string rawMemoryToString( const void *object, std::size_t size ) {
15028 // Reverse order for little endian architectures
15029 int i = 0, end = static_cast<int>( size ), inc = 1;
15030 if( Endianness::which() == Endianness::Little ) {
15035 unsigned char const *bytes = static_cast<unsigned char const *>(object);
15036 ReusableStringStream rss;
15037 rss << "0x" << std::setfill('0') << std::hex;
15038 for( ; i != end; i += inc )
15039 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15044 template<typename T>
15045 std::string fpToString( T value, int precision ) {
15046 if (Catch::isnan(value)) {
15050 ReusableStringStream rss;
15051 rss << std::setprecision( precision )
15054 std::string d = rss.str();
15055 std::size_t i = d.find_last_not_of( '0' );
15056 if( i != std::string::npos && i != d.size()-1 ) {
15059 d = d.substr( 0, i+1 );
15064 //// ======================================================= ////
15066 // Out-of-line defs for full specialization of StringMaker
15068 //// ======================================================= ////
15070 std::string StringMaker<std::string>::convert(const std::string& str) {
15071 if (!getCurrentContext().getConfig()->showInvisibles()) {
15072 return '"' + str + '"';
15075 std::string s("\"");
15076 for (char c : str) {
15093 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15094 std::string StringMaker<std::string_view>::convert(std::string_view str) {
15095 return ::Catch::Detail::stringify(std::string{ str });
15099 std::string StringMaker<char const*>::convert(char const* str) {
15101 return ::Catch::Detail::stringify(std::string{ str });
15103 return{ "{null string}" };
15106 std::string StringMaker<char*>::convert(char* str) {
15108 return ::Catch::Detail::stringify(std::string{ str });
15110 return{ "{null string}" };
15114 #ifdef CATCH_CONFIG_WCHAR
15115 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15117 s.reserve(wstr.size());
15118 for (auto c : wstr) {
15119 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15121 return ::Catch::Detail::stringify(s);
15124 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15125 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15126 return StringMaker<std::wstring>::convert(std::wstring(str));
15130 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
15132 return ::Catch::Detail::stringify(std::wstring{ str });
15134 return{ "{null string}" };
15137 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
15139 return ::Catch::Detail::stringify(std::wstring{ str });
15141 return{ "{null string}" };
15146 #if defined(CATCH_CONFIG_CPP17_BYTE)
15148 std::string StringMaker<std::byte>::convert(std::byte value) {
15149 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15151 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15153 std::string StringMaker<int>::convert(int value) {
15154 return ::Catch::Detail::stringify(static_cast<long long>(value));
15156 std::string StringMaker<long>::convert(long value) {
15157 return ::Catch::Detail::stringify(static_cast<long long>(value));
15159 std::string StringMaker<long long>::convert(long long value) {
15160 ReusableStringStream rss;
15162 if (value > Detail::hexThreshold) {
15163 rss << " (0x" << std::hex << value << ')';
15168 std::string StringMaker<unsigned int>::convert(unsigned int value) {
15169 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15171 std::string StringMaker<unsigned long>::convert(unsigned long value) {
15172 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15174 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15175 ReusableStringStream rss;
15177 if (value > Detail::hexThreshold) {
15178 rss << " (0x" << std::hex << value << ')';
15183 std::string StringMaker<bool>::convert(bool b) {
15184 return b ? "true" : "false";
15187 std::string StringMaker<signed char>::convert(signed char value) {
15188 if (value == '\r') {
15190 } else if (value == '\f') {
15192 } else if (value == '\n') {
15194 } else if (value == '\t') {
15196 } else if ('\0' <= value && value < ' ') {
15197 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15199 char chstr[] = "' '";
15204 std::string StringMaker<char>::convert(char c) {
15205 return ::Catch::Detail::stringify(static_cast<signed char>(c));
15207 std::string StringMaker<unsigned char>::convert(unsigned char c) {
15208 return ::Catch::Detail::stringify(static_cast<char>(c));
15211 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15215 int StringMaker<float>::precision = 5;
15217 std::string StringMaker<float>::convert(float value) {
15218 return fpToString(value, precision) + 'f';
15221 int StringMaker<double>::precision = 10;
15223 std::string StringMaker<double>::convert(double value) {
15224 return fpToString(value, precision);
15227 std::string ratio_string<std::atto>::symbol() { return "a"; }
15228 std::string ratio_string<std::femto>::symbol() { return "f"; }
15229 std::string ratio_string<std::pico>::symbol() { return "p"; }
15230 std::string ratio_string<std::nano>::symbol() { return "n"; }
15231 std::string ratio_string<std::micro>::symbol() { return "u"; }
15232 std::string ratio_string<std::milli>::symbol() { return "m"; }
15234 } // end namespace Catch
15236 #if defined(__clang__)
15237 # pragma clang diagnostic pop
15240 // end catch_tostring.cpp
15241 // start catch_totals.cpp
15245 Counts Counts::operator - ( Counts const& other ) const {
15247 diff.passed = passed - other.passed;
15248 diff.failed = failed - other.failed;
15249 diff.failedButOk = failedButOk - other.failedButOk;
15253 Counts& Counts::operator += ( Counts const& other ) {
15254 passed += other.passed;
15255 failed += other.failed;
15256 failedButOk += other.failedButOk;
15260 std::size_t Counts::total() const {
15261 return passed + failed + failedButOk;
15263 bool Counts::allPassed() const {
15264 return failed == 0 && failedButOk == 0;
15266 bool Counts::allOk() const {
15267 return failed == 0;
15270 Totals Totals::operator - ( Totals const& other ) const {
15272 diff.assertions = assertions - other.assertions;
15273 diff.testCases = testCases - other.testCases;
15277 Totals& Totals::operator += ( Totals const& other ) {
15278 assertions += other.assertions;
15279 testCases += other.testCases;
15283 Totals Totals::delta( Totals const& prevTotals ) const {
15284 Totals diff = *this - prevTotals;
15285 if( diff.assertions.failed > 0 )
15286 ++diff.testCases.failed;
15287 else if( diff.assertions.failedButOk > 0 )
15288 ++diff.testCases.failedButOk;
15290 ++diff.testCases.passed;
15295 // end catch_totals.cpp
15296 // start catch_uncaught_exceptions.cpp
15298 // start catch_config_uncaught_exceptions.hpp
15300 // Copyright Catch2 Authors
15301 // Distributed under the Boost Software License, Version 1.0.
15302 // (See accompanying file LICENSE_1_0.txt or copy at
15303 // https://www.boost.org/LICENSE_1_0.txt)
15305 // SPDX-License-Identifier: BSL-1.0
15307 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15308 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15310 #if defined(_MSC_VER)
15311 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15312 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15316 #include <exception>
15318 #if defined(__cpp_lib_uncaught_exceptions) \
15319 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15321 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15322 #endif // __cpp_lib_uncaught_exceptions
15324 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15325 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15326 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15328 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15331 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15332 // end catch_config_uncaught_exceptions.hpp
15333 #include <exception>
15336 bool uncaught_exceptions() {
15337 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15339 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15340 return std::uncaught_exceptions() > 0;
15342 return std::uncaught_exception();
15345 } // end namespace Catch
15346 // end catch_uncaught_exceptions.cpp
15347 // start catch_version.cpp
15354 ( unsigned int _majorVersion,
15355 unsigned int _minorVersion,
15356 unsigned int _patchNumber,
15357 char const * const _branchName,
15358 unsigned int _buildNumber )
15359 : majorVersion( _majorVersion ),
15360 minorVersion( _minorVersion ),
15361 patchNumber( _patchNumber ),
15362 branchName( _branchName ),
15363 buildNumber( _buildNumber )
15366 std::ostream& operator << ( std::ostream& os, Version const& version ) {
15367 os << version.majorVersion << '.'
15368 << version.minorVersion << '.'
15369 << version.patchNumber;
15370 // branchName is never null -> 0th char is \0 if it is empty
15371 if (version.branchName[0]) {
15372 os << '-' << version.branchName
15373 << '.' << version.buildNumber;
15378 Version const& libraryVersion() {
15379 static Version version( 2, 13, 6, "", 0 );
15384 // end catch_version.cpp
15385 // start catch_wildcard_pattern.cpp
15389 WildcardPattern::WildcardPattern( std::string const& pattern,
15390 CaseSensitive::Choice caseSensitivity )
15391 : m_caseSensitivity( caseSensitivity ),
15392 m_pattern( normaliseString( pattern ) )
15394 if( startsWith( m_pattern, '*' ) ) {
15395 m_pattern = m_pattern.substr( 1 );
15396 m_wildcard = WildcardAtStart;
15398 if( endsWith( m_pattern, '*' ) ) {
15399 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15400 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
15404 bool WildcardPattern::matches( std::string const& str ) const {
15405 switch( m_wildcard ) {
15407 return m_pattern == normaliseString( str );
15408 case WildcardAtStart:
15409 return endsWith( normaliseString( str ), m_pattern );
15410 case WildcardAtEnd:
15411 return startsWith( normaliseString( str ), m_pattern );
15412 case WildcardAtBothEnds:
15413 return contains( normaliseString( str ), m_pattern );
15415 CATCH_INTERNAL_ERROR( "Unknown enum" );
15419 std::string WildcardPattern::normaliseString( std::string const& str ) const {
15420 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15423 // end catch_wildcard_pattern.cpp
15424 // start catch_xmlwriter.cpp
15427 #include <type_traits>
15433 size_t trailingBytes(unsigned char c) {
15434 if ((c & 0xE0) == 0xC0) {
15437 if ((c & 0xF0) == 0xE0) {
15440 if ((c & 0xF8) == 0xF0) {
15443 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15446 uint32_t headerValue(unsigned char c) {
15447 if ((c & 0xE0) == 0xC0) {
15450 if ((c & 0xF0) == 0xE0) {
15453 if ((c & 0xF8) == 0xF0) {
15456 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15459 void hexEscapeChar(std::ostream& os, unsigned char c) {
15460 std::ios_base::fmtflags f(os.flags());
15462 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15463 << static_cast<int>(c);
15467 bool shouldNewline(XmlFormatting fmt) {
15468 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
15471 bool shouldIndent(XmlFormatting fmt) {
15472 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
15475 } // anonymous namespace
15477 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15478 return static_cast<XmlFormatting>(
15479 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15480 static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15484 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15485 return static_cast<XmlFormatting>(
15486 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15487 static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15491 XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
15493 m_forWhat( forWhat )
15496 void XmlEncode::encodeTo( std::ostream& os ) const {
15497 // Apostrophe escaping not necessary if we always use " to write attributes
15498 // (see: http://www.w3.org/TR/xml/#syntax)
15500 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15501 unsigned char c = m_str[idx];
15503 case '<': os << "<"; break;
15504 case '&': os << "&"; break;
15507 // See: http://www.w3.org/TR/xml/#syntax
15508 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15515 if (m_forWhat == ForAttributes)
15522 // Check for control characters and invalid utf-8
15524 // Escape control characters in standard ascii
15525 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15526 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15527 hexEscapeChar(os, c);
15531 // Plain ASCII: Write it to stream
15538 // Check if the encoding is valid and if it is not, hex escape bytes.
15539 // Important: We do not check the exact decoded values for validity, only the encoding format
15540 // First check that this bytes is a valid lead byte:
15541 // This means that it is not encoded as 1111 1XXX
15545 hexEscapeChar(os, c);
15549 auto encBytes = trailingBytes(c);
15550 // Are there enough bytes left to avoid accessing out-of-bounds memory?
15551 if (idx + encBytes - 1 >= m_str.size()) {
15552 hexEscapeChar(os, c);
15555 // The header is valid, check data
15556 // The next encBytes bytes must together be a valid utf-8
15557 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
15559 uint32_t value = headerValue(c);
15560 for (std::size_t n = 1; n < encBytes; ++n) {
15561 unsigned char nc = m_str[idx + n];
15562 valid &= ((nc & 0xC0) == 0x80);
15563 value = (value << 6) | (nc & 0x3F);
15567 // Wrong bit pattern of following bytes
15569 // Overlong encodings
15571 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15572 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15573 // Encoded value out of range
15574 (value >= 0x110000)
15576 hexEscapeChar(os, c);
15580 // If we got here, this is in fact a valid(ish) utf-8 sequence
15581 for (std::size_t n = 0; n < encBytes; ++n) {
15582 os << m_str[idx + n];
15584 idx += encBytes - 1;
15590 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
15591 xmlEncode.encodeTo( os );
15595 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15596 : m_writer( writer ),
15600 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15601 : m_writer( other.m_writer ),
15604 other.m_writer = nullptr;
15605 other.m_fmt = XmlFormatting::None;
15607 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15609 m_writer->endElement();
15611 m_writer = other.m_writer;
15612 other.m_writer = nullptr;
15613 m_fmt = other.m_fmt;
15614 other.m_fmt = XmlFormatting::None;
15618 XmlWriter::ScopedElement::~ScopedElement() {
15620 m_writer->endElement(m_fmt);
15624 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
15625 m_writer->writeText( text, fmt );
15629 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15631 writeDeclaration();
15634 XmlWriter::~XmlWriter() {
15635 while (!m_tags.empty()) {
15638 newlineIfNecessary();
15641 XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
15643 newlineIfNecessary();
15644 if (shouldIndent(fmt)) {
15648 m_os << '<' << name;
15649 m_tags.push_back( name );
15650 m_tagIsOpen = true;
15651 applyFormatting(fmt);
15655 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
15656 ScopedElement scoped( this, fmt );
15657 startElement( name, fmt );
15661 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15662 m_indent = m_indent.substr(0, m_indent.size() - 2);
15664 if( m_tagIsOpen ) {
15666 m_tagIsOpen = false;
15668 newlineIfNecessary();
15669 if (shouldIndent(fmt)) {
15672 m_os << "</" << m_tags.back() << ">";
15674 m_os << std::flush;
15675 applyFormatting(fmt);
15680 XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
15681 if( !name.empty() && !attribute.empty() )
15682 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
15686 XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
15687 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
15691 XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
15692 if( !text.empty() ){
15693 bool tagWasOpen = m_tagIsOpen;
15695 if (tagWasOpen && shouldIndent(fmt)) {
15698 m_os << XmlEncode( text );
15699 applyFormatting(fmt);
15704 XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
15706 if (shouldIndent(fmt)) {
15709 m_os << "<!--" << text << "-->";
15710 applyFormatting(fmt);
15714 void XmlWriter::writeStylesheetRef( std::string const& url ) {
15715 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
15718 XmlWriter& XmlWriter::writeBlankLine() {
15724 void XmlWriter::ensureTagClosed() {
15725 if( m_tagIsOpen ) {
15726 m_os << '>' << std::flush;
15727 newlineIfNecessary();
15728 m_tagIsOpen = false;
15732 void XmlWriter::applyFormatting(XmlFormatting fmt) {
15733 m_needsNewline = shouldNewline(fmt);
15736 void XmlWriter::writeDeclaration() {
15737 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15740 void XmlWriter::newlineIfNecessary() {
15741 if( m_needsNewline ) {
15743 m_needsNewline = false;
15747 // end catch_xmlwriter.cpp
15748 // start catch_reporter_bases.cpp
15757 void prepareExpandedExpression(AssertionResult& result) {
15758 result.getExpandedExpression();
15761 // Because formatting using c++ streams is stateful, drop down to C is required
15762 // Alternatively we could use stringstream, but its performance is... not good.
15763 std::string getFormattedDuration( double duration ) {
15764 // Max exponent + 1 is required to represent the whole part
15765 // + 1 for decimal point
15766 // + 3 for the 3 decimal places
15767 // + 1 for null terminator
15768 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15769 char buffer[maxDoubleSize];
15771 // Save previous errno, to prevent sprintf from overwriting it
15774 sprintf_s(buffer, "%.3f", duration);
15776 std::sprintf(buffer, "%.3f", duration);
15778 return std::string(buffer);
15781 bool shouldShowDuration( IConfig const& config, double duration ) {
15782 if ( config.showDurations() == ShowDurations::Always ) {
15785 if ( config.showDurations() == ShowDurations::Never ) {
15788 const double min = config.minDuration();
15789 return min >= 0 && duration >= min;
15792 std::string serializeFilters( std::vector<std::string> const& container ) {
15793 ReusableStringStream oss;
15795 for (auto&& filter : container)
15807 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15808 :StreamingReporterBase(_config) {}
15810 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15811 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15814 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15816 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15820 } // end namespace Catch
15821 // end catch_reporter_bases.cpp
15822 // start catch_reporter_compact.cpp
15826 #ifdef CATCH_PLATFORM_MAC
15827 const char* failedString() { return "FAILED"; }
15828 const char* passedString() { return "PASSED"; }
15830 const char* failedString() { return "failed"; }
15831 const char* passedString() { return "passed"; }
15834 // Colour::LightGrey
15835 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15837 std::string bothOrAll( std::size_t count ) {
15838 return count == 1 ? std::string() :
15839 count == 2 ? "both " : "all " ;
15842 } // anon namespace
15846 // Colour, message variants:
15847 // - white: No tests ran.
15848 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15849 // - white: Passed [both/all] N test cases (no assertions).
15850 // - red: Failed N tests cases, failed M assertions.
15851 // - green: Passed [both/all] N tests cases with M assertions.
15852 void printTotals(std::ostream& out, const Totals& totals) {
15853 if (totals.testCases.total() == 0) {
15854 out << "No tests ran.";
15855 } else if (totals.testCases.failed == totals.testCases.total()) {
15856 Colour colour(Colour::ResultError);
15857 const std::string qualify_assertions_failed =
15858 totals.assertions.failed == totals.assertions.total() ?
15859 bothOrAll(totals.assertions.failed) : std::string();
15861 "Failed " << bothOrAll(totals.testCases.failed)
15862 << pluralise(totals.testCases.failed, "test case") << ", "
15863 "failed " << qualify_assertions_failed <<
15864 pluralise(totals.assertions.failed, "assertion") << '.';
15865 } else if (totals.assertions.total() == 0) {
15867 "Passed " << bothOrAll(totals.testCases.total())
15868 << pluralise(totals.testCases.total(), "test case")
15869 << " (no assertions).";
15870 } else if (totals.assertions.failed) {
15871 Colour colour(Colour::ResultError);
15873 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15874 "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15876 Colour colour(Colour::ResultSuccess);
15878 "Passed " << bothOrAll(totals.testCases.passed)
15879 << pluralise(totals.testCases.passed, "test case") <<
15880 " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15884 // Implementation of CompactReporter formatting
15885 class AssertionPrinter {
15887 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15888 AssertionPrinter(AssertionPrinter const&) = delete;
15889 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15891 , result(_stats.assertionResult)
15892 , messages(_stats.infoMessages)
15893 , itMessage(_stats.infoMessages.begin())
15894 , printInfoMessages(_printInfoMessages) {}
15899 itMessage = messages.begin();
15901 switch (result.getResultType()) {
15902 case ResultWas::Ok:
15903 printResultType(Colour::ResultSuccess, passedString());
15904 printOriginalExpression();
15905 printReconstructedExpression();
15906 if (!result.hasExpression())
15907 printRemainingMessages(Colour::None);
15909 printRemainingMessages();
15911 case ResultWas::ExpressionFailed:
15913 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15915 printResultType(Colour::Error, failedString());
15916 printOriginalExpression();
15917 printReconstructedExpression();
15918 printRemainingMessages();
15920 case ResultWas::ThrewException:
15921 printResultType(Colour::Error, failedString());
15922 printIssue("unexpected exception with message:");
15924 printExpressionWas();
15925 printRemainingMessages();
15927 case ResultWas::FatalErrorCondition:
15928 printResultType(Colour::Error, failedString());
15929 printIssue("fatal error condition with message:");
15931 printExpressionWas();
15932 printRemainingMessages();
15934 case ResultWas::DidntThrowException:
15935 printResultType(Colour::Error, failedString());
15936 printIssue("expected exception, got none");
15937 printExpressionWas();
15938 printRemainingMessages();
15940 case ResultWas::Info:
15941 printResultType(Colour::None, "info");
15943 printRemainingMessages();
15945 case ResultWas::Warning:
15946 printResultType(Colour::None, "warning");
15948 printRemainingMessages();
15950 case ResultWas::ExplicitFailure:
15951 printResultType(Colour::Error, failedString());
15952 printIssue("explicitly");
15953 printRemainingMessages(Colour::None);
15955 // These cases are here to prevent compiler warnings
15956 case ResultWas::Unknown:
15957 case ResultWas::FailureBit:
15958 case ResultWas::Exception:
15959 printResultType(Colour::Error, "** internal error **");
15965 void printSourceInfo() const {
15966 Colour colourGuard(Colour::FileName);
15967 stream << result.getSourceInfo() << ':';
15970 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15971 if (!passOrFail.empty()) {
15973 Colour colourGuard(colour);
15974 stream << ' ' << passOrFail;
15980 void printIssue(std::string const& issue) const {
15981 stream << ' ' << issue;
15984 void printExpressionWas() {
15985 if (result.hasExpression()) {
15988 Colour colour(dimColour());
15989 stream << " expression was:";
15991 printOriginalExpression();
15995 void printOriginalExpression() const {
15996 if (result.hasExpression()) {
15997 stream << ' ' << result.getExpression();
16001 void printReconstructedExpression() const {
16002 if (result.hasExpandedExpression()) {
16004 Colour colour(dimColour());
16005 stream << " for: ";
16007 stream << result.getExpandedExpression();
16011 void printMessage() {
16012 if (itMessage != messages.end()) {
16013 stream << " '" << itMessage->message << '\'';
16018 void printRemainingMessages(Colour::Code colour = dimColour()) {
16019 if (itMessage == messages.end())
16022 const auto itEnd = messages.cend();
16023 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16026 Colour colourGuard(colour);
16027 stream << " with " << pluralise(N, "message") << ':';
16030 while (itMessage != itEnd) {
16031 // If this assertion is a warning ignore any INFO messages
16032 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16034 if (itMessage != itEnd) {
16035 Colour colourGuard(dimColour());
16045 std::ostream& stream;
16046 AssertionResult const& result;
16047 std::vector<MessageInfo> messages;
16048 std::vector<MessageInfo>::const_iterator itMessage;
16049 bool printInfoMessages;
16052 } // anon namespace
16054 std::string CompactReporter::getDescription() {
16055 return "Reports test results on a single line, suitable for IDEs";
16058 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
16059 stream << "No test cases matched '" << spec << '\'' << std::endl;
16062 void CompactReporter::assertionStarting( AssertionInfo const& ) {}
16064 bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
16065 AssertionResult const& result = _assertionStats.assertionResult;
16067 bool printInfoMessages = true;
16069 // Drop out if result was successful and we're not printing those
16070 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16071 if( result.getResultType() != ResultWas::Warning )
16073 printInfoMessages = false;
16076 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16079 stream << std::endl;
16083 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16084 double dur = _sectionStats.durationInSeconds;
16085 if ( shouldShowDuration( *m_config, dur ) ) {
16086 stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16090 void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
16091 printTotals( stream, _testRunStats.totals );
16092 stream << '\n' << std::endl;
16093 StreamingReporterBase::testRunEnded( _testRunStats );
16096 CompactReporter::~CompactReporter() {}
16098 CATCH_REGISTER_REPORTER( "compact", CompactReporter )
16100 } // end namespace Catch
16101 // end catch_reporter_compact.cpp
16102 // start catch_reporter_console.cpp
16107 #if defined(_MSC_VER)
16108 #pragma warning(push)
16109 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16110 // Note that 4062 (not all labels are handled and default is missing) is enabled
16113 #if defined(__clang__)
16114 # pragma clang diagnostic push
16115 // For simplicity, benchmarking-only helpers are always enabled
16116 # pragma clang diagnostic ignored "-Wunused-function"
16123 // Formatter impl for ConsoleReporter
16124 class ConsoleAssertionPrinter {
16126 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
16127 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
16128 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
16131 result(_stats.assertionResult),
16132 colour(Colour::None),
16133 message(result.getMessage()),
16134 messages(_stats.infoMessages),
16135 printInfoMessages(_printInfoMessages) {
16136 switch (result.getResultType()) {
16137 case ResultWas::Ok:
16138 colour = Colour::Success;
16139 passOrFail = "PASSED";
16140 //if( result.hasMessage() )
16141 if (_stats.infoMessages.size() == 1)
16142 messageLabel = "with message";
16143 if (_stats.infoMessages.size() > 1)
16144 messageLabel = "with messages";
16146 case ResultWas::ExpressionFailed:
16147 if (result.isOk()) {
16148 colour = Colour::Success;
16149 passOrFail = "FAILED - but was ok";
16151 colour = Colour::Error;
16152 passOrFail = "FAILED";
16154 if (_stats.infoMessages.size() == 1)
16155 messageLabel = "with message";
16156 if (_stats.infoMessages.size() > 1)
16157 messageLabel = "with messages";
16159 case ResultWas::ThrewException:
16160 colour = Colour::Error;
16161 passOrFail = "FAILED";
16162 messageLabel = "due to unexpected exception with ";
16163 if (_stats.infoMessages.size() == 1)
16164 messageLabel += "message";
16165 if (_stats.infoMessages.size() > 1)
16166 messageLabel += "messages";
16168 case ResultWas::FatalErrorCondition:
16169 colour = Colour::Error;
16170 passOrFail = "FAILED";
16171 messageLabel = "due to a fatal error condition";
16173 case ResultWas::DidntThrowException:
16174 colour = Colour::Error;
16175 passOrFail = "FAILED";
16176 messageLabel = "because no exception was thrown where one was expected";
16178 case ResultWas::Info:
16179 messageLabel = "info";
16181 case ResultWas::Warning:
16182 messageLabel = "warning";
16184 case ResultWas::ExplicitFailure:
16185 passOrFail = "FAILED";
16186 colour = Colour::Error;
16187 if (_stats.infoMessages.size() == 1)
16188 messageLabel = "explicitly with message";
16189 if (_stats.infoMessages.size() > 1)
16190 messageLabel = "explicitly with messages";
16192 // These cases are here to prevent compiler warnings
16193 case ResultWas::Unknown:
16194 case ResultWas::FailureBit:
16195 case ResultWas::Exception:
16196 passOrFail = "** internal error **";
16197 colour = Colour::Error;
16202 void print() const {
16204 if (stats.totals.assertions.total() > 0) {
16206 printOriginalExpression();
16207 printReconstructedExpression();
16215 void printResultType() const {
16216 if (!passOrFail.empty()) {
16217 Colour colourGuard(colour);
16218 stream << passOrFail << ":\n";
16221 void printOriginalExpression() const {
16222 if (result.hasExpression()) {
16223 Colour colourGuard(Colour::OriginalExpression);
16225 stream << result.getExpressionInMacro();
16229 void printReconstructedExpression() const {
16230 if (result.hasExpandedExpression()) {
16231 stream << "with expansion:\n";
16232 Colour colourGuard(Colour::ReconstructedExpression);
16233 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16236 void printMessage() const {
16237 if (!messageLabel.empty())
16238 stream << messageLabel << ':' << '\n';
16239 for (auto const& msg : messages) {
16240 // If this assertion is a warning ignore any INFO messages
16241 if (printInfoMessages || msg.type != ResultWas::Info)
16242 stream << Column(msg.message).indent(2) << '\n';
16245 void printSourceInfo() const {
16246 Colour colourGuard(Colour::FileName);
16247 stream << result.getSourceInfo() << ": ";
16250 std::ostream& stream;
16251 AssertionStats const& stats;
16252 AssertionResult const& result;
16253 Colour::Code colour;
16254 std::string passOrFail;
16255 std::string messageLabel;
16256 std::string message;
16257 std::vector<MessageInfo> messages;
16258 bool printInfoMessages;
16261 std::size_t makeRatio(std::size_t number, std::size_t total) {
16262 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16263 return (ratio == 0 && number > 0) ? 1 : ratio;
16266 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16267 if (i > j && i > k)
16275 struct ColumnInfo {
16276 enum Justification { Left, Right };
16279 Justification justification;
16281 struct ColumnBreak {};
16282 struct RowBreak {};
16293 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16294 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16295 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16296 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16298 double m_inNanoseconds;
16302 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
16303 : m_inNanoseconds(inNanoseconds),
16305 if (m_units == Unit::Auto) {
16306 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16307 m_units = Unit::Nanoseconds;
16308 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16309 m_units = Unit::Microseconds;
16310 else if (m_inNanoseconds < s_nanosecondsInASecond)
16311 m_units = Unit::Milliseconds;
16312 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16313 m_units = Unit::Seconds;
16315 m_units = Unit::Minutes;
16320 auto value() const -> double {
16322 case Unit::Microseconds:
16323 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16324 case Unit::Milliseconds:
16325 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16326 case Unit::Seconds:
16327 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16328 case Unit::Minutes:
16329 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16331 return m_inNanoseconds;
16334 auto unitsAsString() const -> std::string {
16336 case Unit::Nanoseconds:
16338 case Unit::Microseconds:
16340 case Unit::Milliseconds:
16342 case Unit::Seconds:
16344 case Unit::Minutes:
16347 return "** internal error **";
16351 friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
16352 return os << duration.value() << ' ' << duration.unitsAsString();
16355 } // end anon namespace
16357 class TablePrinter {
16358 std::ostream& m_os;
16359 std::vector<ColumnInfo> m_columnInfos;
16360 std::ostringstream m_oss;
16361 int m_currentColumn = -1;
16362 bool m_isOpen = false;
16365 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16367 m_columnInfos( std::move( columnInfos ) ) {}
16369 auto columnInfos() const -> std::vector<ColumnInfo> const& {
16370 return m_columnInfos;
16376 *this << RowBreak();
16378 Columns headerCols;
16380 for (auto const& info : m_columnInfos) {
16381 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16382 headerCols += spacer;
16384 m_os << headerCols << '\n';
16386 m_os << Catch::getLineOfChars<'-'>() << '\n';
16391 *this << RowBreak();
16397 template<typename T>
16398 friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
16403 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
16404 auto colStr = tp.m_oss.str();
16405 const auto strSize = colStr.size();
16408 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16409 tp.m_currentColumn = -1;
16412 tp.m_currentColumn++;
16414 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16415 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16416 ? std::string(colInfo.width - (strSize + 1), ' ')
16418 if (colInfo.justification == ColumnInfo::Left)
16419 tp.m_os << colStr << padding << ' ';
16421 tp.m_os << padding << colStr << ' ';
16425 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
16426 if (tp.m_currentColumn > 0) {
16428 tp.m_currentColumn = -1;
16434 ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
16435 : StreamingReporterBase(config),
16436 m_tablePrinter(new TablePrinter(config.stream(),
16437 [&config]() -> std::vector<ColumnInfo> {
16438 if (config.fullConfig()->benchmarkNoAnalysis())
16441 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16442 { " samples", 14, ColumnInfo::Right },
16443 { " iterations", 14, ColumnInfo::Right },
16444 { " mean", 14, ColumnInfo::Right }
16450 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16451 { "samples mean std dev", 14, ColumnInfo::Right },
16452 { "iterations low mean low std dev", 14, ColumnInfo::Right },
16453 { "estimated high mean high std dev", 14, ColumnInfo::Right }
16457 ConsoleReporter::~ConsoleReporter() = default;
16459 std::string ConsoleReporter::getDescription() {
16460 return "Reports test results as plain lines of text";
16463 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16464 stream << "No test cases matched '" << spec << '\'' << std::endl;
16467 void ConsoleReporter::reportInvalidArguments(std::string const&arg){
16468 stream << "Invalid Filter: " << arg << std::endl;
16471 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16473 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16474 AssertionResult const& result = _assertionStats.assertionResult;
16476 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16478 // Drop out if result was successful but we're not printing them.
16479 if (!includeResults && result.getResultType() != ResultWas::Warning)
16484 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16486 stream << std::endl;
16490 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16491 m_tablePrinter->close();
16492 m_headerPrinted = false;
16493 StreamingReporterBase::sectionStarting(_sectionInfo);
16495 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16496 m_tablePrinter->close();
16497 if (_sectionStats.missingAssertions) {
16499 Colour colour(Colour::ResultError);
16500 if (m_sectionStack.size() > 1)
16501 stream << "\nNo assertions in section";
16503 stream << "\nNo assertions in test case";
16504 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16506 double dur = _sectionStats.durationInSeconds;
16507 if (shouldShowDuration(*m_config, dur)) {
16508 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16510 if (m_headerPrinted) {
16511 m_headerPrinted = false;
16513 StreamingReporterBase::sectionEnded(_sectionStats);
16516 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16517 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16518 lazyPrintWithoutClosingBenchmarkTable();
16520 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16522 bool firstLine = true;
16523 for (auto line : nameCol) {
16525 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16529 (*m_tablePrinter) << line << ColumnBreak();
16533 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16534 (*m_tablePrinter) << info.samples << ColumnBreak()
16535 << info.iterations << ColumnBreak();
16536 if (!m_config->benchmarkNoAnalysis())
16537 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16539 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16540 if (m_config->benchmarkNoAnalysis())
16542 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16546 (*m_tablePrinter) << ColumnBreak()
16547 << Duration(stats.mean.point.count()) << ColumnBreak()
16548 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16549 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16550 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16551 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16552 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16556 void ConsoleReporter::benchmarkFailed(std::string const& error) {
16557 Colour colour(Colour::Red);
16559 << "Benchmark failed (" << error << ')'
16560 << ColumnBreak() << RowBreak();
16562 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16564 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16565 m_tablePrinter->close();
16566 StreamingReporterBase::testCaseEnded(_testCaseStats);
16567 m_headerPrinted = false;
16569 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16570 if (currentGroupInfo.used) {
16571 printSummaryDivider();
16572 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16573 printTotals(_testGroupStats.totals);
16574 stream << '\n' << std::endl;
16576 StreamingReporterBase::testGroupEnded(_testGroupStats);
16578 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16579 printTotalsDivider(_testRunStats.totals);
16580 printTotals(_testRunStats.totals);
16581 stream << std::endl;
16582 StreamingReporterBase::testRunEnded(_testRunStats);
16584 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16585 StreamingReporterBase::testRunStarting(_testInfo);
16586 printTestFilters();
16589 void ConsoleReporter::lazyPrint() {
16591 m_tablePrinter->close();
16592 lazyPrintWithoutClosingBenchmarkTable();
16595 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16597 if (!currentTestRunInfo.used)
16598 lazyPrintRunInfo();
16599 if (!currentGroupInfo.used)
16600 lazyPrintGroupInfo();
16602 if (!m_headerPrinted) {
16603 printTestCaseAndSectionHeader();
16604 m_headerPrinted = true;
16607 void ConsoleReporter::lazyPrintRunInfo() {
16608 stream << '\n' << getLineOfChars<'~'>() << '\n';
16609 Colour colour(Colour::SecondaryText);
16610 stream << currentTestRunInfo->name
16611 << " is a Catch v" << libraryVersion() << " host application.\n"
16612 << "Run with -? for options\n\n";
16614 if (m_config->rngSeed() != 0)
16615 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16617 currentTestRunInfo.used = true;
16619 void ConsoleReporter::lazyPrintGroupInfo() {
16620 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16621 printClosedHeader("Group: " + currentGroupInfo->name);
16622 currentGroupInfo.used = true;
16625 void ConsoleReporter::printTestCaseAndSectionHeader() {
16626 assert(!m_sectionStack.empty());
16627 printOpenHeader(currentTestCaseInfo->name);
16629 if (m_sectionStack.size() > 1) {
16630 Colour colourGuard(Colour::Headers);
16633 it = m_sectionStack.begin() + 1, // Skip first section (test case)
16634 itEnd = m_sectionStack.end();
16635 for (; it != itEnd; ++it)
16636 printHeaderString(it->name, 2);
16639 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16641 stream << getLineOfChars<'-'>() << '\n';
16642 Colour colourGuard(Colour::FileName);
16643 stream << lineInfo << '\n';
16644 stream << getLineOfChars<'.'>() << '\n' << std::endl;
16647 void ConsoleReporter::printClosedHeader(std::string const& _name) {
16648 printOpenHeader(_name);
16649 stream << getLineOfChars<'.'>() << '\n';
16651 void ConsoleReporter::printOpenHeader(std::string const& _name) {
16652 stream << getLineOfChars<'-'>() << '\n';
16654 Colour colourGuard(Colour::Headers);
16655 printHeaderString(_name);
16659 // if string has a : in first line will set indent to follow it on
16660 // subsequent lines
16661 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16662 std::size_t i = _string.find(": ");
16663 if (i != std::string::npos)
16667 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16670 struct SummaryColumn {
16672 SummaryColumn( std::string _label, Colour::Code _colour )
16673 : label( std::move( _label ) ),
16674 colour( _colour ) {}
16675 SummaryColumn addRow( std::size_t count ) {
16676 ReusableStringStream rss;
16678 std::string row = rss.str();
16679 for (auto& oldRow : rows) {
16680 while (oldRow.size() < row.size())
16681 oldRow = ' ' + oldRow;
16682 while (oldRow.size() > row.size())
16685 rows.push_back(row);
16690 Colour::Code colour;
16691 std::vector<std::string> rows;
16695 void ConsoleReporter::printTotals( Totals const& totals ) {
16696 if (totals.testCases.total() == 0) {
16697 stream << Colour(Colour::Warning) << "No tests ran\n";
16698 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16699 stream << Colour(Colour::ResultSuccess) << "All tests passed";
16701 << pluralise(totals.assertions.passed, "assertion") << " in "
16702 << pluralise(totals.testCases.passed, "test case") << ')'
16706 std::vector<SummaryColumn> columns;
16707 columns.push_back(SummaryColumn("", Colour::None)
16708 .addRow(totals.testCases.total())
16709 .addRow(totals.assertions.total()));
16710 columns.push_back(SummaryColumn("passed", Colour::Success)
16711 .addRow(totals.testCases.passed)
16712 .addRow(totals.assertions.passed));
16713 columns.push_back(SummaryColumn("failed", Colour::ResultError)
16714 .addRow(totals.testCases.failed)
16715 .addRow(totals.assertions.failed));
16716 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
16717 .addRow(totals.testCases.failedButOk)
16718 .addRow(totals.assertions.failedButOk));
16720 printSummaryRow("test cases", columns, 0);
16721 printSummaryRow("assertions", columns, 1);
16724 void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
16725 for (auto col : cols) {
16726 std::string value = col.rows[row];
16727 if (col.label.empty()) {
16728 stream << label << ": ";
16732 stream << Colour(Colour::Warning) << "- none -";
16733 } else if (value != "0") {
16734 stream << Colour(Colour::LightGrey) << " | ";
16735 stream << Colour(col.colour)
16736 << value << ' ' << col.label;
16742 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
16743 if (totals.testCases.total() > 0) {
16744 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16745 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16746 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16747 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16748 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16749 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16750 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16752 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
16753 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
16754 if (totals.testCases.allPassed())
16755 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
16757 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
16759 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
16763 void ConsoleReporter::printSummaryDivider() {
16764 stream << getLineOfChars<'-'>() << '\n';
16767 void ConsoleReporter::printTestFilters() {
16768 if (m_config->testSpec().hasFilters()) {
16769 Colour guard(Colour::BrightYellow);
16770 stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
16774 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
16776 } // end namespace Catch
16778 #if defined(_MSC_VER)
16779 #pragma warning(pop)
16782 #if defined(__clang__)
16783 # pragma clang diagnostic pop
16785 // end catch_reporter_console.cpp
16786 // start catch_reporter_junit.cpp
16791 #include <algorithm>
16796 std::string getCurrentTimestamp() {
16797 // Beware, this is not reentrant because of backward compatibility issues
16798 // Also, UTC only, again because of backward compatibility (%z is C++11)
16800 std::time(&rawtime);
16801 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
16804 std::tm timeInfo = {};
16805 gmtime_s(&timeInfo, &rawtime);
16808 timeInfo = std::gmtime(&rawtime);
16811 char timeStamp[timeStampSize];
16812 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
16815 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16817 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16819 return std::string(timeStamp);
16822 std::string fileNameTag(const std::vector<std::string> &tags) {
16823 auto it = std::find_if(begin(tags),
16825 [] (std::string const& tag) {return tag.front() == '#'; });
16826 if (it != tags.end())
16827 return it->substr(1);
16828 return std::string();
16830 } // anonymous namespace
16832 JunitReporter::JunitReporter( ReporterConfig const& _config )
16833 : CumulativeReporterBase( _config ),
16834 xml( _config.stream() )
16836 m_reporterPrefs.shouldRedirectStdOut = true;
16837 m_reporterPrefs.shouldReportAllAssertions = true;
16840 JunitReporter::~JunitReporter() {}
16842 std::string JunitReporter::getDescription() {
16843 return "Reports test results in an XML format that looks like Ant's junitreport target";
16846 void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
16848 void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
16849 CumulativeReporterBase::testRunStarting( runInfo );
16850 xml.startElement( "testsuites" );
16853 void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16854 suiteTimer.start();
16855 stdOutForSuite.clear();
16856 stdErrForSuite.clear();
16857 unexpectedExceptions = 0;
16858 CumulativeReporterBase::testGroupStarting( groupInfo );
16861 void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
16862 m_okToFail = testCaseInfo.okToFail();
16865 bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
16866 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16867 unexpectedExceptions++;
16868 return CumulativeReporterBase::assertionEnded( assertionStats );
16871 void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16872 stdOutForSuite += testCaseStats.stdOut;
16873 stdErrForSuite += testCaseStats.stdErr;
16874 CumulativeReporterBase::testCaseEnded( testCaseStats );
16877 void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16878 double suiteTime = suiteTimer.getElapsedSeconds();
16879 CumulativeReporterBase::testGroupEnded( testGroupStats );
16880 writeGroup( *m_testGroups.back(), suiteTime );
16883 void JunitReporter::testRunEndedCumulative() {
16887 void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
16888 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
16890 TestGroupStats const& stats = groupNode.value;
16891 xml.writeAttribute( "name", stats.groupInfo.name );
16892 xml.writeAttribute( "errors", unexpectedExceptions );
16893 xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
16894 xml.writeAttribute( "tests", stats.totals.assertions.total() );
16895 xml.writeAttribute( "hostname", "tbd" ); // !TBD
16896 if( m_config->showDurations() == ShowDurations::Never )
16897 xml.writeAttribute( "time", "" );
16899 xml.writeAttribute( "time", suiteTime );
16900 xml.writeAttribute( "timestamp", getCurrentTimestamp() );
16902 // Write properties if there are any
16903 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16904 auto properties = xml.scopedElement("properties");
16905 if (m_config->hasTestFilters()) {
16906 xml.scopedElement("property")
16907 .writeAttribute("name", "filters")
16908 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16910 if (m_config->rngSeed() != 0) {
16911 xml.scopedElement("property")
16912 .writeAttribute("name", "random-seed")
16913 .writeAttribute("value", m_config->rngSeed());
16917 // Write test cases
16918 for( auto const& child : groupNode.children )
16919 writeTestCase( *child );
16921 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16922 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16925 void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
16926 TestCaseStats const& stats = testCaseNode.value;
16928 // All test cases have exactly one section - which represents the
16929 // test case itself. That section may have 0-n nested sections
16930 assert( testCaseNode.children.size() == 1 );
16931 SectionNode const& rootSection = *testCaseNode.children.front();
16933 std::string className = stats.testInfo.className;
16935 if( className.empty() ) {
16936 className = fileNameTag(stats.testInfo.tags);
16937 if ( className.empty() )
16938 className = "global";
16941 if ( !m_config->name().empty() )
16942 className = m_config->name() + "." + className;
16944 writeSection( className, "", rootSection );
16947 void JunitReporter::writeSection( std::string const& className,
16948 std::string const& rootName,
16949 SectionNode const& sectionNode ) {
16950 std::string name = trim( sectionNode.stats.sectionInfo.name );
16951 if( !rootName.empty() )
16952 name = rootName + '/' + name;
16954 if( !sectionNode.assertions.empty() ||
16955 !sectionNode.stdOut.empty() ||
16956 !sectionNode.stdErr.empty() ) {
16957 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
16958 if( className.empty() ) {
16959 xml.writeAttribute( "classname", name );
16960 xml.writeAttribute( "name", "root" );
16963 xml.writeAttribute( "classname", className );
16964 xml.writeAttribute( "name", name );
16966 xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
16967 // This is not ideal, but it should be enough to mimic gtest's
16969 // Ideally the JUnit reporter would also handle `skipTest`
16970 // events and write those out appropriately.
16971 xml.writeAttribute( "status", "run" );
16973 writeAssertions( sectionNode );
16975 if( !sectionNode.stdOut.empty() )
16976 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
16977 if( !sectionNode.stdErr.empty() )
16978 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
16980 for( auto const& childNode : sectionNode.childSections )
16981 if( className.empty() )
16982 writeSection( name, "", *childNode );
16984 writeSection( className, name, *childNode );
16987 void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
16988 for( auto const& assertion : sectionNode.assertions )
16989 writeAssertion( assertion );
16992 void JunitReporter::writeAssertion( AssertionStats const& stats ) {
16993 AssertionResult const& result = stats.assertionResult;
16994 if( !result.isOk() ) {
16995 std::string elementName;
16996 switch( result.getResultType() ) {
16997 case ResultWas::ThrewException:
16998 case ResultWas::FatalErrorCondition:
16999 elementName = "error";
17001 case ResultWas::ExplicitFailure:
17002 case ResultWas::ExpressionFailed:
17003 case ResultWas::DidntThrowException:
17004 elementName = "failure";
17007 // We should never see these here:
17008 case ResultWas::Info:
17009 case ResultWas::Warning:
17010 case ResultWas::Ok:
17011 case ResultWas::Unknown:
17012 case ResultWas::FailureBit:
17013 case ResultWas::Exception:
17014 elementName = "internalError";
17018 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17020 xml.writeAttribute( "message", result.getExpression() );
17021 xml.writeAttribute( "type", result.getTestMacroName() );
17023 ReusableStringStream rss;
17024 if (stats.totals.assertions.total() > 0) {
17025 rss << "FAILED" << ":\n";
17026 if (result.hasExpression()) {
17028 rss << result.getExpressionInMacro();
17031 if (result.hasExpandedExpression()) {
17032 rss << "with expansion:\n";
17033 rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17039 if( !result.getMessage().empty() )
17040 rss << result.getMessage() << '\n';
17041 for( auto const& msg : stats.infoMessages )
17042 if( msg.type == ResultWas::Info )
17043 rss << msg.message << '\n';
17045 rss << "at " << result.getSourceInfo();
17046 xml.writeText( rss.str(), XmlFormatting::Newline );
17050 CATCH_REGISTER_REPORTER( "junit", JunitReporter )
17052 } // end namespace Catch
17053 // end catch_reporter_junit.cpp
17054 // start catch_reporter_listening.cpp
17060 ListeningReporter::ListeningReporter() {
17061 // We will assume that listeners will always want all assertions
17062 m_preferences.shouldReportAllAssertions = true;
17065 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17066 m_listeners.push_back( std::move( listener ) );
17069 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17070 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17071 m_reporter = std::move( reporter );
17072 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17075 ReporterPreferences ListeningReporter::getPreferences() const {
17076 return m_preferences;
17079 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17080 return std::set<Verbosity>{ };
17083 void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
17084 for ( auto const& listener : m_listeners ) {
17085 listener->noMatchingTestCases( spec );
17087 m_reporter->noMatchingTestCases( spec );
17090 void ListeningReporter::reportInvalidArguments(std::string const&arg){
17091 for ( auto const& listener : m_listeners ) {
17092 listener->reportInvalidArguments( arg );
17094 m_reporter->reportInvalidArguments( arg );
17097 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17098 void ListeningReporter::benchmarkPreparing( std::string const& name ) {
17099 for (auto const& listener : m_listeners) {
17100 listener->benchmarkPreparing(name);
17102 m_reporter->benchmarkPreparing(name);
17104 void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
17105 for ( auto const& listener : m_listeners ) {
17106 listener->benchmarkStarting( benchmarkInfo );
17108 m_reporter->benchmarkStarting( benchmarkInfo );
17110 void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
17111 for ( auto const& listener : m_listeners ) {
17112 listener->benchmarkEnded( benchmarkStats );
17114 m_reporter->benchmarkEnded( benchmarkStats );
17117 void ListeningReporter::benchmarkFailed( std::string const& error ) {
17118 for (auto const& listener : m_listeners) {
17119 listener->benchmarkFailed(error);
17121 m_reporter->benchmarkFailed(error);
17123 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17125 void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
17126 for ( auto const& listener : m_listeners ) {
17127 listener->testRunStarting( testRunInfo );
17129 m_reporter->testRunStarting( testRunInfo );
17132 void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17133 for ( auto const& listener : m_listeners ) {
17134 listener->testGroupStarting( groupInfo );
17136 m_reporter->testGroupStarting( groupInfo );
17139 void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17140 for ( auto const& listener : m_listeners ) {
17141 listener->testCaseStarting( testInfo );
17143 m_reporter->testCaseStarting( testInfo );
17146 void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17147 for ( auto const& listener : m_listeners ) {
17148 listener->sectionStarting( sectionInfo );
17150 m_reporter->sectionStarting( sectionInfo );
17153 void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
17154 for ( auto const& listener : m_listeners ) {
17155 listener->assertionStarting( assertionInfo );
17157 m_reporter->assertionStarting( assertionInfo );
17160 // The return value indicates if the messages buffer should be cleared:
17161 bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
17162 for( auto const& listener : m_listeners ) {
17163 static_cast<void>( listener->assertionEnded( assertionStats ) );
17165 return m_reporter->assertionEnded( assertionStats );
17168 void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
17169 for ( auto const& listener : m_listeners ) {
17170 listener->sectionEnded( sectionStats );
17172 m_reporter->sectionEnded( sectionStats );
17175 void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17176 for ( auto const& listener : m_listeners ) {
17177 listener->testCaseEnded( testCaseStats );
17179 m_reporter->testCaseEnded( testCaseStats );
17182 void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17183 for ( auto const& listener : m_listeners ) {
17184 listener->testGroupEnded( testGroupStats );
17186 m_reporter->testGroupEnded( testGroupStats );
17189 void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
17190 for ( auto const& listener : m_listeners ) {
17191 listener->testRunEnded( testRunStats );
17193 m_reporter->testRunEnded( testRunStats );
17196 void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
17197 for ( auto const& listener : m_listeners ) {
17198 listener->skipTest( testInfo );
17200 m_reporter->skipTest( testInfo );
17203 bool ListeningReporter::isMulti() const {
17207 } // end namespace Catch
17208 // end catch_reporter_listening.cpp
17209 // start catch_reporter_xml.cpp
17211 #if defined(_MSC_VER)
17212 #pragma warning(push)
17213 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
17214 // Note that 4062 (not all labels are handled
17215 // and default is missing) is enabled
17219 XmlReporter::XmlReporter( ReporterConfig const& _config )
17220 : StreamingReporterBase( _config ),
17221 m_xml(_config.stream())
17223 m_reporterPrefs.shouldRedirectStdOut = true;
17224 m_reporterPrefs.shouldReportAllAssertions = true;
17227 XmlReporter::~XmlReporter() = default;
17229 std::string XmlReporter::getDescription() {
17230 return "Reports test results as an XML document";
17233 std::string XmlReporter::getStylesheetRef() const {
17234 return std::string();
17237 void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
17239 .writeAttribute( "filename", sourceInfo.file )
17240 .writeAttribute( "line", sourceInfo.line );
17243 void XmlReporter::noMatchingTestCases( std::string const& s ) {
17244 StreamingReporterBase::noMatchingTestCases( s );
17247 void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
17248 StreamingReporterBase::testRunStarting( testInfo );
17249 std::string stylesheetRef = getStylesheetRef();
17250 if( !stylesheetRef.empty() )
17251 m_xml.writeStylesheetRef( stylesheetRef );
17252 m_xml.startElement( "Catch" );
17253 if( !m_config->name().empty() )
17254 m_xml.writeAttribute( "name", m_config->name() );
17255 if (m_config->testSpec().hasFilters())
17256 m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
17257 if( m_config->rngSeed() != 0 )
17258 m_xml.scopedElement( "Randomness" )
17259 .writeAttribute( "seed", m_config->rngSeed() );
17262 void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17263 StreamingReporterBase::testGroupStarting( groupInfo );
17264 m_xml.startElement( "Group" )
17265 .writeAttribute( "name", groupInfo.name );
17268 void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17269 StreamingReporterBase::testCaseStarting(testInfo);
17270 m_xml.startElement( "TestCase" )
17271 .writeAttribute( "name", trim( testInfo.name ) )
17272 .writeAttribute( "description", testInfo.description )
17273 .writeAttribute( "tags", testInfo.tagsAsString() );
17275 writeSourceInfo( testInfo.lineInfo );
17277 if ( m_config->showDurations() == ShowDurations::Always )
17278 m_testCaseTimer.start();
17279 m_xml.ensureTagClosed();
17282 void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17283 StreamingReporterBase::sectionStarting( sectionInfo );
17284 if( m_sectionDepth++ > 0 ) {
17285 m_xml.startElement( "Section" )
17286 .writeAttribute( "name", trim( sectionInfo.name ) );
17287 writeSourceInfo( sectionInfo.lineInfo );
17288 m_xml.ensureTagClosed();
17292 void XmlReporter::assertionStarting( AssertionInfo const& ) { }
17294 bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
17296 AssertionResult const& result = assertionStats.assertionResult;
17298 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17300 if( includeResults || result.getResultType() == ResultWas::Warning ) {
17301 // Print any info messages in <Info> tags.
17302 for( auto const& msg : assertionStats.infoMessages ) {
17303 if( msg.type == ResultWas::Info && includeResults ) {
17304 m_xml.scopedElement( "Info" )
17305 .writeText( msg.message );
17306 } else if ( msg.type == ResultWas::Warning ) {
17307 m_xml.scopedElement( "Warning" )
17308 .writeText( msg.message );
17313 // Drop out if result was successful but we're not printing them.
17314 if( !includeResults && result.getResultType() != ResultWas::Warning )
17317 // Print the expression if there is one.
17318 if( result.hasExpression() ) {
17319 m_xml.startElement( "Expression" )
17320 .writeAttribute( "success", result.succeeded() )
17321 .writeAttribute( "type", result.getTestMacroName() );
17323 writeSourceInfo( result.getSourceInfo() );
17325 m_xml.scopedElement( "Original" )
17326 .writeText( result.getExpression() );
17327 m_xml.scopedElement( "Expanded" )
17328 .writeText( result.getExpandedExpression() );
17331 // And... Print a result applicable to each result type.
17332 switch( result.getResultType() ) {
17333 case ResultWas::ThrewException:
17334 m_xml.startElement( "Exception" );
17335 writeSourceInfo( result.getSourceInfo() );
17336 m_xml.writeText( result.getMessage() );
17337 m_xml.endElement();
17339 case ResultWas::FatalErrorCondition:
17340 m_xml.startElement( "FatalErrorCondition" );
17341 writeSourceInfo( result.getSourceInfo() );
17342 m_xml.writeText( result.getMessage() );
17343 m_xml.endElement();
17345 case ResultWas::Info:
17346 m_xml.scopedElement( "Info" )
17347 .writeText( result.getMessage() );
17349 case ResultWas::Warning:
17350 // Warning will already have been written
17352 case ResultWas::ExplicitFailure:
17353 m_xml.startElement( "Failure" );
17354 writeSourceInfo( result.getSourceInfo() );
17355 m_xml.writeText( result.getMessage() );
17356 m_xml.endElement();
17362 if( result.hasExpression() )
17363 m_xml.endElement();
17368 void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
17369 StreamingReporterBase::sectionEnded( sectionStats );
17370 if( --m_sectionDepth > 0 ) {
17371 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
17372 e.writeAttribute( "successes", sectionStats.assertions.passed );
17373 e.writeAttribute( "failures", sectionStats.assertions.failed );
17374 e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
17376 if ( m_config->showDurations() == ShowDurations::Always )
17377 e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
17379 m_xml.endElement();
17383 void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17384 StreamingReporterBase::testCaseEnded( testCaseStats );
17385 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
17386 e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
17388 if ( m_config->showDurations() == ShowDurations::Always )
17389 e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17391 if( !testCaseStats.stdOut.empty() )
17392 m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17393 if( !testCaseStats.stdErr.empty() )
17394 m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17396 m_xml.endElement();
17399 void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17400 StreamingReporterBase::testGroupEnded( testGroupStats );
17401 // TODO: Check testGroupStats.aborting and act accordingly.
17402 m_xml.scopedElement( "OverallResults" )
17403 .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
17404 .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
17405 .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
17406 m_xml.scopedElement( "OverallResultsCases")
17407 .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
17408 .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
17409 .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
17410 m_xml.endElement();
17413 void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
17414 StreamingReporterBase::testRunEnded( testRunStats );
17415 m_xml.scopedElement( "OverallResults" )
17416 .writeAttribute( "successes", testRunStats.totals.assertions.passed )
17417 .writeAttribute( "failures", testRunStats.totals.assertions.failed )
17418 .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
17419 m_xml.scopedElement( "OverallResultsCases")
17420 .writeAttribute( "successes", testRunStats.totals.testCases.passed )
17421 .writeAttribute( "failures", testRunStats.totals.testCases.failed )
17422 .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
17423 m_xml.endElement();
17426 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17427 void XmlReporter::benchmarkPreparing(std::string const& name) {
17428 m_xml.startElement("BenchmarkResults")
17429 .writeAttribute("name", name);
17432 void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
17433 m_xml.writeAttribute("samples", info.samples)
17434 .writeAttribute("resamples", info.resamples)
17435 .writeAttribute("iterations", info.iterations)
17436 .writeAttribute("clockResolution", info.clockResolution)
17437 .writeAttribute("estimatedDuration", info.estimatedDuration)
17438 .writeComment("All values in nano seconds");
17441 void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17442 m_xml.startElement("mean")
17443 .writeAttribute("value", benchmarkStats.mean.point.count())
17444 .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17445 .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17446 .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17447 m_xml.endElement();
17448 m_xml.startElement("standardDeviation")
17449 .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17450 .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17451 .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17452 .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17453 m_xml.endElement();
17454 m_xml.startElement("outliers")
17455 .writeAttribute("variance", benchmarkStats.outlierVariance)
17456 .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17457 .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17458 .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17459 .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17460 m_xml.endElement();
17461 m_xml.endElement();
17464 void XmlReporter::benchmarkFailed(std::string const &error) {
17465 m_xml.scopedElement("failed").
17466 writeAttribute("message", error);
17467 m_xml.endElement();
17469 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17471 CATCH_REGISTER_REPORTER( "xml", XmlReporter )
17473 } // end namespace Catch
17475 #if defined(_MSC_VER)
17476 #pragma warning(pop)
17478 // end catch_reporter_xml.cpp
17481 LeakDetector leakDetector;
17485 #pragma clang diagnostic pop
17488 // end catch_impl.hpp
17491 #ifdef CATCH_CONFIG_MAIN
17492 // start catch_default_main.hpp
17496 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17497 // Standard C/C++ Win32 Unicode wmain entry point
17498 extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
17500 // Standard C/C++ main entry point
17501 int main (int argc, char * argv[]) {
17504 return Catch::Session().run( argc, argv );
17509 // Objective-C entry point
17510 int main (int argc, char * const argv[]) {
17511 #if !CATCH_ARC_ENABLED
17512 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17515 Catch::registerTestMethods();
17516 int result = Catch::Session().run( argc, (char**)argv );
17518 #if !CATCH_ARC_ENABLED
17527 // end catch_default_main.hpp
17530 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17532 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17533 # undef CLARA_CONFIG_MAIN
17536 #if !defined(CATCH_CONFIG_DISABLE)
17538 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17539 #ifdef CATCH_CONFIG_PREFIX_ALL
17541 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17542 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17544 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17545 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17546 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17547 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17548 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17549 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17550 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17552 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17553 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17554 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17555 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17556 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17558 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17559 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17560 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17561 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17562 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17563 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17564 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17566 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17567 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17569 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17570 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17572 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17573 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17574 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17575 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17577 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17578 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17579 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17580 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17581 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17582 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17583 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17584 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17585 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17587 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17589 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17590 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17591 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17592 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17593 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17594 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17595 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17596 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17597 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17599 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17600 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17601 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17602 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17603 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17604 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17605 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17606 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17609 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17610 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
17611 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17613 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
17614 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17617 // "BDD-style" convenience wrappers
17618 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17619 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17620 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17621 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17622 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17623 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17624 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17625 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17627 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17628 #define CATCH_BENCHMARK(...) \
17629 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
17630 #define CATCH_BENCHMARK_ADVANCED(name) \
17631 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17632 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17634 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17637 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17638 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17640 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17641 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17642 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17643 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17644 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17645 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17646 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17648 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17649 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17650 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17651 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17652 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17654 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17655 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17656 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17657 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17658 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17659 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17660 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17662 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17663 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17665 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17666 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17668 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17669 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17670 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17671 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17673 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17674 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17675 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17676 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17677 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17678 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17679 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17680 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17681 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17682 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17684 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17685 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17686 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17687 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17688 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17689 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17690 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17691 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17692 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17693 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17694 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17696 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17697 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17698 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17699 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17700 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17701 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17702 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17703 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17704 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17705 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17708 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17709 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17710 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17712 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
17713 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17718 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17720 // "BDD-style" convenience wrappers
17721 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17722 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17724 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17725 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17726 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17727 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17728 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17729 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17731 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17732 #define BENCHMARK(...) \
17733 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
17734 #define BENCHMARK_ADVANCED(name) \
17735 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17736 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17738 using Catch::Detail::Approx;
17740 #else // CATCH_CONFIG_DISABLE
17743 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17744 #ifdef CATCH_CONFIG_PREFIX_ALL
17746 #define CATCH_REQUIRE( ... ) (void)(0)
17747 #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
17749 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17750 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17751 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17752 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17753 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17754 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17755 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17757 #define CATCH_CHECK( ... ) (void)(0)
17758 #define CATCH_CHECK_FALSE( ... ) (void)(0)
17759 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
17760 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17761 #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
17763 #define CATCH_CHECK_THROWS( ... ) (void)(0)
17764 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17765 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17766 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17767 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17768 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17769 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17771 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17772 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
17774 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17775 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17777 #define CATCH_INFO( msg ) (void)(0)
17778 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17779 #define CATCH_WARN( msg ) (void)(0)
17780 #define CATCH_CAPTURE( msg ) (void)(0)
17782 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17783 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17784 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
17785 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17786 #define CATCH_SECTION( ... )
17787 #define CATCH_DYNAMIC_SECTION( ... )
17788 #define CATCH_FAIL( ... ) (void)(0)
17789 #define CATCH_FAIL_CHECK( ... ) (void)(0)
17790 #define CATCH_SUCCEED( ... ) (void)(0)
17792 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17794 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17795 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17796 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17797 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17798 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17799 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17800 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17801 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17802 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17804 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17805 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17806 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17807 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17808 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17809 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17810 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17811 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17814 // "BDD-style" convenience wrappers
17815 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17816 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17817 #define CATCH_GIVEN( desc )
17818 #define CATCH_AND_GIVEN( desc )
17819 #define CATCH_WHEN( desc )
17820 #define CATCH_AND_WHEN( desc )
17821 #define CATCH_THEN( desc )
17822 #define CATCH_AND_THEN( desc )
17824 #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
17825 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17827 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17830 #define REQUIRE( ... ) (void)(0)
17831 #define REQUIRE_FALSE( ... ) (void)(0)
17833 #define REQUIRE_THROWS( ... ) (void)(0)
17834 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17835 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17836 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17837 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17838 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17839 #define REQUIRE_NOTHROW( ... ) (void)(0)
17841 #define CHECK( ... ) (void)(0)
17842 #define CHECK_FALSE( ... ) (void)(0)
17843 #define CHECKED_IF( ... ) if (__VA_ARGS__)
17844 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17845 #define CHECK_NOFAIL( ... ) (void)(0)
17847 #define CHECK_THROWS( ... ) (void)(0)
17848 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17849 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17850 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17851 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17852 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17853 #define CHECK_NOTHROW( ... ) (void)(0)
17855 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17856 #define CHECK_THAT( arg, matcher ) (void)(0)
17858 #define REQUIRE_THAT( arg, matcher ) (void)(0)
17859 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17861 #define INFO( msg ) (void)(0)
17862 #define UNSCOPED_INFO( msg ) (void)(0)
17863 #define WARN( msg ) (void)(0)
17864 #define CAPTURE( msg ) (void)(0)
17866 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17867 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17868 #define METHOD_AS_TEST_CASE( method, ... )
17869 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17870 #define SECTION( ... )
17871 #define DYNAMIC_SECTION( ... )
17872 #define FAIL( ... ) (void)(0)
17873 #define FAIL_CHECK( ... ) (void)(0)
17874 #define SUCCEED( ... ) (void)(0)
17875 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17877 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17878 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17879 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17880 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17881 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17882 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17883 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17884 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17885 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17887 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17888 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17889 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17890 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17891 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17892 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17893 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17894 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17897 #define STATIC_REQUIRE( ... ) (void)(0)
17898 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17902 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17904 // "BDD-style" convenience wrappers
17905 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
17906 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17908 #define GIVEN( desc )
17909 #define AND_GIVEN( desc )
17910 #define WHEN( desc )
17911 #define AND_WHEN( desc )
17912 #define THEN( desc )
17913 #define AND_THEN( desc )
17915 using Catch::Detail::Approx;
17919 #endif // ! CATCH_CONFIG_IMPL_ONLY
17921 // start catch_reenable_warnings.h
17925 # ifdef __ICC // icpc defines the __clang__ macro
17926 # pragma warning(pop)
17928 # pragma clang diagnostic pop
17930 #elif defined __GNUC__
17931 # pragma GCC diagnostic pop
17934 // end catch_reenable_warnings.h
17936 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED