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 1
21 # pragma clang system_header
22 #elif defined __GNUC__
23 # pragma GCC system_header
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__
42 # pragma GCC diagnostic ignored "-Wparentheses"
44 # pragma GCC diagnostic push
45 # pragma GCC diagnostic ignored "-Wunused-variable"
46 # pragma GCC diagnostic ignored "-Wpadded"
49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
51 # define CATCH_CONFIG_ALL_PARTS
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)
70 # include <TargetConditionals.h>
71 # if TARGET_OS_OSX == 1
72 # define CATCH_PLATFORM_MAC
73 # elif TARGET_OS_IPHONE == 1
74 # define CATCH_PLATFORM_IPHONE
77 #elif defined(linux) || defined(__linux) || defined(__linux__)
78 # define CATCH_PLATFORM_LINUX
80 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
81 # define CATCH_PLATFORM_WINDOWS
87 # ifndef CLARA_CONFIG_MAIN
88 # define CLARA_CONFIG_MAIN_NOT_DEFINED
89 # define CLARA_CONFIG_MAIN
96 unsigned int rngSeed();
125 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
126 # define CATCH_CPP14_OR_GREATER
129 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
130 # define CATCH_CPP17_OR_GREATER
135 #if defined(__cpp_lib_uncaught_exceptions)
136 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
141 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC)
142 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
143 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
145 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
149 #if defined(__clang__)
151 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
152 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
165 # if !defined(__ibmxl__)
166 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
169 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
170 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
171 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
173 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
174 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
176 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
177 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
179 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
180 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
182 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
183 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
189 #if !defined(CATCH_PLATFORM_WINDOWS)
190 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
195 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
196 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
200 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
201 # define CATCH_CONFIG_COLOUR_NONE
206 #if defined(__ANDROID__)
207 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
208 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
213 #if defined(__MINGW32__)
214 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
219 #if defined(__ORBIS__)
220 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
232 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
233 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
235 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
242 #if defined(_MSC_VER)
244 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
245 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
247 # if _MSC_VER >= 1900
248 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
253 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
254 # define CATCH_CONFIG_COLOUR_NONE
256 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
262 # if !defined(__clang__)
263 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
264 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
270 #if defined(_REENTRANT) || defined(_MSC_VER)
272 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
277 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
278 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
284 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
289 #if defined(__BORLANDC__)
290 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
300 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
301 #define CATCH_INTERNAL_CONFIG_COUNTER
309 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
310 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
311 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
312 #define CATCH_CONFIG_COLOUR_NONE
315 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
316 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
320 #if defined(__has_include)
322 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
323 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
327 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
328 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
332 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
334 # if __cpp_lib_byte > 0
335 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
340 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
341 # if defined(__clang__) && (__clang_major__ < 8)
345 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
346 # define CATCH_CONFIG_NO_CPP17_VARIANT
348 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
351 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
356 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
357 # define CATCH_CONFIG_COUNTER
359 #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)
360 # define CATCH_CONFIG_WINDOWS_SEH
363 #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)
364 # define CATCH_CONFIG_POSIX_SIGNALS
367 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
368 # define CATCH_CONFIG_WCHAR
371 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
372 # define CATCH_CONFIG_CPP11_TO_STRING
375 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
376 # define CATCH_CONFIG_CPP17_OPTIONAL
379 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
380 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
383 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
384 # define CATCH_CONFIG_CPP17_STRING_VIEW
387 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
388 # define CATCH_CONFIG_CPP17_VARIANT
391 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
392 # define CATCH_CONFIG_CPP17_BYTE
395 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
396 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
399 #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)
400 # define CATCH_CONFIG_NEW_CAPTURE
403 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
404 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
407 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
408 # define CATCH_CONFIG_POLYFILL_ISNAN
411 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
412 # define CATCH_CONFIG_USE_ASYNC
415 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
416 # define CATCH_CONFIG_ANDROID_LOGWRITE
419 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
420 # define CATCH_CONFIG_GLOBAL_NEXTAFTER
425 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
426 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
428 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
429 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
431 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
432 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
434 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
435 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
437 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
438 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
440 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
441 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
446 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
447 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
450 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
451 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
452 #elif defined(__clang__) && (__clang_major__ < 5)
453 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
456 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
457 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
460 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
461 #define CATCH_TRY if ((true))
462 #define CATCH_CATCH_ALL if ((false))
463 #define CATCH_CATCH_ANON(type) if ((false))
465 #define CATCH_TRY try
466 #define CATCH_CATCH_ALL catch (...)
467 #define CATCH_CATCH_ANON(type) catch (type)
470 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
471 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
475 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
476 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
477 #ifdef CATCH_CONFIG_COUNTER
478 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
480 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
522 bool empty()
const noexcept {
return file[0] ==
'\0'; }
530 std::ostream& operator << ( std::ostream& os,
SourceLineInfo const& info );
542 std::string operator+()
const;
550 #define CATCH_INTERNAL_LINEINFO \
551 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
562 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
563 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
564 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
565 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
566 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
580 virtual void invoke ()
const = 0;
589 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
590 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const = 0;
595 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases,
TestSpec const& testSpec,
IConfig const& config );
596 std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config );
615 using size_type = std::size_t;
616 using const_iterator =
const char*;
619 static constexpr
char const*
const s_empty =
"";
621 char const* m_start = s_empty;
622 size_type m_size = 0;
625 constexpr
StringRef() noexcept =
default;
627 StringRef(
char const* rawChars ) noexcept;
629 constexpr
StringRef(
char const* rawChars, size_type size ) noexcept
630 : m_start( rawChars ),
634 StringRef( std::string
const& stdString ) noexcept
635 : m_start( stdString.c_str() ),
636 m_size( stdString.size() )
639 explicit operator std::string()
const {
640 return std::string(m_start, m_size);
644 auto operator == (
StringRef const& other )
const noexcept -> bool;
645 auto operator != (
StringRef const& other)
const noexcept ->
bool {
646 return !(*
this == other);
649 auto operator[] ( size_type index )
const noexcept ->
char {
650 assert(index < m_size);
651 return m_start[index];
655 constexpr
auto empty()
const noexcept ->
bool {
658 constexpr
auto size()
const noexcept -> size_type {
664 auto c_str()
const ->
char const*;
670 auto substr( size_type start, size_type length )
const noexcept ->
StringRef;
673 auto data()
const noexcept ->
char const*;
675 constexpr
auto isNullTerminated()
const noexcept ->
bool {
676 return m_start[m_size] ==
'\0';
680 constexpr const_iterator begin()
const {
return m_start; }
681 constexpr const_iterator end()
const {
return m_start + m_size; }
684 auto operator += ( std::string& lhs,
StringRef const& sr ) -> std::string&;
685 auto operator << ( std::ostream& os,
StringRef const& sr ) -> std::ostream&;
687 constexpr
auto operator "" _sr(
char const* rawChars, std::size_t size ) noexcept ->
StringRef {
692 constexpr
auto operator "" _catch_sr(
char const* rawChars, std::size_t size ) noexcept ->
Catch::StringRef {
700 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
701 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
702 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
703 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
704 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
705 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
707 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
708 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
710 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
711 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
713 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
716 #define CATCH_REC_END(...)
717 #define CATCH_REC_OUT
719 #define CATCH_EMPTY()
720 #define CATCH_DEFER(id) id CATCH_EMPTY()
722 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
723 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
724 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
725 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
726 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
727 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
729 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
730 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
731 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
733 #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__ )
734 #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__ )
735 #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__ )
740 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
742 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
744 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
745 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
746 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
747 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
748 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
749 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
750 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
751 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
754 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
755 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
756 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
759 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
760 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
762 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
764 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
765 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
766 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
768 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
769 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
772 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
773 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
775 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
776 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
777 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
778 #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)
779 #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)
780 #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)
781 #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)
782 #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)
783 #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)
784 #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)
785 #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)
787 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
789 #define INTERNAL_CATCH_TYPE_GEN\
790 template<typename...> struct TypeList {};\
791 template<typename...Ts>\
792 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
793 template<template<typename...> class...> struct TemplateTypeList{};\
794 template<template<typename...> class...Cs>\
795 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
796 template<typename...>\
798 template<typename...>\
800 template<template<typename...> class, typename...>\
802 template<template<typename...> class, typename>\
805 template<typename T> \
806 struct append<T> { using type = T; };\
807 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
808 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
809 template< template<typename...> class L1, typename...E1, typename...Rest>\
810 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
812 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
813 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
814 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
815 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
817 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
818 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
819 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
820 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
822 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
823 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
824 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
825 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
826 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
827 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
828 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
830 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
831 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
832 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
833 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
834 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
835 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
837 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
838 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
839 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
840 static void TestName()
841 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
842 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
843 static void TestName()
845 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
846 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
847 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
848 static void TestName()
849 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
850 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
851 static void TestName()
853 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
854 template<typename Type>\
855 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
857 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
860 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
861 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
862 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
864 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
867 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
868 template<typename Type>\
869 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
871 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
874 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
875 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
876 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
878 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
881 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
882 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
883 template<typename TestType> \
884 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
888 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
889 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
890 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
894 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
895 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
896 template<typename TestType> \
897 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
898 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
899 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
900 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
902 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
903 #define INTERNAL_CATCH_NTTP_0
904 #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)
905 #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__)
906 #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__)
907 #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__)
908 #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__)
909 #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__)
910 #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__)
911 #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__)
913 #define INTERNAL_CATCH_NTTP_0(signature)
914 #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__))
915 #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__))
916 #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__))
917 #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__))
918 #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__))
919 #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__))
920 #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__))
921 #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__))
928 #include <type_traits>
936 template <
typename Fun,
typename... Args>
938 template <
typename...>
939 std::false_type
static test(...);
942 template <
typename T>
945 template <
typename Fun,
typename... Args>
946 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
948 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
951 template <
typename Func,
typename... U>
952 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
955 template <
typename Func,
typename... U>
956 using FunctionReturnType =
typename std::remove_reference<
typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
970 void (C::*m_testAsMethod)();
972 TestInvokerAsMethod(
void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
974 void invoke()
const override {
976 (obj.*m_testAsMethod)();
980 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept ->
ITestInvoker*;
983 auto makeTestInvoker(
void (C::*testAsMethod)() ) noexcept ->
ITestInvoker* {
1000 #if defined(CATCH_CONFIG_DISABLE)
1001 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
1002 static void TestName()
1003 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
1005 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1009 void TestName::test()
1010 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1011 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1012 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1014 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1015 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1018 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1020 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1021 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1022 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__ )
1024 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1025 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__ ) )
1028 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1029 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1030 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__ )
1032 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1033 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__ ) )
1036 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1037 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1038 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__ )
1040 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1041 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__ ) )
1044 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1045 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1046 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__ )
1048 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1049 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__ ) )
1054 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1055 static void TestName(); \
1056 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1057 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1058 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \
1059 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1060 static void TestName()
1061 #define INTERNAL_CATCH_TESTCASE( ... ) \
1062 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1065 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1066 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1067 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1068 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); }
\
1069 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1072 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1073 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1074 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1076 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1079 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \
1081 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1082 void TestName::test()
1083 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1084 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1087 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1088 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1089 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1090 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \
1091 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1094 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1095 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1096 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1097 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1098 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1099 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1101 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1102 INTERNAL_CATCH_TYPE_GEN\
1103 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1104 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1105 template<typename...Types> \
1109 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1110 using expander = int[];\
1111 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };
\
1114 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1115 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1120 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1121 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1123 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1124 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1125 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__ )
1127 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1128 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__ ) )
1131 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1132 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1133 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__ )
1135 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1136 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__ ) )
1139 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1140 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1141 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1142 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1143 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1144 template<typename TestType> static void TestFuncName(); \
1146 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1147 INTERNAL_CATCH_TYPE_GEN \
1148 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1149 template<typename... Types> \
1151 void reg_tests() { \
1153 using expander = int[]; \
1154 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1155 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1156 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1157 (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++)... };
\
1160 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1161 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; \
1168 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1169 template<typename TestType> \
1170 static void TestFuncName()
1172 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1173 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1174 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__)
1176 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1177 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__ ) )
1180 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1181 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1182 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__)
1184 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1185 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__ ) )
1188 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1189 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1190 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1191 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1192 template<typename TestType> static void TestFunc(); \
1194 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1195 INTERNAL_CATCH_TYPE_GEN\
1196 template<typename... Types> \
1198 void reg_tests() { \
1200 using expander = int[]; \
1201 (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++)... };
\
1204 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1205 using TestInit = typename convert<TestName, TmplList>::type; \
1211 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1212 template<typename TestType> \
1213 static void TestFunc()
1215 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1216 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 )
1218 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1219 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1220 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1221 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1222 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1224 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1225 INTERNAL_CATCH_TYPE_GEN\
1226 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1227 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1228 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1229 template<typename...Types> \
1230 struct TestNameClass{\
1233 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1234 using expander = int[];\
1235 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };
\
1238 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1239 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1244 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1245 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1247 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1248 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1249 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__ )
1251 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1252 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__ ) )
1255 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1256 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1257 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__ )
1259 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1260 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__ ) )
1263 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1264 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1265 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1266 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1267 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1268 template<typename TestType> \
1269 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1273 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1274 INTERNAL_CATCH_TYPE_GEN \
1275 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1276 template<typename...Types>\
1277 struct TestNameClass{\
1280 using expander = int[];\
1281 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1282 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1283 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1284 (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++)... };
\
1287 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1288 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;\
1295 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1296 template<typename TestType> \
1297 void TestName<TestType>::test()
1299 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1300 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1301 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__ )
1303 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1304 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__ ) )
1307 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1308 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1309 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__ )
1311 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1312 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__ ) )
1315 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1316 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1317 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1318 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1319 template<typename TestType> \
1320 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1324 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1325 INTERNAL_CATCH_TYPE_GEN\
1326 template<typename...Types>\
1327 struct TestNameClass{\
1330 using expander = int[];\
1331 (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++)... };
\
1334 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1335 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1341 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1342 template<typename TestType> \
1343 void TestName<TestType>::test()
1345 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1346 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 )
1368 ExpressionFailed = FailureBit | 1,
1369 ExplicitFailure = FailureBit | 2,
1371 Exception = 0x100 | FailureBit,
1373 ThrewException = Exception | 1,
1374 DidntThrowException = Exception | 2,
1376 FatalErrorCondition = 0x200 | FailureBit
1380 bool isOk( ResultWas::OfType resultType );
1381 bool isJustInfo(
int flags );
1387 ContinueOnFailure = 0x02,
1392 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1394 bool shouldContinueOnFailure(
int flags );
1395 inline bool isFalseTest(
int flags ) {
return ( flags & ResultDisposition::FalseTest ) != 0; }
1396 bool shouldSuppressFailure(
int flags );
1408 ResultDisposition::Flags resultDisposition;
1424 #include <type_traits>
1434 std::ostream& cout();
1435 std::ostream& cerr();
1436 std::ostream& clog();
1442 virtual std::ostream& stream()
const = 0;
1448 std::size_t m_index;
1449 std::ostream* m_oss;
1454 auto str()
const -> std::string;
1456 template<
typename T>
1461 auto get() -> std::ostream& {
return *m_oss; }
1475 std::vector<std::pair<int, StringRef>> m_values;
1488 template<
typename E>
1490 static_assert(
sizeof(
int) >=
sizeof(E),
"Cannot serialize enum to int");
1491 std::vector<int> intValues;
1492 intValues.reserve( values.size() );
1493 for(
auto enumValue : values )
1494 intValues.push_back(
static_cast<int>( enumValue ) );
1495 return registerEnum( enumName, allEnums, intValues );
1503 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1504 #include <string_view>
1510 #import <Foundation/Foundation.h>
1512 #ifdef __has_feature
1513 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1515 #define CATCH_ARC_ENABLED 0
1518 void arcSafeRelease( NSObject* obj );
1519 id performOptionalSelector(
id obj,
SEL sel );
1521 #if !CATCH_ARC_ENABLED
1522 inline void arcSafeRelease( NSObject* obj ) {
1525 inline id performOptionalSelector(
id obj,
SEL sel ) {
1526 if( [obj respondsToSelector: sel] )
1527 return [obj performSelector: sel];
1530 #define CATCH_UNSAFE_UNRETAINED
1531 #define CATCH_ARC_STRONG
1533 inline void arcSafeRelease( NSObject* ){}
1534 inline id performOptionalSelector(
id obj,
SEL sel ) {
1536 #pragma clang diagnostic push
1537 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1539 if( [obj respondsToSelector: sel] )
1540 return [obj performSelector: sel];
1542 #pragma clang diagnostic pop
1546 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1547 #define CATCH_ARC_STRONG __strong
1554 #pragma warning(push)
1555 #pragma warning(disable:4180)
1561 extern const std::string unprintableString;
1563 std::string rawMemoryToString(
const void *
object, std::size_t size );
1565 template<
typename T>
1566 std::string rawMemoryToString(
const T&
object ) {
1567 return rawMemoryToString( &
object,
sizeof(
object) );
1570 template<
typename T>
1572 template<
typename Stream,
typename U>
1573 static auto test(
int)
1574 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1576 template<
typename,
typename>
1577 static auto test(...)->std::false_type;
1580 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1583 template<
typename E>
1584 std::string convertUnknownEnumToString( E e );
1586 template<
typename T>
1587 typename std::enable_if<
1588 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1589 std::string>::type convertUnstreamable( T
const& ) {
1590 return Detail::unprintableString;
1592 template<
typename T>
1593 typename std::enable_if<
1594 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1595 std::string>::type convertUnstreamable(T
const& ex) {
1599 template<
typename T>
1600 typename std::enable_if<
1601 std::is_enum<T>::value
1602 , std::string>::type convertUnstreamable( T
const& value ) {
1603 return convertUnknownEnumToString( value );
1606 #if defined(_MANAGED)
1608 template<
typename T>
1609 std::string clrReferenceToString( T^ ref ) {
1611 return std::string(
"null");
1612 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1613 cli::pin_ptr<System::Byte> p = &bytes[0];
1614 return std::string(
reinterpret_cast<char const *
>(p), bytes->Length);
1621 template <
typename T,
typename =
void>
1623 template <
typename Fake = T>
1625 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1626 convert(
const Fake& value) {
1630 rss.operator<<(value);
1634 template <
typename Fake = T>
1636 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1637 convert(
const Fake& value ) {
1638 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1639 return Detail::convertUnstreamable(value);
1641 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1650 template <
typename T>
1651 std::string stringify(
const T& e) {
1652 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1655 template<
typename E>
1656 std::string convertUnknownEnumToString( E e ) {
1657 return ::Catch::Detail::stringify(
static_cast<typename std::underlying_type<E>::type
>(e));
1660 #if defined(_MANAGED)
1661 template <
typename T>
1662 std::string stringify( T^ e ) {
1663 return ::Catch::StringMaker<T^>::convert(e);
1673 static std::string convert(
const std::string& str);
1676 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1679 static std::string convert(std::string_view str);
1685 static std::string convert(
char const * str);
1689 static std::string convert(
char * str);
1692 #ifdef CATCH_CONFIG_WCHAR
1695 static std::string convert(
const std::wstring& wstr);
1698 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1701 static std::string convert(std::wstring_view str);
1707 static std::string convert(
wchar_t const * str);
1711 static std::string convert(
wchar_t * str);
1719 static std::string convert(
char const* str) {
1720 return ::Catch::Detail::stringify(std::string{ str });
1725 static std::string convert(
signed char const* str) {
1726 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const *
>(str) });
1731 static std::string convert(
unsigned char const* str) {
1732 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const *
>(str) });
1736 #if defined(CATCH_CONFIG_CPP17_BYTE)
1739 static std::string convert(std::byte value);
1744 static std::string convert(
int value);
1748 static std::string convert(
long value);
1752 static std::string convert(
long long value);
1756 static std::string convert(
unsigned int value);
1760 static std::string convert(
unsigned long value);
1764 static std::string convert(
unsigned long long value);
1769 static std::string convert(
bool b);
1774 static std::string convert(
char c);
1778 static std::string convert(
signed char c);
1782 static std::string convert(
unsigned char c);
1787 static std::string convert(std::nullptr_t);
1792 static std::string convert(
float value);
1793 static int precision;
1798 static std::string convert(
double value);
1799 static int precision;
1802 template <
typename T>
1804 template <
typename U>
1805 static std::string convert(U* p) {
1807 return ::Catch::Detail::rawMemoryToString(p);
1814 template <
typename R,
typename C>
1816 static std::string convert(R C::* p) {
1818 return ::Catch::Detail::rawMemoryToString(p);
1825 #if defined(_MANAGED)
1826 template <
typename T>
1828 static std::string convert( T^ ref ) {
1829 return ::Catch::Detail::clrReferenceToString(ref);
1835 template<
typename InputIterator,
typename Sentinel = InputIterator>
1836 std::string rangeToString(InputIterator first, Sentinel last) {
1839 if (first != last) {
1840 rss << ::Catch::Detail::stringify(*first);
1841 for (++first; first != last; ++first)
1842 rss <<
", " << ::Catch::Detail::stringify(*first);
1852 static std::string convert(NSString * nsstring) {
1855 return std::string(
"@") + [nsstring UTF8String];
1860 static std::string convert(NSObject* nsObject) {
1861 return ::Catch::Detail::stringify([nsObject description]);
1866 inline std::string stringify( NSString* nsstring ) {
1879 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1880 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1881 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1882 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1883 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1884 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1888 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1891 template<
typename T1,
typename T2>
1893 static std::string convert(
const std::pair<T1, T2>& pair) {
1896 << ::Catch::Detail::stringify(pair.first)
1898 << ::Catch::Detail::stringify(pair.second)
1906 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1909 template<
typename T>
1911 static std::string convert(
const std::optional<T>& optional) {
1913 if (optional.has_value()) {
1914 rss << ::Catch::Detail::stringify(*optional);
1925 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1932 bool = (N < std::tuple_size<Tuple>::value)
1935 static void print(
const Tuple& tuple, std::ostream& os) {
1936 os << (N ?
", " :
" ")
1937 << ::Catch::Detail::stringify(std::get<N>(tuple));
1947 static void print(
const Tuple&, std::ostream&) {}
1952 template<
typename ...Types>
1954 static std::string convert(
const std::tuple<Types...>& tuple) {
1965 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1970 static std::string convert(
const std::monostate&) {
1975 template<
typename... Elements>
1977 static std::string convert(
const std::variant<Elements...>& variant) {
1978 if (variant.valueless_by_exception()) {
1979 return "{valueless variant}";
1982 [](
const auto& value) {
1983 return ::Catch::Detail::stringify(value);
1999 template <
typename...>
2004 template <
typename T,
typename =
void>
2008 template <
typename T>
2013 template <
typename T>
2017 #if defined(_MANAGED)
2018 template <
typename T>
2020 static const bool value =
false;
2024 template<
typename Range>
2025 std::string rangeToString( Range
const& range ) {
2026 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2030 template<
typename Allocator>
2031 std::string rangeToString( std::vector<bool, Allocator>
const& v ) {
2032 ReusableStringStream rss;
2040 rss << ::Catch::Detail::stringify( b );
2046 template<
typename R>
2047 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2048 static std::string convert( R
const& range ) {
2049 return rangeToString( range );
2053 template <
typename T,
int SZ>
2055 static std::string convert(T
const(&arr)[SZ]) {
2056 return rangeToString(arr);
2063 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2070 template <
class Ratio>
2072 static std::string symbol();
2075 template <
class Ratio>
2078 rss <<
'[' << Ratio::num <<
'/'
2079 << Ratio::den <<
']';
2084 static std::string symbol();
2088 static std::string symbol();
2092 static std::string symbol();
2096 static std::string symbol();
2100 static std::string symbol();
2104 static std::string symbol();
2109 template<
typename Value,
typename Ratio>
2111 static std::string convert(std::chrono::duration<Value, Ratio>
const& duration) {
2117 template<
typename Value>
2119 static std::string convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2121 rss << duration.count() <<
" s";
2125 template<
typename Value>
2127 static std::string convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2129 rss << duration.count() <<
" m";
2133 template<
typename Value>
2135 static std::string convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2137 rss << duration.count() <<
" h";
2145 template<
typename Clock,
typename Duration>
2147 static std::string convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2148 return ::Catch::Detail::stringify(time_point.time_since_epoch()) +
" since epoch";
2152 template<
typename Duration>
2153 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2154 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2155 auto converted = std::chrono::system_clock::to_time_t(time_point);
2158 std::tm timeInfo = {};
2159 gmtime_s(&timeInfo, &converted);
2161 std::tm* timeInfo = std::gmtime(&converted);
2164 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2165 char timeStamp[timeStampSize];
2166 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2169 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2171 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2173 return std::string(timeStamp);
2179 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2181 template<> struct StringMaker<enumName> { \
2182 static std::string convert( enumName value ) { \
2183 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2184 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2189 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2192 #pragma warning(pop)
2199 #pragma warning(push)
2200 #pragma warning(disable:4389)
2201 #pragma warning(disable:4018)
2202 #pragma warning(disable:4312)
2203 #pragma warning(disable:4180)
2204 #pragma warning(disable:4800)
2210 auto isBinaryExpression()
const ->
bool {
return m_isBinaryExpression; }
2211 auto getResult()
const ->
bool {
return m_result; }
2212 virtual void streamReconstructedExpression( std::ostream &os )
const = 0;
2215 : m_isBinaryExpression( isBinaryExpression ),
2223 bool m_isBinaryExpression;
2228 void formatReconstructedExpression( std::ostream &os, std::string
const& lhs,
StringRef op, std::string
const& rhs );
2230 template<
typename LhsT,
typename RhsT>
2236 void streamReconstructedExpression( std::ostream &os )
const override {
2237 formatReconstructedExpression
2238 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2249 template<
typename T>
2252 "chained comparisons are not supported inside assertions, "
2253 "wrap the expression inside parentheses, or decompose it");
2256 template<
typename T>
2259 "chained comparisons are not supported inside assertions, "
2260 "wrap the expression inside parentheses, or decompose it");
2263 template<
typename T>
2266 "chained comparisons are not supported inside assertions, "
2267 "wrap the expression inside parentheses, or decompose it");
2270 template<
typename T>
2273 "chained comparisons are not supported inside assertions, "
2274 "wrap the expression inside parentheses, or decompose it");
2277 template<
typename T>
2280 "chained comparisons are not supported inside assertions, "
2281 "wrap the expression inside parentheses, or decompose it");
2284 template<
typename T>
2287 "chained comparisons are not supported inside assertions, "
2288 "wrap the expression inside parentheses, or decompose it");
2291 template<
typename T>
2294 "chained comparisons are not supported inside assertions, "
2295 "wrap the expression inside parentheses, or decompose it");
2298 template<
typename T>
2301 "chained comparisons are not supported inside assertions, "
2302 "wrap the expression inside parentheses, or decompose it");
2306 template<
typename LhsT>
2310 void streamReconstructedExpression( std::ostream &os )
const override {
2311 os << Catch::Detail::stringify( m_lhs );
2322 template<
typename LhsT,
typename RhsT>
2323 auto compareEqual( LhsT
const& lhs, RhsT
const& rhs ) ->
bool {
return static_cast<bool>(lhs == rhs); }
2324 template<
typename T>
2325 auto compareEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2326 template<
typename T>
2327 auto compareEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2328 template<
typename T>
2329 auto compareEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2330 template<
typename T>
2331 auto compareEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2333 template<
typename LhsT,
typename RhsT>
2334 auto compareNotEqual( LhsT
const& lhs, RhsT&& rhs ) ->
bool {
return static_cast<bool>(lhs != rhs); }
2335 template<
typename T>
2336 auto compareNotEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2337 template<
typename T>
2338 auto compareNotEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2339 template<
typename T>
2340 auto compareNotEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2341 template<
typename T>
2342 auto compareNotEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2344 template<
typename LhsT>
2348 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2350 template<
typename RhsT>
2352 return { compareEqual( m_lhs, rhs ), m_lhs,
"==", rhs };
2355 return { m_lhs == rhs, m_lhs,
"==", rhs };
2358 template<
typename RhsT>
2360 return { compareNotEqual( m_lhs, rhs ), m_lhs,
"!=", rhs };
2363 return { m_lhs != rhs, m_lhs,
"!=", rhs };
2366 template<
typename RhsT>
2368 return {
static_cast<bool>(m_lhs > rhs), m_lhs,
">", rhs };
2370 template<
typename RhsT>
2372 return {
static_cast<bool>(m_lhs < rhs), m_lhs,
"<", rhs };
2374 template<
typename RhsT>
2376 return {
static_cast<bool>(m_lhs >= rhs), m_lhs,
">=", rhs };
2378 template<
typename RhsT>
2380 return {
static_cast<bool>(m_lhs <= rhs), m_lhs,
"<=", rhs };
2382 template <
typename RhsT>
2384 return {
static_cast<bool>(m_lhs | rhs), m_lhs,
"|", rhs };
2386 template <
typename RhsT>
2388 return {
static_cast<bool>(m_lhs & rhs), m_lhs,
"&", rhs };
2390 template <
typename RhsT>
2392 return {
static_cast<bool>(m_lhs ^ rhs), m_lhs,
"^", rhs };
2395 template<
typename RhsT>
2398 "operator&& is not supported inside assertions, "
2399 "wrap the expression inside parentheses, or decompose it");
2402 template<
typename RhsT>
2405 "operator|| is not supported inside assertions, "
2406 "wrap the expression inside parentheses, or decompose it");
2416 template<
typename T>
2417 void handleExpression(
ExprLhs<T> const& expr ) {
2418 handleExpression( expr.makeUnaryExpr() );
2422 template<
typename T>
2435 #pragma warning(pop)
2446 class AssertionResult;
2447 struct AssertionInfo;
2449 struct SectionEndInfo;
2451 struct MessageBuilder;
2453 struct AssertionReaction;
2454 struct SourceLineInfo;
2456 struct ITransientExpression;
2457 struct IGeneratorTracker;
2459 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2460 struct BenchmarkInfo;
2461 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2462 struct BenchmarkStats;
2469 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
2470 Counts& assertions ) = 0;
2472 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo ) = 0;
2476 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2477 virtual void benchmarkPreparing( std::string
const& name ) = 0;
2478 virtual void benchmarkStarting(
BenchmarkInfo const& info ) = 0;
2480 virtual void benchmarkFailed( std::string
const& error ) = 0;
2483 virtual void pushScopedMessage(
MessageInfo const& message ) = 0;
2484 virtual void popScopedMessage(
MessageInfo const& message ) = 0;
2486 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder ) = 0;
2488 virtual void handleFatalErrorCondition(
StringRef message ) = 0;
2490 virtual void handleExpr
2494 virtual void handleMessage
2496 ResultWas::OfType resultType,
2499 virtual void handleUnexpectedExceptionNotThrown
2502 virtual void handleUnexpectedInflightException
2504 std::string
const& message,
2506 virtual void handleIncomplete
2508 virtual void handleNonExpr
2510 ResultWas::OfType resultType,
2513 virtual bool lastAssertionPassed() = 0;
2514 virtual void assertionPassed() = 0;
2517 virtual std::string getCurrentTestName()
const = 0;
2519 virtual void exceptionEarlyReported() = 0;
2545 explicit operator bool()
const;
2547 friend auto operator << ( std::ostream& os,
LazyExpression const& lazyExpr ) -> std::ostream&;
2551 bool shouldDebugBreak =
false;
2552 bool shouldThrow =
false;
2558 bool m_completed =
false;
2566 ResultDisposition::Flags resultDisposition );
2568 if ( !m_completed ) {
2569 m_resultCapture.handleIncomplete( m_assertionInfo );
2573 template<
typename T>
2575 handleExpr( expr.makeUnaryExpr() );
2579 void handleMessage(ResultWas::OfType resultType,
StringRef const& message);
2581 void handleExceptionThrownAsExpected();
2582 void handleUnexpectedExceptionNotThrown();
2583 void handleExceptionNotThrownAsExpected();
2584 void handleThrowingCallSkipped();
2585 void handleUnexpectedInflightException();
2588 void setCompleted();
2591 auto allowThrows()
const -> bool;
2609 ResultWas::OfType _type );
2612 std::string message;
2614 ResultWas::OfType type;
2615 unsigned int sequence;
2617 bool operator == (
MessageInfo const& other )
const;
2618 bool operator < (
MessageInfo const& other )
const;
2620 static unsigned int globalCount;
2625 template<
typename T>
2637 ResultWas::OfType type );
2639 template<
typename T>
2660 std::vector<MessageInfo> m_messages;
2662 size_t m_captured = 0;
2667 void captureValue(
size_t index, std::string
const& value );
2669 template<
typename T>
2670 void captureValues(
size_t index, T
const& value ) {
2671 captureValue( index, Catch::Detail::stringify( value ) );
2674 template<
typename T,
typename... Ts>
2675 void captureValues(
size_t index, T
const& value, Ts
const&... values ) {
2676 captureValue( index, Catch::Detail::stringify(value) );
2677 captureValues( index+1, values... );
2684 #if !defined(CATCH_CONFIG_DISABLE)
2686 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2687 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2689 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2692 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2697 #define INTERNAL_CATCH_TRY
2698 #define INTERNAL_CATCH_CATCH( capturer )
2702 #define INTERNAL_CATCH_TRY try
2703 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2707 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2710 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2712 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2713 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2714 INTERNAL_CATCH_TRY { \
2715 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2716 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2717 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2718 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2719 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2720 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2721 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2724 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2725 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2726 if( Catch::getResultCapture().lastAssertionPassed() )
2729 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2730 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2731 if( !Catch::getResultCapture().lastAssertionPassed() )
2734 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2736 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2738 static_cast<void>(__VA_ARGS__); \
2739 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2742 catchAssertionHandler.handleUnexpectedInflightException(); \
2744 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2748 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2750 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2751 if( catchAssertionHandler.allowThrows() ) \
2753 static_cast<void>(__VA_ARGS__); \
2754 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2757 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2760 catchAssertionHandler.handleThrowingCallSkipped(); \
2761 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2765 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2767 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2768 if( catchAssertionHandler.allowThrows() ) \
2770 static_cast<void>(expr); \
2771 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2773 catch( exceptionType const& ) { \
2774 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2777 catchAssertionHandler.handleUnexpectedInflightException(); \
2780 catchAssertionHandler.handleThrowingCallSkipped(); \
2781 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2785 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2787 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2788 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2789 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2793 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2794 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2795 varName.captureValues( 0, __VA_ARGS__ )
2798 #define INTERNAL_CATCH_INFO( macroName, log ) \
2799 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2802 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2803 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2807 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2809 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2810 if( catchAssertionHandler.allowThrows() ) \
2812 static_cast<void>(__VA_ARGS__); \
2813 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2816 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2819 catchAssertionHandler.handleThrowingCallSkipped(); \
2820 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2840 std::size_t total()
const;
2841 bool allPassed()
const;
2844 std::size_t passed = 0;
2845 std::size_t failed = 0;
2846 std::size_t failedButOk = 0;
2870 std::string
const& _name );
2875 std::string
const& _name,
2876 std::string
const& ) :
SectionInfo( _lineInfo, _name ) {}
2879 std::string description;
2886 double durationInSeconds;
2898 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2899 auto getEstimatedClockResolution() -> uint64_t;
2902 uint64_t m_nanoseconds = 0;
2905 auto getElapsedNanoseconds()
const -> uint64_t;
2906 auto getElapsedMicroseconds()
const -> uint64_t;
2907 auto getElapsedMilliseconds()
const ->
unsigned int;
2908 auto getElapsedSeconds()
const -> double;
2924 explicit operator bool()
const;
2931 bool m_sectionIncluded;
2937 #define INTERNAL_CATCH_SECTION( ... ) \
2938 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2939 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2940 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2941 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2943 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2944 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2945 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2946 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2947 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2960 struct ITestCaseRegistry;
2961 struct IExceptionTranslatorRegistry;
2962 struct IExceptionTranslator;
2963 struct IReporterRegistry;
2964 struct IReporterFactory;
2965 struct ITagAliasRegistry;
2966 struct IMutableEnumValuesRegistry;
2968 class StartupExceptionRegistry;
2970 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2985 virtual void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory ) = 0;
2986 virtual void registerListener( IReporterFactoryPtr
const& factory ) = 0;
2987 virtual void registerTest(
TestCase const& testInfo ) = 0;
2989 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) = 0;
2990 virtual void registerStartupException() noexcept = 0;
2997 std::string translateActiveException();
3002 #if defined(CATCH_CONFIG_DISABLE)
3003 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
3004 static std::string translatorName( signature )
3007 #include <exception>
3012 using exceptionTranslateFunction = std::string(*)();
3014 struct IExceptionTranslator;
3015 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3019 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3025 virtual std::string translateActiveException()
const = 0;
3029 template<
typename T>
3033 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3034 : m_translateFunction( translateFunction )
3037 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const override {
3038 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3043 std::rethrow_exception(std::current_exception());
3045 return (*it)->translate( it+1, itEnd );
3048 return m_translateFunction( ex );
3054 std::string(*m_translateFunction)( T& );
3058 template<
typename T>
3060 getMutableRegistryHub().registerTranslator
3061 (
new ExceptionTranslator<T>( translateFunction ) );
3067 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3068 static std::string translatorName( signature ); \
3069 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3070 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3071 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3072 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3073 static std::string translatorName( signature )
3075 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3080 #include <type_traits>
3087 bool equalityComparisonImpl(
double other)
const;
3090 void setMargin(
double margin);
3093 void setEpsilon(
double epsilon);
3096 explicit Approx (
double value );
3100 Approx operator-()
const;
3102 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3103 Approx operator()( T
const& value ) {
3104 Approx approx(
static_cast<double>(value) );
3105 approx.m_epsilon = m_epsilon;
3106 approx.m_margin = m_margin;
3107 approx.m_scale = m_scale;
3111 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3112 explicit Approx( T
const& value ):
Approx(
static_cast<double>(value))
3115 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3116 friend bool operator == (
const T& lhs,
Approx const& rhs ) {
3117 auto lhs_v =
static_cast<double>(lhs);
3118 return rhs.equalityComparisonImpl(lhs_v);
3121 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3122 friend bool operator == (
Approx const& lhs,
const T& rhs ) {
3123 return operator==( rhs, lhs );
3126 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3127 friend bool operator != ( T
const& lhs,
Approx const& rhs ) {
3128 return !operator==( lhs, rhs );
3131 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3132 friend bool operator != (
Approx const& lhs, T
const& rhs ) {
3133 return !operator==( rhs, lhs );
3136 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3137 friend bool operator <= ( T
const& lhs,
Approx const& rhs ) {
3138 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3141 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3142 friend bool operator <= (
Approx const& lhs, T
const& rhs ) {
3143 return lhs.m_value <
static_cast<double>(rhs) || lhs == rhs;
3146 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3147 friend bool operator >= ( T
const& lhs,
Approx const& rhs ) {
3148 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3151 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3152 friend bool operator >= (
Approx const& lhs, T
const& rhs ) {
3153 return lhs.m_value >
static_cast<double>(rhs) || lhs == rhs;
3156 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3157 Approx& epsilon( T
const& newEpsilon ) {
3158 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3159 setEpsilon(epsilonAsDouble);
3163 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3164 Approx& margin( T
const& newMargin ) {
3165 double marginAsDouble =
static_cast<double>(newMargin);
3166 setMargin(marginAsDouble);
3170 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3171 Approx& scale( T
const& newScale ) {
3172 m_scale =
static_cast<double>(newScale);
3176 std::string toString()
const;
3186 namespace literals {
3207 bool startsWith( std::string
const& s, std::string
const& prefix );
3208 bool startsWith( std::string
const& s,
char prefix );
3209 bool endsWith( std::string
const& s, std::string
const& suffix );
3210 bool endsWith( std::string
const& s,
char suffix );
3211 bool contains( std::string
const& s, std::string
const& infix );
3212 void toLowerInPlace( std::string& s );
3213 std::string toLower( std::string
const& s );
3215 std::string trim( std::string
const& str );
3217 StringRef trim(StringRef ref);
3220 std::vector<StringRef> splitStringRef( StringRef str,
char delimiter );
3221 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
3224 pluralise( std::size_t count, std::string
const& label );
3226 friend std::ostream& operator << ( std::ostream& os,
pluralise const& pluraliser );
3228 std::size_t m_count;
3229 std::string m_label;
3234 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3243 namespace Matchers {
3246 template<
typename ArgT>
struct MatchAllOf;
3247 template<
typename ArgT>
struct MatchAnyOf;
3248 template<
typename ArgT>
struct MatchNotOf;
3255 std::string toString()
const;
3259 virtual std::string describe()
const = 0;
3260 mutable std::string m_cachedToString;
3264 # pragma clang diagnostic push
3265 # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3268 template<
typename ObjectT>
3270 virtual bool match( ObjectT
const& arg )
const = 0;
3273 #if defined(__OBJC__)
3278 virtual bool match( NSString* arg )
const = 0;
3283 # pragma clang diagnostic pop
3286 template<
typename T>
3294 template<
typename ArgT>
3296 bool match( ArgT
const& arg )
const override {
3297 for(
auto matcher : m_matchers ) {
3298 if (!matcher->match(arg))
3303 std::string describe()
const override {
3304 std::string description;
3305 description.reserve( 4 + m_matchers.size()*32 );
3306 description +=
"( ";
3308 for(
auto matcher : m_matchers ) {
3312 description +=
" and ";
3313 description += matcher->toString();
3315 description +=
" )";
3321 copy.m_matchers.push_back( &other );
3325 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3327 template<
typename ArgT>
3330 bool match( ArgT
const& arg )
const override {
3331 for(
auto matcher : m_matchers ) {
3332 if (matcher->match(arg))
3337 std::string describe()
const override {
3338 std::string description;
3339 description.reserve( 4 + m_matchers.size()*32 );
3340 description +=
"( ";
3342 for(
auto matcher : m_matchers ) {
3346 description +=
" or ";
3347 description += matcher->toString();
3349 description +=
" )";
3355 copy.m_matchers.push_back( &other );
3359 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3362 template<
typename ArgT>
3367 bool match( ArgT
const& arg )
const override {
3368 return !m_underlyingMatcher.match( arg );
3371 std::string describe()
const override {
3372 return "not " + m_underlyingMatcher.toString();
3377 template<
typename T>
3381 template<
typename T>
3383 return MatchAnyOf<T>() || *
this || other;
3385 template<
typename T>
3387 return MatchNotOf<T>( *
this );
3394 using namespace Matchers;
3395 using Matchers::Impl::MatcherBase;
3403 namespace Matchers {
3404 namespace Exception {
3407 std::string m_message;
3414 bool match(std::exception
const& ex)
const override;
3416 std::string describe()
const override;
3430 namespace Matchers {
3432 namespace Floating {
3434 enum class FloatingPointKind : uint8_t;
3438 bool match(
double const& matchee)
const override;
3439 std::string describe()
const override;
3447 bool match(
double const& matchee)
const override;
3448 std::string describe()
const override;
3452 FloatingPointKind m_type;
3463 bool match(
double const& matchee)
const override;
3464 std::string describe()
const override;
3490 #include <functional>
3494 namespace Matchers {
3498 std::string finalizeDescription(
const std::string& desc);
3501 template <
typename T>
3503 std::function<bool(T
const&)> m_predicate;
3504 std::string m_description;
3507 PredicateMatcher(std::function<
bool(T
const&)>
const& elem, std::string
const& descr)
3508 :m_predicate(std::move(elem)),
3509 m_description(Detail::finalizeDescription(descr))
3512 bool match( T
const& item )
const override {
3513 return m_predicate(item);
3516 std::string describe()
const override {
3517 return m_description;
3527 template<
typename T>
3541 namespace Matchers {
3543 namespace StdString {
3547 CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity );
3548 std::string adjustString( std::string
const& str )
const;
3549 std::string caseSensitivitySuffix()
const;
3551 CaseSensitive::Choice m_caseSensitivity;
3557 std::string describe()
const override;
3560 std::string m_operation;
3565 bool match( std::string
const& source )
const override;
3569 bool match( std::string
const& source )
const override;
3573 bool match( std::string
const& source )
const override;
3577 bool match( std::string
const& source )
const override;
3581 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3582 bool match( std::string
const& matchee )
const override;
3583 std::string describe()
const override;
3586 std::string m_regex;
3587 CaseSensitive::Choice m_caseSensitivity;
3595 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3599 StdString::RegexMatcher Matches( std::string
const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3607 #include <algorithm>
3610 namespace Matchers {
3613 template<
typename T,
typename Alloc>
3618 bool match(std::vector<T, Alloc>
const &v)
const override {
3619 for (
auto const& el : v) {
3620 if (el == m_comparator) {
3627 std::string describe()
const override {
3628 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3631 T
const& m_comparator;
3634 template<
typename T,
typename AllocComp,
typename AllocMatch>
3637 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3639 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3641 if (m_comparator.size() > v.size())
3643 for (
auto const& comparator : m_comparator) {
3644 auto present =
false;
3645 for (
const auto& el : v) {
3646 if (el == comparator) {
3657 std::string describe()
const override {
3658 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3661 std::vector<T, AllocComp>
const& m_comparator;
3664 template<
typename T,
typename AllocComp,
typename AllocMatch>
3667 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3669 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3674 if (m_comparator.size() != v.size())
3676 for (std::size_t i = 0; i < v.size(); ++i)
3677 if (m_comparator[i] != v[i])
3681 std::string describe()
const override {
3682 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3684 std::vector<T, AllocComp>
const& m_comparator;
3687 template<
typename T,
typename AllocComp,
typename AllocMatch>
3690 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3692 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3693 if (m_comparator.size() != v.size())
3695 for (std::size_t i = 0; i < v.size(); ++i)
3696 if (m_comparator[i] != approx(v[i]))
3700 std::string describe()
const override {
3701 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3703 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3705 approx.epsilon(newEpsilon);
3708 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3710 approx.margin(newMargin);
3713 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3715 approx.scale(newScale);
3719 std::vector<T, AllocComp>
const& m_comparator;
3723 template<
typename T,
typename AllocComp,
typename AllocMatch>
3726 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3727 if (m_target.size() != vec.size()) {
3730 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3733 std::string describe()
const override {
3734 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3737 std::vector<T, AllocComp>
const& m_target;
3745 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3750 template<
typename T,
typename Alloc = std::allocator<T>>
3755 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3756 Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp>
const& comparator ) {
3757 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
3760 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3761 Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp>
const& comparator ) {
3762 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
3765 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3766 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp>
const& target) {
3767 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
3776 template<
typename ArgT,
typename MatcherT>
3782 MatchExpr( ArgT
const& arg, MatcherT
const& matcher,
StringRef const& matcherString )
3785 m_matcher( matcher ),
3786 m_matcherString( matcherString )
3789 void streamReconstructedExpression( std::ostream &os )
const override {
3790 auto matcherAsString = m_matcher.toString();
3791 os << Catch::Detail::stringify( m_arg ) <<
' ';
3792 if( matcherAsString == Detail::unprintableString )
3793 os << m_matcherString;
3795 os << matcherAsString;
3803 template<
typename ArgT,
typename MatcherT>
3811 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3813 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3814 INTERNAL_CATCH_TRY { \
3815 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3816 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3817 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3821 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3823 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3824 if( catchAssertionHandler.allowThrows() ) \
3826 static_cast<void>(__VA_ARGS__ ); \
3827 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3829 catch( exceptionType const& ex ) { \
3830 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3833 catchAssertionHandler.handleUnexpectedInflightException(); \
3836 catchAssertionHandler.handleThrowingCallSkipped(); \
3837 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3851 namespace Generators {
3860 virtual bool next() = 0;
3862 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3868 virtual auto hasGenerator()
const ->
bool = 0;
3869 virtual auto getGenerator()
const -> Generators::GeneratorBasePtr
const& = 0;
3870 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3878 #include <exception>
3881 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3882 template <
typename Ex>
3884 void throw_exception(Ex
const& e) {
3889 void throw_exception(std::exception
const& e);
3893 void throw_logic_error(std::string
const& msg);
3895 void throw_domain_error(std::string
const& msg);
3897 void throw_runtime_error(std::string
const& msg);
3901 #define CATCH_MAKE_MSG(...) \
3902 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3904 #define CATCH_INTERNAL_ERROR(...) \
3905 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3907 #define CATCH_ERROR(...) \
3908 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3910 #define CATCH_RUNTIME_ERROR(...) \
3911 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3913 #define CATCH_ENFORCE( condition, ... ) \
3914 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3922 #include <exception>
3927 const char*
const m_msg =
"";
3934 const char* what()
const noexcept
override final;
3937 namespace Generators {
3941 template<
typename T,
typename... Args>
3942 std::unique_ptr<T> make_unique( Args&&... args ) {
3943 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
3947 template<
typename T>
3955 virtual T
const& get()
const = 0;
3959 template<
typename T>
3965 T
const& get()
const override {
3968 bool next()
override {
3973 template<
typename T>
3975 static_assert(!std::is_same<T, bool>::value,
3976 "FixedValuesGenerator does not support bools because of std::vector<bool>"
3977 "specialization, use SingleValue Generator instead.");
3978 std::vector<T> m_values;
3983 T
const& get()
const override {
3984 return m_values[m_idx];
3986 bool next()
override {
3988 return m_idx < m_values.size();
3992 template <
typename T>
3994 std::unique_ptr<IGenerator<T>> m_generator;
3997 m_generator(std::move(generator))
3999 T
const& get()
const {
4000 return m_generator->get();
4003 return m_generator->next();
4007 template <
typename T>
4011 template <
typename T>
4012 GeneratorWrapper<T> values(std::initializer_list<T> values) {
4013 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4016 template<
typename T>
4018 std::vector<GeneratorWrapper<T>> m_generators;
4019 size_t m_current = 0;
4022 m_generators.emplace_back(std::move(generator));
4024 void populate(T&& val) {
4025 m_generators.emplace_back(value(std::forward<T>(val)));
4027 template<
typename U>
4028 void populate(U&& val) {
4029 populate(T(std::forward<U>(val)));
4031 template<
typename U,
typename... Gs>
4032 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4033 populate(std::forward<U>(valueOrGenerator));
4034 populate(std::forward<Gs>(moreGenerators)...);
4038 template <
typename... Gs>
4040 m_generators.reserve(
sizeof...(Gs));
4041 populate(std::forward<Gs>(moreGenerators)...);
4044 T
const& get()
const override {
4045 return m_generators[m_current].get();
4048 bool next()
override {
4049 if (m_current >= m_generators.size()) {
4052 const bool current_status = m_generators[m_current].next();
4053 if (!current_status) {
4056 return m_current < m_generators.size();
4060 template<
typename... Ts>
4061 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples ) {
4062 return values<std::tuple<Ts...>>( tuples );
4066 template <
typename T>
4069 template<
typename T,
typename... Gs>
4071 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4073 template<
typename T>
4074 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4075 return Generators<T>(std::move(generator));
4077 template<
typename T,
typename... Gs>
4078 auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4079 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4081 template<
typename T,
typename U,
typename... Gs>
4082 auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4083 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4086 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker&;
4088 template<
typename L>
4092 auto generate( StringRef generatorName, SourceLineInfo
const& lineInfo, L
const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4093 using UnderlyingType =
typename decltype(generatorExpression())::type;
4095 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4096 if (!tracker.hasGenerator()) {
4097 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4100 auto const& generator =
static_cast<IGenerator<UnderlyingType> const&
>( *tracker.getGenerator() );
4101 return generator.get();
4107 #define GENERATE( ... ) \
4108 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4109 CATCH_INTERNAL_LINEINFO, \
4110 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4111 #define GENERATE_COPY( ... ) \
4112 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4113 CATCH_INTERNAL_LINEINFO, \
4114 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4115 #define GENERATE_REF( ... ) \
4116 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4117 CATCH_INTERNAL_LINEINFO, \
4118 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4124 namespace Generators {
4126 template <
typename T>
4129 size_t m_returned = 0;
4133 m_generator(std::move(generator)),
4136 assert(target != 0 &&
"Empty generators are not allowed");
4138 T
const& get()
const override {
4139 return m_generator.get();
4141 bool next()
override {
4143 if (m_returned >= m_target) {
4147 const auto success = m_generator.next();
4151 m_returned = m_target;
4157 template <
typename T>
4162 template <
typename T,
typename Predicate>
4165 Predicate m_predicate;
4167 template <
typename P = Predicate>
4169 m_generator(std::move(generator)),
4170 m_predicate(std::forward<P>(pred))
4172 if (!m_predicate(m_generator.get())) {
4175 auto has_initial_value = next();
4176 if (!has_initial_value) {
4177 Catch::throw_exception(
GeneratorException(
"No valid value found in filtered generator"));
4182 T
const& get()
const override {
4183 return m_generator.get();
4186 bool next()
override {
4187 bool success = m_generator.next();
4191 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) ==
true);
4196 template <
typename T,
typename Predicate>
4201 template <
typename T>
4203 static_assert(!std::is_same<T, bool>::value,
4204 "RepeatGenerator currently does not support bools"
4205 "because of std::vector<bool> specialization");
4207 mutable std::vector<T> m_returned;
4208 size_t m_target_repeats;
4209 size_t m_current_repeat = 0;
4210 size_t m_repeat_index = 0;
4213 m_generator(std::move(generator)),
4214 m_target_repeats(repeats)
4216 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4219 T
const& get()
const override {
4220 if (m_current_repeat == 0) {
4221 m_returned.push_back(m_generator.get());
4222 return m_returned.back();
4224 return m_returned[m_repeat_index];
4227 bool next()
override {
4234 if (m_current_repeat == 0) {
4235 const auto success = m_generator.next();
4239 return m_current_repeat < m_target_repeats;
4244 if (m_repeat_index == m_returned.size()) {
4248 return m_current_repeat < m_target_repeats;
4252 template <
typename T>
4257 template <
typename T,
typename U,
typename Func>
4265 template <
typename F2 = Func>
4267 m_generator(std::move(generator)),
4268 m_function(std::forward<F2>(
function)),
4269 m_cache(m_function(m_generator.get()))
4272 T
const& get()
const override {
4275 bool next()
override {
4276 const auto success = m_generator.next();
4278 m_cache = m_function(m_generator.get());
4284 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4291 template <
typename T,
typename U,
typename Func>
4292 GeneratorWrapper<T> map(Func&&
function, GeneratorWrapper<U>&& generator) {
4293 return GeneratorWrapper<T>(
4294 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4298 template <
typename T>
4300 std::vector<T> m_chunk;
4301 size_t m_chunk_size;
4303 bool m_used_up =
false;
4306 m_chunk_size(size), m_generator(std::move(generator))
4308 m_chunk.reserve(m_chunk_size);
4309 if (m_chunk_size != 0) {
4310 m_chunk.push_back(m_generator.get());
4311 for (
size_t i = 1; i < m_chunk_size; ++i) {
4312 if (!m_generator.next()) {
4313 Catch::throw_exception(
GeneratorException(
"Not enough values to initialize the first chunk"));
4315 m_chunk.push_back(m_generator.get());
4319 std::vector<T>
const& get()
const override {
4322 bool next()
override {
4324 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4325 if (!m_generator.next()) {
4328 m_chunk.push_back(m_generator.get());
4334 template <
typename T>
4337 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4353 struct IResultCapture;
4356 struct IMutableContext;
4358 using IConfigPtr = std::shared_ptr<IConfig const>;
4365 virtual IRunner* getRunner() = 0;
4366 virtual IConfigPtr
const& getConfig()
const = 0;
4372 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4373 virtual void setRunner(
IRunner* runner ) = 0;
4374 virtual void setConfig( IConfigPtr
const& config ) = 0;
4379 friend void cleanUpContext();
4380 static void createContext();
4385 if( !IMutableContext::currentContext )
4386 IMutableContext::createContext();
4388 return *IMutableContext::currentContext;
4391 inline IContext& getCurrentContext()
4393 return getCurrentMutableContext();
4396 void cleanUpContext();
4410 template<
typename T>
4413 Option() : nullableValue(
nullptr ) {}
4414 Option( T
const& _value )
4415 : nullableValue(
new( storage ) T( _value ) )
4418 : nullableValue( _other ?
new( storage ) T( *_other ) :
nullptr )
4426 if( &_other !=
this ) {
4429 nullableValue =
new( storage ) T( *_other );
4433 Option& operator = ( T
const& _value ) {
4435 nullableValue =
new( storage ) T( _value );
4441 nullableValue->~T();
4442 nullableValue =
nullptr;
4445 T& operator*() {
return *nullableValue; }
4446 T
const& operator*()
const {
return *nullableValue; }
4447 T* operator->() {
return nullableValue; }
4448 const T* operator->()
const {
return nullableValue; }
4450 T valueOr( T
const& defaultValue )
const {
4451 return nullableValue ? *nullableValue : defaultValue;
4454 bool some()
const {
return nullableValue !=
nullptr; }
4455 bool none()
const {
return nullableValue ==
nullptr; }
4457 bool operator !()
const {
return nullableValue ==
nullptr; }
4458 explicit operator bool()
const {
4464 alignas(
alignof(T))
char storage[
sizeof(T)];
4478 enum class Verbosity {
4486 NoAssertions = 0x01,
4497 InLexicographicalOrder,
4509 BeforeStartAndExit = BeforeStart | BeforeExit
4518 virtual bool allowThrows()
const = 0;
4519 virtual std::ostream& stream()
const = 0;
4520 virtual std::string name()
const = 0;
4521 virtual bool includeSuccessfulResults()
const = 0;
4522 virtual bool shouldDebugBreak()
const = 0;
4523 virtual bool warnAboutMissingAssertions()
const = 0;
4524 virtual bool warnAboutNoTests()
const = 0;
4525 virtual int abortAfter()
const = 0;
4526 virtual bool showInvisibles()
const = 0;
4527 virtual ShowDurations::OrNot showDurations()
const = 0;
4528 virtual double minDuration()
const = 0;
4529 virtual TestSpec const& testSpec()
const = 0;
4530 virtual bool hasTestFilters()
const = 0;
4531 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4532 virtual RunTests::InWhatOrder runOrder()
const = 0;
4533 virtual unsigned int rngSeed()
const = 0;
4534 virtual UseColour::YesOrNo useColour()
const = 0;
4535 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4536 virtual Verbosity verbosity()
const = 0;
4538 virtual bool benchmarkNoAnalysis()
const = 0;
4539 virtual int benchmarkSamples()
const = 0;
4540 virtual double benchmarkConfidenceInterval()
const = 0;
4541 virtual unsigned int benchmarkResamples()
const = 0;
4542 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4545 using IConfigPtr = std::shared_ptr<IConfig const>;
4561 using state_type = std::uint64_t;
4563 using result_type = std::uint32_t;
4564 static constexpr result_type (min)() {
4567 static constexpr result_type (max)() {
4568 return static_cast<result_type
>(-1);
4576 void seed(result_type seed_);
4577 void discard(uint64_t skip);
4579 result_type operator()();
4588 std::uint64_t m_state;
4593 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4602 namespace Generators {
4604 template <
typename Float>
4607 std::uniform_real_distribution<Float> m_dist;
4608 Float m_current_number;
4614 static_cast<void>(next());
4617 Float
const& get()
const override {
4618 return m_current_number;
4620 bool next()
override {
4621 m_current_number = m_dist(m_rng);
4626 template <
typename Integer>
4629 std::uniform_int_distribution<Integer> m_dist;
4630 Integer m_current_number;
4636 static_cast<void>(next());
4639 Integer
const& get()
const override {
4640 return m_current_number;
4642 bool next()
override {
4643 m_current_number = m_dist(m_rng);
4650 template <
typename T>
4651 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4659 template <
typename T>
4660 typename std::enable_if<std::is_floating_point<T>::value,
4661 GeneratorWrapper<T>>::type
4663 return GeneratorWrapper<T>(
4664 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4668 template <
typename T>
4680 m_positive(m_step > T(0))
4682 assert(m_current != m_end &&
"Range start and end cannot be equal");
4683 assert(m_step != T(0) &&
"Step size cannot be zero");
4684 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4691 T
const& get()
const override {
4695 bool next()
override {
4696 m_current += m_step;
4697 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4701 template <
typename T>
4703 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
"Type must be numeric");
4707 template <
typename T>
4708 GeneratorWrapper<T> range(T
const& start, T
const& end) {
4709 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
"Type must be an integer");
4710 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4713 template <
typename T>
4715 static_assert(!std::is_same<T, bool>::value,
4716 "IteratorGenerator currently does not support bools"
4717 "because of std::vector<bool> specialization");
4719 std::vector<T> m_elems;
4720 size_t m_current = 0;
4722 template <
typename InputIterator,
typename InputSentinel>
4723 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4724 if (m_elems.empty()) {
4725 Catch::throw_exception(
GeneratorException(
"IteratorGenerator received no valid values"));
4729 T
const& get()
const override {
4730 return m_elems[m_current];
4733 bool next()
override {
4735 return m_current != m_elems.size();
4739 template <
typename InputIterator,
4740 typename InputSentinel,
4741 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4746 template <
typename Container,
4747 typename ResultType =
typename Container::value_type>
4748 GeneratorWrapper<ResultType> from_range(Container
const& cnt) {
4749 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4766 #pragma clang diagnostic push
4767 #pragma clang diagnostic ignored "-Wpadded"
4772 struct ITestInvoker;
4775 enum SpecialProperties{
4778 ShouldFail = 1 << 2,
4781 NonPortable = 1 << 5,
4786 std::string
const& _className,
4787 std::string
const& _description,
4788 std::vector<std::string>
const& _tags,
4791 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4793 bool isHidden()
const;
4794 bool throws()
const;
4795 bool okToFail()
const;
4796 bool expectedToFail()
const;
4798 std::string tagsAsString()
const;
4801 std::string className;
4802 std::string description;
4803 std::vector<std::string> tags;
4804 std::vector<std::string> lcaseTags;
4806 SpecialProperties properties;
4814 TestCase withName( std::string
const& _newName )
const;
4816 void invoke()
const;
4820 bool operator == (
TestCase const& other )
const;
4821 bool operator < (
TestCase const& other )
const;
4824 std::shared_ptr<ITestInvoker> test;
4828 std::string
const& className,
4834 #pragma clang diagnostic pop
4844 virtual bool aborting()
const = 0;
4853 #import <objc/runtime.h>
4878 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4880 virtual void invoke()
const {
4881 id obj = [[m_cls alloc] init];
4883 performOptionalSelector( obj,
@selector(setUp) );
4884 performOptionalSelector( obj, m_sel );
4885 performOptionalSelector( obj,
@selector(tearDown) );
4887 arcSafeRelease( obj );
4898 inline std::string getAnnotation( Class cls,
4899 std::string
const& annotationName,
4900 std::string
const& testCaseName ) {
4901 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4902 SEL sel = NSSelectorFromString( selStr );
4903 arcSafeRelease( selStr );
4904 id value = performOptionalSelector( cls, sel );
4906 return [(NSString*)value UTF8String];
4911 inline std::size_t registerTestMethods() {
4912 std::size_t noTestMethods = 0;
4913 int noClasses = objc_getClassList(
nullptr, 0 );
4915 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4916 objc_getClassList( classes, noClasses );
4918 for(
int c = 0; c < noClasses; c++ ) {
4919 Class cls = classes[c];
4922 Method* methods = class_copyMethodList( cls, &count );
4923 for( u_int m = 0; m < count ; m++ ) {
4924 SEL selector = method_getName(methods[m]);
4925 std::string methodName = sel_getName(selector);
4926 if( startsWith( methodName,
"Catch_TestCase_" ) ) {
4927 std::string testCaseName = methodName.substr( 15 );
4928 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4929 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4930 const char* className = class_getName( cls );
4932 getMutableRegistryHub().registerTest( makeTestCase(
new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo(
"",0) ) );
4939 return noTestMethods;
4942 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4944 namespace Matchers {
4946 namespace NSStringMatchers {
4948 struct StringHolder : MatcherBase<NSString*>{
4949 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4950 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4952 arcSafeRelease( m_substr );
4955 bool match( NSString* str )
const override {
4959 NSString* CATCH_ARC_STRONG m_substr;
4962 struct Equals : StringHolder {
4963 Equals( NSString* substr ) : StringHolder( substr ){}
4965 bool match( NSString* str )
const override {
4966 return (str != nil || m_substr == nil ) &&
4967 [str isEqualToString:m_substr];
4970 std::string describe()
const override {
4971 return "equals string: " + Catch::Detail::stringify( m_substr );
4975 struct Contains : StringHolder {
4976 Contains( NSString* substr ) : StringHolder( substr ){}
4978 bool match( NSString* str )
const override {
4979 return (str != nil || m_substr == nil ) &&
4980 [str rangeOfString:m_substr].location != NSNotFound;
4983 std::string describe()
const override {
4984 return "contains string: " + Catch::Detail::stringify( m_substr );
4988 struct StartsWith : StringHolder {
4989 StartsWith( NSString* substr ) : StringHolder( substr ){}
4991 bool match( NSString* str )
const override {
4992 return (str != nil || m_substr == nil ) &&
4993 [str rangeOfString:m_substr].location == 0;
4996 std::string describe()
const override {
4997 return "starts with: " + Catch::Detail::stringify( m_substr );
5000 struct EndsWith : StringHolder {
5001 EndsWith( NSString* substr ) : StringHolder( substr ){}
5003 bool match( NSString* str )
const override {
5004 return (str != nil || m_substr == nil ) &&
5005 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5008 std::string describe()
const override {
5009 return "ends with: " + Catch::Detail::stringify( m_substr );
5016 inline Impl::NSStringMatchers::Equals
5017 Equals( NSString* substr ){
return Impl::NSStringMatchers::Equals( substr ); }
5019 inline Impl::NSStringMatchers::Contains
5020 Contains( NSString* substr ){
return Impl::NSStringMatchers::Contains( substr ); }
5022 inline Impl::NSStringMatchers::StartsWith
5023 StartsWith( NSString* substr ){
return Impl::NSStringMatchers::StartsWith( substr ); }
5025 inline Impl::NSStringMatchers::EndsWith
5026 EndsWith( NSString* substr ){
return Impl::NSStringMatchers::EndsWith( substr ); }
5030 using namespace Matchers;
5037 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5038 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5039 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5043 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5047 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5049 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5055 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5067 #pragma clang diagnostic push
5068 #pragma clang diagnostic ignored "-Wpadded"
5074 #pragma clang diagnostic push
5075 #pragma clang diagnostic ignored "-Wpadded"
5083 enum WildcardPosition {
5085 WildcardAtStart = 1,
5087 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5092 WildcardPattern( std::string
const& pattern, CaseSensitive::Choice caseSensitivity );
5094 virtual bool matches( std::string
const& str )
const;
5097 std::string normaliseString( std::string
const& str )
const;
5098 CaseSensitive::Choice m_caseSensitivity;
5099 WildcardPosition m_wildcard = NoWildcard;
5100 std::string m_pattern;
5116 explicit Pattern( std::string
const& name );
5118 virtual bool matches(
TestCaseInfo const& testCase )
const = 0;
5119 std::string
const& name()
const;
5121 std::string
const m_name;
5123 using PatternPtr = std::shared_ptr<Pattern>;
5125 class NamePattern :
public Pattern {
5127 explicit NamePattern( std::string
const& name, std::string
const& filterString );
5128 bool matches(
TestCaseInfo const& testCase )
const override;
5133 class TagPattern :
public Pattern {
5135 explicit TagPattern( std::string
const& tag, std::string
const& filterString );
5136 bool matches(
TestCaseInfo const& testCase )
const override;
5141 class ExcludedPattern :
public Pattern {
5143 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5144 bool matches(
TestCaseInfo const& testCase )
const override;
5146 PatternPtr m_underlyingPattern;
5150 std::vector<PatternPtr> m_patterns;
5153 std::string name()
const;
5157 struct FilterMatch {
5159 std::vector<TestCase const*> tests;
5161 using Matches = std::vector<FilterMatch>;
5162 using vectorStrings = std::vector<std::string>;
5164 bool hasFilters()
const;
5166 Matches matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const;
5167 const vectorStrings & getInvalidArgs()
const;
5170 std::vector<Filter> m_filters;
5171 std::vector<std::string> m_invalidArgs;
5177 #pragma clang diagnostic pop
5192 virtual TagAlias const* find( std::string
const& alias )
const = 0;
5193 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
5204 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5206 Mode lastMode = None;
5207 bool m_exclusion =
false;
5208 std::size_t m_pos = 0;
5209 std::size_t m_realPatternPos = 0;
5211 std::string m_substring;
5212 std::string m_patternName;
5213 std::vector<std::size_t> m_escapeChars;
5214 TestSpec::Filter m_currentFilter;
5225 bool visitChar(
char c );
5226 void startNewMode( Mode mode );
5227 bool processNoneChar(
char c );
5228 void processNameChar(
char c );
5229 bool processOtherChar(
char c );
5232 bool isControlChar(
char c )
const;
5233 void saveLastMode();
5234 void revertBackToLastMode();
5239 std::string preprocessPattern();
5241 void addNamePattern();
5243 void addTagPattern();
5245 inline void addCharToPattern(
char c) {
5252 TestSpec parseTestSpec( std::string
const& arg );
5257 #pragma clang diagnostic pop
5267 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5268 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5276 bool listTests =
false;
5277 bool listTags =
false;
5278 bool listReporters =
false;
5279 bool listTestNamesOnly =
false;
5281 bool showSuccessfulTests =
false;
5282 bool shouldDebugBreak =
false;
5283 bool noThrow =
false;
5284 bool showHelp =
false;
5285 bool showInvisibles =
false;
5286 bool filenamesAsTags =
false;
5287 bool libIdentify =
false;
5289 int abortAfter = -1;
5290 unsigned int rngSeed = 0;
5292 bool benchmarkNoAnalysis =
false;
5293 unsigned int benchmarkSamples = 100;
5294 double benchmarkConfidenceInterval = 0.95;
5295 unsigned int benchmarkResamples = 100000;
5296 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5298 Verbosity verbosity = Verbosity::Normal;
5299 WarnAbout::What warnings = WarnAbout::Nothing;
5300 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5301 double minDuration = -1;
5302 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5303 UseColour::YesOrNo useColour = UseColour::Auto;
5304 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5306 std::string outputFilename;
5308 std::string processName;
5309 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5310 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5312 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5313 #undef CATCH_CONFIG_DEFAULT_REPORTER
5315 std::vector<std::string> testsOrTags;
5316 std::vector<std::string> sectionsToRun;
5324 virtual ~
Config() =
default;
5326 std::string
const& getFilename()
const;
5328 bool listTests()
const;
5329 bool listTestNamesOnly()
const;
5330 bool listTags()
const;
5331 bool listReporters()
const;
5333 std::string getProcessName()
const;
5334 std::string
const& getReporterName()
const;
5336 std::vector<std::string>
const& getTestsOrTags()
const override;
5337 std::vector<std::string>
const& getSectionsToRun()
const override;
5339 TestSpec const& testSpec()
const override;
5340 bool hasTestFilters()
const override;
5342 bool showHelp()
const;
5345 bool allowThrows()
const override;
5346 std::ostream& stream()
const override;
5347 std::string name()
const override;
5348 bool includeSuccessfulResults()
const override;
5349 bool warnAboutMissingAssertions()
const override;
5350 bool warnAboutNoTests()
const override;
5351 ShowDurations::OrNot showDurations()
const override;
5352 double minDuration()
const override;
5353 RunTests::InWhatOrder runOrder()
const override;
5354 unsigned int rngSeed()
const override;
5355 UseColour::YesOrNo useColour()
const override;
5356 bool shouldDebugBreak()
const override;
5357 int abortAfter()
const override;
5358 bool showInvisibles()
const override;
5359 Verbosity verbosity()
const override;
5360 bool benchmarkNoAnalysis()
const override;
5361 int benchmarkSamples()
const override;
5362 double benchmarkConfidenceInterval()
const override;
5363 unsigned int benchmarkResamples()
const override;
5364 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5371 std::unique_ptr<IStream const> m_stream;
5373 bool m_hasTestFilters =
false;
5391 std::string message;
5392 mutable std::string reconstructedExpression;
5394 ResultWas::OfType resultType;
5396 std::string reconstructExpression()
const;
5405 bool succeeded()
const;
5406 ResultWas::OfType getResultType()
const;
5407 bool hasExpression()
const;
5408 bool hasMessage()
const;
5409 std::string getExpression()
const;
5410 std::string getExpressionInMacro()
const;
5411 bool hasExpandedExpression()
const;
5412 std::string getExpandedExpression()
const;
5413 std::string getMessage()
const;
5425 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5432 namespace Benchmark {
5433 template <
typename Duration>
5436 Duration lower_bound;
5437 Duration upper_bound;
5438 double confidence_interval;
5440 template <
typename Duration2>
5442 return { point, lower_bound, upper_bound, confidence_interval };
5454 namespace Benchmark {
5456 int samples_seen = 0;
5460 int high_severe = 0;
5463 return low_severe + low_mild + high_mild + high_severe;
5477 #include <algorithm>
5484 ReporterConfig( IConfigPtr
const& _fullConfig, std::ostream& _stream );
5486 std::ostream& stream()
const;
5487 IConfigPtr fullConfig()
const;
5490 std::ostream* m_stream;
5491 IConfigPtr m_fullConfig;
5495 bool shouldRedirectStdOut =
false;
5496 bool shouldReportAllAssertions =
false;
5499 template<
typename T>
5501 LazyStat& operator=( T
const& _value ) {
5519 std::size_t _groupIndex,
5520 std::size_t _groupsCount );
5523 std::size_t groupIndex;
5524 std::size_t groupsCounts;
5529 std::vector<MessageInfo>
const& _infoMessages,
5539 std::vector<MessageInfo> infoMessages;
5545 Counts const& _assertions,
5546 double _durationInSeconds,
5547 bool _missingAssertions );
5556 double durationInSeconds;
5557 bool missingAssertions;
5563 std::string
const& _stdOut,
5564 std::string
const& _stdErr,
5613 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5616 double estimatedDuration;
5619 unsigned int resamples;
5620 double clockResolution;
5624 template <
class Duration>
5628 std::vector<Duration> samples;
5632 double outlierVariance;
5634 template <
typename Duration2>
5636 std::vector<Duration2> samples2;
5637 samples2.reserve(samples.size());
5638 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5641 std::move(samples2),
5660 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5662 virtual void reportInvalidArguments(std::string
const&) {}
5664 virtual void testRunStarting(
TestRunInfo const& testRunInfo ) = 0;
5665 virtual void testGroupStarting(
GroupInfo const& groupInfo ) = 0;
5667 virtual void testCaseStarting(
TestCaseInfo const& testInfo ) = 0;
5668 virtual void sectionStarting(
SectionInfo const& sectionInfo ) = 0;
5670 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5671 virtual void benchmarkPreparing( std::string
const& ) {}
5674 virtual void benchmarkFailed( std::string
const& ) {}
5677 virtual void assertionStarting(
AssertionInfo const& assertionInfo ) = 0;
5680 virtual bool assertionEnded(
AssertionStats const& assertionStats ) = 0;
5682 virtual void sectionEnded(
SectionStats const& sectionStats ) = 0;
5683 virtual void testCaseEnded(
TestCaseStats const& testCaseStats ) = 0;
5684 virtual void testGroupEnded(
TestGroupStats const& testGroupStats ) = 0;
5685 virtual void testRunEnded(
TestRunStats const& testRunStats ) = 0;
5687 virtual void skipTest(
TestCaseInfo const& testInfo ) = 0;
5690 virtual void fatalErrorEncountered(
StringRef name );
5692 virtual bool isMulti()
const;
5694 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5698 virtual IStreamingReporterPtr create(
ReporterConfig const& config )
const = 0;
5699 virtual std::string getDescription()
const = 0;
5701 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5704 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5705 using Listeners = std::vector<IReporterFactoryPtr>;
5708 virtual IStreamingReporterPtr create( std::string
const& name, IConfigPtr
const& config )
const = 0;
5709 virtual FactoryMap
const& getFactories()
const = 0;
5710 virtual Listeners
const& getListeners()
const = 0;
5716 #include <algorithm>
5725 void prepareExpandedExpression(AssertionResult& result);
5728 std::string getFormattedDuration(
double duration );
5731 bool shouldShowDuration( IConfig
const& config,
double duration );
5733 std::string serializeFilters( std::vector<std::string>
const& container );
5735 template<
typename DerivedT>
5739 : m_config( _config.fullConfig() ),
5740 stream( _config.stream() )
5742 m_reporterPrefs.shouldRedirectStdOut =
false;
5743 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5744 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5748 return m_reporterPrefs;
5751 static std::set<Verbosity> getSupportedVerbosities() {
5752 return { Verbosity::Normal };
5757 void noMatchingTestCases(std::string
const&)
override {}
5759 void reportInvalidArguments(std::string
const&)
override {}
5761 void testRunStarting(
TestRunInfo const& _testRunInfo)
override {
5762 currentTestRunInfo = _testRunInfo;
5765 void testGroupStarting(
GroupInfo const& _groupInfo)
override {
5766 currentGroupInfo = _groupInfo;
5769 void testCaseStarting(
TestCaseInfo const& _testInfo)
override {
5770 currentTestCaseInfo = _testInfo;
5772 void sectionStarting(
SectionInfo const& _sectionInfo)
override {
5773 m_sectionStack.push_back(_sectionInfo);
5777 m_sectionStack.pop_back();
5780 currentTestCaseInfo.reset();
5783 currentGroupInfo.reset();
5786 currentTestCaseInfo.reset();
5787 currentGroupInfo.reset();
5788 currentTestRunInfo.reset();
5796 IConfigPtr m_config;
5797 std::ostream& stream;
5803 std::vector<SectionInfo> m_sectionStack;
5807 template<
typename DerivedT>
5809 template<
typename T,
typename ChildNodeT>
5811 explicit Node( T
const& _value ) : value( _value ) {}
5814 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5816 ChildNodes children;
5822 bool operator == (
SectionNode const& other)
const {
5823 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5825 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5826 return operator==(*other);
5830 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5831 using Assertions = std::vector<AssertionStats>;
5832 ChildSections childSections;
5833 Assertions assertions;
5841 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5842 return ((node->stats.sectionInfo.name == m_other.name) &&
5843 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5856 : m_config( _config.fullConfig() ),
5857 stream( _config.stream() )
5859 m_reporterPrefs.shouldRedirectStdOut =
false;
5860 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5861 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5866 return m_reporterPrefs;
5869 static std::set<Verbosity> getSupportedVerbosities() {
5870 return { Verbosity::Normal };
5873 void testRunStarting( TestRunInfo
const& )
override {}
5874 void testGroupStarting( GroupInfo
const& )
override {}
5876 void testCaseStarting( TestCaseInfo
const& )
override {}
5878 void sectionStarting( SectionInfo
const& sectionInfo )
override {
5879 SectionStats incompleteStats( sectionInfo, Counts(), 0,
false );
5880 std::shared_ptr<SectionNode> node;
5881 if( m_sectionStack.empty() ) {
5882 if( !m_rootSection )
5883 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5884 node = m_rootSection;
5887 SectionNode& parentNode = *m_sectionStack.back();
5889 std::find_if( parentNode.childSections.begin(),
5890 parentNode.childSections.end(),
5891 BySectionInfo( sectionInfo ) );
5892 if( it == parentNode.childSections.end() ) {
5893 node = std::make_shared<SectionNode>( incompleteStats );
5894 parentNode.childSections.push_back( node );
5899 m_sectionStack.push_back( node );
5900 m_deepestSection = std::move(node);
5903 void assertionStarting(AssertionInfo
const&)
override {}
5905 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5906 assert(!m_sectionStack.empty());
5912 prepareExpandedExpression(
const_cast<AssertionResult&
>( assertionStats.assertionResult ) );
5913 SectionNode& sectionNode = *m_sectionStack.back();
5914 sectionNode.assertions.push_back(assertionStats);
5917 void sectionEnded(SectionStats
const& sectionStats)
override {
5918 assert(!m_sectionStack.empty());
5919 SectionNode& node = *m_sectionStack.back();
5920 node.stats = sectionStats;
5921 m_sectionStack.pop_back();
5923 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5924 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5925 assert(m_sectionStack.size() == 0);
5926 node->children.push_back(m_rootSection);
5927 m_testCases.push_back(node);
5928 m_rootSection.reset();
5930 assert(m_deepestSection);
5931 m_deepestSection->stdOut = testCaseStats.stdOut;
5932 m_deepestSection->stdErr = testCaseStats.stdErr;
5934 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5935 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5936 node->children.swap(m_testCases);
5937 m_testGroups.push_back(node);
5939 void testRunEnded(TestRunStats
const& testRunStats)
override {
5940 auto node = std::make_shared<TestRunNode>(testRunStats);
5941 node->children.swap(m_testGroups);
5942 m_testRuns.push_back(node);
5943 testRunEndedCumulative();
5945 virtual void testRunEndedCumulative() = 0;
5947 void skipTest(TestCaseInfo
const&)
override {}
5949 IConfigPtr m_config;
5950 std::ostream& stream;
5951 std::vector<AssertionStats> m_assertions;
5952 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5953 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5954 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5956 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5958 std::shared_ptr<SectionNode> m_rootSection;
5959 std::shared_ptr<SectionNode> m_deepestSection;
5960 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5961 ReporterPreferences m_reporterPrefs;
5965 char const* getLineOfChars() {
5966 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5968 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5969 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5977 static std::set<Verbosity> getSupportedVerbosities();
6004 BrightRed = Bright | Red,
6005 BrightGreen = Bright | Green,
6006 LightGrey = Bright | Grey,
6007 BrightWhite = Bright | White,
6008 BrightYellow = Bright | Yellow,
6011 FileName = LightGrey,
6012 Warning = BrightYellow,
6013 ResultError = BrightRed,
6014 ResultSuccess = BrightGreen,
6015 ResultExpectedFailure = Warning,
6020 OriginalExpression = Cyan,
6021 ReconstructedExpression = BrightYellow,
6023 SecondaryText = LightGrey,
6028 Colour( Code _colourCode );
6034 static void use( Code _colourCode );
6037 bool m_moved =
false;
6040 std::ostream& operator << ( std::ostream& os,
Colour const& );
6050 template<
typename T>
6055 IStreamingReporterPtr create(
ReporterConfig const& config )
const override {
6056 return std::unique_ptr<T>(
new T( config ) );
6059 std::string getDescription()
const override {
6060 return T::getDescription();
6067 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6071 template<
typename T>
6076 IStreamingReporterPtr create(
ReporterConfig const& config )
const override {
6077 return std::unique_ptr<T>(
new T( config ) );
6079 std::string getDescription()
const override {
6080 return std::string();
6087 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6092 #if !defined(CATCH_CONFIG_DISABLE)
6094 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
6095 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6096 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6097 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6098 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6100 #define CATCH_REGISTER_LISTENER( listenerType ) \
6101 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6102 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6103 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6104 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6107 #define CATCH_REGISTER_REPORTER(name, reporterType)
6108 #define CATCH_REGISTER_LISTENER(listenerType)
6120 using StreamingReporterBase::StreamingReporterBase;
6124 static std::string getDescription();
6126 void noMatchingTestCases(std::string
const& spec)
override;
6130 bool assertionEnded(
AssertionStats const& _assertionStats)
override;
6132 void sectionEnded(
SectionStats const& _sectionStats)
override;
6134 void testRunEnded(
TestRunStats const& _testRunStats)
override;
6143 #if defined(_MSC_VER)
6144 #pragma warning(push)
6145 #pragma warning(disable:4061)
6152 struct SummaryColumn;
6156 std::unique_ptr<TablePrinter> m_tablePrinter;
6160 static std::string getDescription();
6162 void noMatchingTestCases(std::string
const& spec)
override;
6164 void reportInvalidArguments(std::string
const&arg)
override;
6168 bool assertionEnded(
AssertionStats const& _assertionStats)
override;
6170 void sectionStarting(
SectionInfo const& _sectionInfo)
override;
6171 void sectionEnded(
SectionStats const& _sectionStats)
override;
6173 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6174 void benchmarkPreparing(std::string
const& name)
override;
6177 void benchmarkFailed(std::string
const& error)
override;
6180 void testCaseEnded(
TestCaseStats const& _testCaseStats)
override;
6181 void testGroupEnded(
TestGroupStats const& _testGroupStats)
override;
6182 void testRunEnded(
TestRunStats const& _testRunStats)
override;
6183 void testRunStarting(
TestRunInfo const& _testRunInfo)
override;
6188 void lazyPrintWithoutClosingBenchmarkTable();
6189 void lazyPrintRunInfo();
6190 void lazyPrintGroupInfo();
6191 void printTestCaseAndSectionHeader();
6193 void printClosedHeader(std::string
const& _name);
6194 void printOpenHeader(std::string
const& _name);
6198 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6200 void printTotals(
Totals const& totals);
6201 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row);
6203 void printTotalsDivider(
Totals const& totals);
6204 void printSummaryDivider();
6205 void printTestFilters();
6208 bool m_headerPrinted =
false;
6213 #if defined(_MSC_VER)
6214 #pragma warning(pop)
6225 enum class XmlFormatting {
6231 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6232 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6236 enum ForWhat { ForTextNodes, ForAttributes };
6238 XmlEncode( std::string
const& str, ForWhat forWhat = ForTextNodes );
6240 void encodeTo( std::ostream& os )
const;
6242 friend std::ostream& operator << ( std::ostream& os,
XmlEncode const& xmlEncode );
6261 ScopedElement& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6263 template<
typename T>
6264 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
6265 m_writer->writeAttribute( name, attribute );
6271 XmlFormatting m_fmt;
6274 XmlWriter( std::ostream& os = Catch::cout() );
6280 XmlWriter& startElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6282 ScopedElement scopedElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6284 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6286 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute );
6288 XmlWriter& writeAttribute( std::string
const& name,
bool attribute );
6290 template<
typename T>
6291 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
6294 return writeAttribute( name, rss.str() );
6297 XmlWriter& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6299 XmlWriter& writeComment(std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6301 void writeStylesheetRef( std::string
const& url );
6305 void ensureTagClosed();
6309 void applyFormatting(XmlFormatting fmt);
6311 void writeDeclaration();
6313 void newlineIfNecessary();
6315 bool m_tagIsOpen =
false;
6316 bool m_needsNewline =
false;
6317 std::vector<std::string> m_tags;
6318 std::string m_indent;
6333 static std::string getDescription();
6335 void noMatchingTestCases(std::string
const& )
override;
6337 void testRunStarting(
TestRunInfo const& runInfo)
override;
6339 void testGroupStarting(
GroupInfo const& groupInfo)
override;
6341 void testCaseStarting(
TestCaseInfo const& testCaseInfo)
override;
6342 bool assertionEnded(
AssertionStats const& assertionStats)
override;
6344 void testCaseEnded(
TestCaseStats const& testCaseStats)
override;
6346 void testGroupEnded(
TestGroupStats const& testGroupStats)
override;
6348 void testRunEndedCumulative()
override;
6350 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6352 void writeTestCase(TestCaseNode
const& testCaseNode);
6354 void writeSection(std::string
const& className,
6355 std::string
const& rootName,
6356 SectionNode
const& sectionNode);
6358 void writeAssertions(SectionNode
const& sectionNode);
6363 std::string stdOutForSuite;
6364 std::string stdErrForSuite;
6365 unsigned int unexpectedExceptions = 0;
6366 bool m_okToFail =
false;
6381 static std::string getDescription();
6383 virtual std::string getStylesheetRef()
const;
6389 void noMatchingTestCases(std::string
const& s)
override;
6391 void testRunStarting(
TestRunInfo const& testInfo)
override;
6393 void testGroupStarting(
GroupInfo const& groupInfo)
override;
6395 void testCaseStarting(
TestCaseInfo const& testInfo)
override;
6397 void sectionStarting(
SectionInfo const& sectionInfo)
override;
6401 bool assertionEnded(
AssertionStats const& assertionStats)
override;
6403 void sectionEnded(
SectionStats const& sectionStats)
override;
6405 void testCaseEnded(
TestCaseStats const& testCaseStats)
override;
6407 void testGroupEnded(
TestGroupStats const& testGroupStats)
override;
6409 void testRunEnded(
TestRunStats const& testRunStats)
override;
6411 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6412 void benchmarkPreparing(std::string
const& name)
override;
6415 void benchmarkFailed(std::string
const&)
override;
6419 Timer m_testCaseTimer;
6421 int m_sectionDepth = 0;
6431 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6456 namespace Benchmark {
6457 template <
typename Clock>
6458 using ClockDuration =
typename Clock::duration;
6459 template <
typename Clock>
6460 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6462 template <
typename Clock>
6463 using TimePoint =
typename Clock::time_point;
6465 using default_clock = std::chrono::steady_clock;
6467 template <
typename Clock>
6469 TimePoint<Clock> operator()()
const {
6470 return Clock::now();
6474 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6484 #if defined(_MSC_VER)
6489 namespace Benchmark {
6490 #if defined(__GNUC__) || defined(__clang__)
6491 template <
typename T>
6492 inline void keep_memory(T* p) {
6493 asm volatile(
"" : :
"g"(p) :
"memory");
6495 inline void keep_memory() {
6496 asm volatile(
"" : : :
"memory");
6500 inline void optimizer_barrier() { keep_memory(); }
6502 #elif defined(_MSC_VER)
6504 #pragma optimize("", off)
6505 template <
typename T>
6506 inline void keep_memory(T* p) {
6508 *
reinterpret_cast<char volatile*
>(p) = *
reinterpret_cast<char const volatile*
>(p);
6511 #pragma optimize("", on)
6514 inline void optimizer_barrier() {
6515 std::atomic_thread_fence(std::memory_order_seq_cst);
6521 template <
typename T>
6522 inline void deoptimize_value(T&& x) {
6526 template <
typename Fn,
typename... Args>
6527 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6528 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6531 template <
typename Fn,
typename... Args>
6532 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6533 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6544 #include <type_traits>
6548 namespace Benchmark {
6550 template <
typename T>
6555 template <
typename T>
6556 using CompleteType_t =
typename CompleteType<T>::type;
6558 template <
typename Result>
6559 struct CompleteInvoker {
6560 template <
typename Fun,
typename... Args>
6561 static Result invoke(Fun&& fun, Args&&... args) {
6562 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6566 struct CompleteInvoker<void> {
6567 template <
typename Fun,
typename... Args>
6568 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6569 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6575 template <
typename Fun,
typename... Args>
6576 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6577 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6580 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6583 template <
typename Fun>
6584 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6586 return Detail::complete_invoke(std::forward<Fun>(fun));
6588 getResultCapture().benchmarkFailed(translateActiveException());
6589 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6597 namespace Benchmark {
6600 virtual void start() = 0;
6601 virtual void finish() = 0;
6604 template <
typename Clock>
6606 void start()
override { started = Clock::now(); }
6607 void finish()
override { finished = Clock::now(); }
6609 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6611 TimePoint<Clock> started;
6612 TimePoint<Clock> finished;
6618 template <
typename Fun>
6619 void measure(Fun&& fun) { measure(std::forward<Fun>(fun),
is_callable<Fun(
int)>()); }
6621 int runs()
const {
return k; }
6628 template <
typename Fun>
6629 void measure(Fun&& fun, std::false_type) {
6630 measure([&fun](
int) {
return fun(); }, std::true_type());
6633 template <
typename Fun>
6634 void measure(Fun&& fun, std::true_type) {
6635 Detail::optimizer_barrier();
6637 for (
int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6639 Detail::optimizer_barrier();
6655 namespace Benchmark {
6656 template <
typename Duration>
6661 template <
typename Duration2>
6663 return { mean, outliers };
6666 template <
typename Clock>
6668 using clock_type = Clock;
6687 #include <type_traits>
6692 namespace Benchmark {
6694 template <
typename T>
6695 using Decay =
typename std::decay<T>::type;
6696 template <
typename T,
typename U>
6698 : std::is_same<Decay<T>, Decay<U>> {};
6707 struct BenchmarkFunction {
6710 virtual void call(Chronometer meter)
const = 0;
6711 virtual callable* clone()
const = 0;
6712 virtual ~callable() =
default;
6714 template <
typename Fun>
6715 struct model :
public callable {
6716 model(Fun&& fun) : fun(std::move(fun)) {}
6717 model(Fun
const& fun) : fun(fun) {}
6719 model<Fun>* clone()
const override {
return new model<Fun>(*
this); }
6721 void call(Chronometer meter)
const override {
6722 call(meter, is_callable<Fun(Chronometer)>());
6724 void call(Chronometer meter, std::true_type)
const {
6727 void call(Chronometer meter, std::false_type)
const {
6734 struct do_nothing {
void operator()()
const {} };
6736 template <
typename T>
6737 BenchmarkFunction(model<T>* c) : f(c) {}
6741 : f(new model<do_nothing>{ {} }) {}
6743 template <
typename Fun,
6744 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
int>::type = 0>
6745 BenchmarkFunction(Fun&& fun)
6746 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6748 BenchmarkFunction(BenchmarkFunction&& that)
6749 : f(std::move(that.f)) {}
6751 BenchmarkFunction(BenchmarkFunction
const& that)
6752 : f(that.f->clone()) {}
6754 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6755 f = std::move(that.f);
6759 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6760 f.reset(that.f->clone());
6764 void operator()(Chronometer meter)
const { f->call(meter); }
6767 std::unique_ptr<callable> f;
6779 #include <type_traits>
6783 namespace Benchmark {
6785 template <
typename Fun>
6787 void operator()(
int k)
const {
6788 for (
int i = 0; i < k; ++i) {
6794 template <
typename Fun>
6796 return { std::forward<Fun>(fun) };
6819 #include <type_traits>
6822 namespace Benchmark {
6823 template <
typename Duration,
typename Result>
6829 template <
typename Clock,
typename Func,
typename... Args>
6838 namespace Benchmark {
6840 template <
typename Clock,
typename Fun,
typename... Args>
6841 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6842 auto start = Clock::now();
6843 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6844 auto end = Clock::now();
6845 auto delta = end - start;
6846 return { delta, std::forward<decltype(r)>(r), 1 };
6854 #include <type_traits>
6857 namespace Benchmark {
6859 template <
typename Clock,
typename Fun>
6860 TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6861 return Detail::measure<Clock>(fun, iters);
6863 template <
typename Clock,
typename Fun>
6864 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6865 Detail::ChronometerModel<Clock> meter;
6866 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6868 return { meter.elapsed(), std::move(result), iters };
6871 template <
typename Clock,
typename Fun>
6872 using run_for_at_least_argument_t =
typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer,
int>::type;
6874 struct optimized_away_error : std::exception {
6875 const char* what() const noexcept
override {
6876 return "could not measure benchmark, maybe it was optimized away";
6880 template <
typename Clock,
typename Fun>
6881 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6883 while (iters < (1 << 30)) {
6884 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6886 if (Timing.elapsed >= how_long) {
6887 return { Timing.elapsed, std::move(Timing.result), iters };
6891 throw optimized_away_error{};
6898 #include <algorithm>
6901 namespace Benchmark {
6902 template <
typename Duration>
6904 int iterations_per_sample;
6905 Duration estimated_duration;
6906 Detail::BenchmarkFunction benchmark;
6907 Duration warmup_time;
6908 int warmup_iterations;
6910 template <
typename Duration2>
6912 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6915 template <
typename Clock>
6916 std::vector<FloatDuration<Clock>> run(
const IConfig &cfg,
Environment<FloatDuration<Clock>> env)
const {
6918 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(
now<Clock>{}));
6920 std::vector<FloatDuration<Clock>> times;
6921 times.reserve(cfg.benchmarkSamples());
6922 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [
this, env] {
6923 Detail::ChronometerModel<Clock> model;
6924 this->benchmark(Chronometer(model, iterations_per_sample));
6925 auto sample_time = model.elapsed() - env.clock_cost.mean;
6926 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6927 return sample_time / iterations_per_sample;
6946 #include <algorithm>
6947 #include <functional>
6958 namespace Benchmark {
6960 using sample = std::vector<double>;
6962 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6964 template <
typename Iterator>
6965 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6966 std::vector<double> copy(first, last);
6968 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6969 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6971 auto los = q1 - (iqr * 3.);
6972 auto lom = q1 - (iqr * 1.5);
6973 auto him = q3 + (iqr * 1.5);
6974 auto his = q3 + (iqr * 3.);
6976 OutlierClassification o;
6977 for (; first != last; ++first) {
6979 if (t < los) ++o.low_severe;
6980 else if (t < lom) ++o.low_mild;
6981 else if (t > his) ++o.high_severe;
6982 else if (t > him) ++o.high_mild;
6988 template <
typename Iterator>
6989 double mean(Iterator first, Iterator last) {
6990 auto count = last - first;
6991 double sum = std::accumulate(first, last, 0.);
6995 template <
typename URng,
typename Iterator,
typename Estimator>
6996 sample resample(URng& rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
6997 auto n = last - first;
6998 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7001 out.reserve(resamples);
7002 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7003 std::vector<double> resampled;
7004 resampled.reserve(n);
7005 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
return first[dist(rng)]; });
7006 return estimator(resampled.begin(), resampled.end());
7008 std::sort(out.begin(), out.end());
7012 template <
typename Estimator,
typename Iterator>
7013 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7014 auto n = last - first;
7015 auto second = std::next(first);
7019 for (
auto it = first; it != last; ++it) {
7020 std::iter_swap(it, first);
7021 results.push_back(estimator(second, last));
7027 inline double normal_cdf(
double x) {
7028 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7031 double erfc_inv(
double x);
7033 double normal_quantile(
double p);
7035 template <
typename Iterator,
typename Estimator>
7036 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last, sample
const& resample, Estimator&& estimator) {
7037 auto n_samples = last - first;
7039 double point = estimator(first, last);
7041 if (n_samples == 1)
return { point, point, point, confidence_level };
7043 sample jack = jackknife(estimator, first, last);
7044 double jack_mean = mean(jack.begin(), jack.end());
7045 double sum_squares, sum_cubes;
7046 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> {
7047 auto d = jack_mean - x;
7050 return { sqcb.first + d2, sqcb.second + d3 };
7053 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7054 int n =
static_cast<int>(resample.size());
7055 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) { return x < point; }) / (double)n;
7057 if (prob_n == 0)
return { point, point, point, confidence_level };
7059 double bias = normal_quantile(prob_n);
7060 double z1 = normal_quantile((1. - confidence_level) / 2.);
7062 auto cumn = [n](
double x) ->
int {
7063 return std::lround(normal_cdf(x) * n); };
7064 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7065 double b1 = bias + z1;
7066 double b2 = bias - z1;
7069 auto lo = std::max(cumn(a1), 0);
7070 auto hi = std::min(cumn(a2), n - 1);
7072 return { point, resample[lo], resample[hi], confidence_level };
7075 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7080 double outlier_variance;
7083 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7089 #include <algorithm>
7096 namespace Benchmark {
7098 template <
typename Clock>
7099 std::vector<double> resolution(
int k) {
7100 std::vector<TimePoint<Clock>> times;
7101 times.reserve(k + 1);
7102 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7104 std::vector<double> deltas;
7106 std::transform(std::next(times.begin()), times.end(), times.begin(),
7107 std::back_inserter(deltas),
7108 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7113 const auto warmup_iterations = 10000;
7114 const auto warmup_time = std::chrono::milliseconds(100);
7115 const auto minimum_ticks = 1000;
7116 const auto warmup_seed = 10000;
7117 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7118 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7119 const auto clock_cost_estimation_tick_limit = 100000;
7120 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7121 const auto clock_cost_estimation_iterations = 10000;
7123 template <
typename Clock>
7125 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7128 template <
typename Clock>
7129 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7130 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7133 FloatDuration<Clock>(mean(r.begin(), r.end())),
7134 classify_outliers(r.begin(), r.end()),
7137 template <
typename Clock>
7138 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7139 auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
7140 auto time_clock = [](
int k) {
7141 return Detail::measure<Clock>([k] {
7142 for (
int i = 0; i < k; ++i) {
7143 volatile auto ignored = Clock::now();
7149 int iters = clock_cost_estimation_iterations;
7150 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7151 std::vector<double> times;
7152 int nsamples =
static_cast<int>(std::ceil(time_limit / r.elapsed));
7153 times.reserve(nsamples);
7154 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7155 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7158 FloatDuration<Clock>(mean(times.begin(), times.end())),
7159 classify_outliers(times.begin(), times.end()),
7163 template <
typename Clock>
7164 Environment<FloatDuration<Clock>> measure_environment() {
7165 static Environment<FloatDuration<Clock>>* env =
nullptr;
7170 auto iters = Detail::warmup<Clock>();
7171 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7172 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7174 env =
new Environment<FloatDuration<Clock>>{ resolution, cost };
7192 #include <algorithm>
7198 namespace Benchmark {
7199 template <
typename Duration>
7201 std::vector<Duration> samples;
7205 double outlier_variance;
7207 template <
typename Duration2>
7209 std::vector<Duration2> samples2;
7210 samples2.reserve(samples.size());
7211 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7213 std::move(samples2),
7225 #include <algorithm>
7230 namespace Benchmark {
7232 template <
typename Duration,
typename Iterator>
7233 SampleAnalysis<Duration> analyse(
const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7234 if (!cfg.benchmarkNoAnalysis()) {
7235 std::vector<double> samples;
7236 samples.reserve(last - first);
7237 std::transform(first, last, std::back_inserter(samples), [](Duration d) {
return d.count(); });
7239 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7240 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7242 auto wrap_estimate = [](Estimate<double> e) {
7243 return Estimate<Duration> {
7245 Duration(e.lower_bound),
7246 Duration(e.upper_bound),
7247 e.confidence_interval,
7250 std::vector<Duration> samples2;
7251 samples2.reserve(samples.size());
7252 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
double d) { return Duration(d); });
7254 std::move(samples2),
7255 wrap_estimate(analysis.mean),
7256 wrap_estimate(analysis.standard_deviation),
7258 analysis.outlier_variance,
7261 std::vector<Duration> samples;
7262 samples.reserve(last - first);
7264 Duration mean = Duration(0);
7266 for (
auto it = first; it < last; ++it, ++i) {
7267 samples.push_back(Duration(*it));
7268 mean += Duration(*it);
7274 Estimate<Duration>{mean, mean, mean, 0.0},
7275 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7276 OutlierClassification{},
7286 #include <algorithm>
7287 #include <functional>
7293 namespace Benchmark {
7296 : name(std::move(name)) {}
7298 template <
class FUN>
7299 Benchmark(std::string &&name, FUN &&func)
7300 : fun(std::move(func)), name(std::move(name)) {}
7302 template <
typename Clock>
7304 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7305 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7306 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7307 int new_iters =
static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7308 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7311 template <
typename Clock = default_clock>
7313 IConfigPtr cfg = getCurrentContext().getConfig();
7315 auto env = Detail::measure_environment<Clock>();
7317 getResultCapture().benchmarkPreparing(name);
7319 auto plan = user_code([&] {
7320 return prepare<Clock>(*cfg, env);
7325 plan.estimated_duration.count(),
7326 plan.iterations_per_sample,
7327 cfg->benchmarkSamples(),
7328 cfg->benchmarkResamples(),
7329 env.clock_resolution.mean.count(),
7330 env.clock_cost.mean.count()
7333 getResultCapture().benchmarkStarting(info);
7335 auto samples = user_code([&] {
7336 return plan.template run<Clock>(*cfg, env);
7339 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7341 getResultCapture().benchmarkEnded(stats);
7344 if (translateActiveException() != Detail::benchmarkErrorMsg)
7345 std::rethrow_exception(std::current_exception());
7350 template <
typename Fun,
7351 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value,
int>::type = 0>
7353 fun = Detail::BenchmarkFunction(func);
7358 explicit operator bool() {
7363 Detail::BenchmarkFunction fun;
7369 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7370 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7372 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7373 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7374 BenchmarkName = [&](int benchmarkIndex)
7376 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7377 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7386 #include <type_traits>
7389 namespace Benchmark {
7391 template <
typename T,
bool Destruct>
7394 using TStorage =
typename std::aligned_storage<
sizeof(T), std::alignment_of<T>::value>::type;
7400 new(&data) T(other.stored_object());
7405 new(&data) T(std::move(other.stored_object()));
7410 template <
typename... Args>
7411 void construct(Args&&... args)
7413 new (&data) T(std::forward<Args>(args)...);
7416 template <
bool AllowManualDestruction = !Destruct>
7417 typename std::enable_if<AllowManualDestruction>::type destruct()
7419 stored_object().~T();
7424 template <
typename U>
7425 void destruct_on_exit(
typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7427 template <
typename U>
7428 void destruct_on_exit(
typename std::enable_if<!Destruct, U>::type* = 0) { }
7430 T& stored_object() {
7431 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7434 T
const& stored_object()
const {
7435 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7442 template <
typename T>
7445 template <
typename T>
7460 #pragma clang diagnostic push
7461 #pragma clang diagnostic ignored "-Wweak-vtables"
7472 namespace TestCaseTracking {
7480 return lhs.name == rhs.name
7481 && lhs.location == rhs.location;
7487 using ITrackerPtr = std::shared_ptr<ITracker>;
7494 m_nameAndLocation(nameAndLoc)
7499 return m_nameAndLocation;
7505 virtual bool isComplete()
const = 0;
7506 virtual bool isSuccessfullyCompleted()
const = 0;
7507 virtual bool isOpen()
const = 0;
7508 virtual bool hasChildren()
const = 0;
7509 virtual bool hasStarted()
const = 0;
7514 virtual void close() = 0;
7515 virtual void fail() = 0;
7516 virtual void markAsNeedingAnotherRun() = 0;
7518 virtual void addChild( ITrackerPtr
const& child ) = 0;
7519 virtual ITrackerPtr findChild(
NameAndLocation const& nameAndLocation ) = 0;
7520 virtual void openChild() = 0;
7523 virtual bool isSectionTracker()
const = 0;
7524 virtual bool isGeneratorTracker()
const = 0;
7535 ITrackerPtr m_rootTracker;
7536 ITracker* m_currentTracker =
nullptr;
7537 RunState m_runState = NotStarted;
7545 void completeCycle();
7547 bool completedCycle()
const;
7549 void setCurrentTracker(
ITracker* tracker );
7559 CompletedSuccessfully,
7563 using Children = std::vector<ITrackerPtr>;
7566 Children m_children;
7567 CycleState m_runState = NotStarted;
7572 bool isComplete()
const override;
7573 bool isSuccessfullyCompleted()
const override;
7574 bool isOpen()
const override;
7575 bool hasChildren()
const override;
7576 bool hasStarted()
const override {
7577 return m_runState != NotStarted;
7580 void addChild( ITrackerPtr
const& child )
override;
7582 ITrackerPtr findChild(
NameAndLocation const& nameAndLocation )
override;
7585 void openChild()
override;
7587 bool isSectionTracker()
const override;
7588 bool isGeneratorTracker()
const override;
7592 void close()
override;
7593 void fail()
override;
7594 void markAsNeedingAnotherRun()
override;
7597 void moveToParent();
7602 std::vector<std::string> m_filters;
7603 std::string m_trimmed_name;
7607 bool isSectionTracker()
const override;
7609 bool isComplete()
const override;
7615 void addInitialFilters( std::vector<std::string>
const& filters );
7616 void addNextFilters( std::vector<std::string>
const& filters );
7645 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7650 #if defined(CATCH_CONFIG_USE_ASYNC)
7655 double erf_inv(
double x) {
7659 w = -log((1.0 - x) * (1.0 + x));
7663 p = -3.6444120640178196996e-21;
7664 p = -1.685059138182016589e-19 + p * w;
7665 p = 1.2858480715256400167e-18 + p * w;
7666 p = 1.115787767802518096e-17 + p * w;
7667 p = -1.333171662854620906e-16 + p * w;
7668 p = 2.0972767875968561637e-17 + p * w;
7669 p = 6.6376381343583238325e-15 + p * w;
7670 p = -4.0545662729752068639e-14 + p * w;
7671 p = -8.1519341976054721522e-14 + p * w;
7672 p = 2.6335093153082322977e-12 + p * w;
7673 p = -1.2975133253453532498e-11 + p * w;
7674 p = -5.4154120542946279317e-11 + p * w;
7675 p = 1.051212273321532285e-09 + p * w;
7676 p = -4.1126339803469836976e-09 + p * w;
7677 p = -2.9070369957882005086e-08 + p * w;
7678 p = 4.2347877827932403518e-07 + p * w;
7679 p = -1.3654692000834678645e-06 + p * w;
7680 p = -1.3882523362786468719e-05 + p * w;
7681 p = 0.0001867342080340571352 + p * w;
7682 p = -0.00074070253416626697512 + p * w;
7683 p = -0.0060336708714301490533 + p * w;
7684 p = 0.24015818242558961693 + p * w;
7685 p = 1.6536545626831027356 + p * w;
7686 }
else if (w < 16.000000) {
7687 w = sqrt(w) - 3.250000;
7688 p = 2.2137376921775787049e-09;
7689 p = 9.0756561938885390979e-08 + p * w;
7690 p = -2.7517406297064545428e-07 + p * w;
7691 p = 1.8239629214389227755e-08 + p * w;
7692 p = 1.5027403968909827627e-06 + p * w;
7693 p = -4.013867526981545969e-06 + p * w;
7694 p = 2.9234449089955446044e-06 + p * w;
7695 p = 1.2475304481671778723e-05 + p * w;
7696 p = -4.7318229009055733981e-05 + p * w;
7697 p = 6.8284851459573175448e-05 + p * w;
7698 p = 2.4031110387097893999e-05 + p * w;
7699 p = -0.0003550375203628474796 + p * w;
7700 p = 0.00095328937973738049703 + p * w;
7701 p = -0.0016882755560235047313 + p * w;
7702 p = 0.0024914420961078508066 + p * w;
7703 p = -0.0037512085075692412107 + p * w;
7704 p = 0.005370914553590063617 + p * w;
7705 p = 1.0052589676941592334 + p * w;
7706 p = 3.0838856104922207635 + p * w;
7708 w = sqrt(w) - 5.000000;
7709 p = -2.7109920616438573243e-11;
7710 p = -2.5556418169965252055e-10 + p * w;
7711 p = 1.5076572693500548083e-09 + p * w;
7712 p = -3.7894654401267369937e-09 + p * w;
7713 p = 7.6157012080783393804e-09 + p * w;
7714 p = -1.4960026627149240478e-08 + p * w;
7715 p = 2.9147953450901080826e-08 + p * w;
7716 p = -6.7711997758452339498e-08 + p * w;
7717 p = 2.2900482228026654717e-07 + p * w;
7718 p = -9.9298272942317002539e-07 + p * w;
7719 p = 4.5260625972231537039e-06 + p * w;
7720 p = -1.9681778105531670567e-05 + p * w;
7721 p = 7.5995277030017761139e-05 + p * w;
7722 p = -0.00021503011930044477347 + p * w;
7723 p = -0.00013871931833623122026 + p * w;
7724 p = 1.0103004648645343977 + p * w;
7725 p = 4.8499064014085844221 + p * w;
7730 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7731 auto m = Catch::Benchmark::Detail::mean(first, last);
7732 double variance = std::accumulate(first, last, 0., [m](
double a,
double b) {
7733 double diff = b - m;
7734 return a + diff * diff;
7735 }) / (last - first);
7736 return std::sqrt(variance);
7742 namespace Benchmark {
7745 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7746 auto count = last - first;
7747 double idx = (count - 1) * k / static_cast<double>(q);
7748 int j =
static_cast<int>(idx);
7750 std::nth_element(first, first + j, last);
7752 if (g == 0)
return xj;
7754 auto xj1 = *std::min_element(first + (j + 1), last);
7755 return xj + g * (xj1 - xj);
7758 double erfc_inv(
double x) {
7759 return erf_inv(1.0 - x);
7762 double normal_quantile(
double p) {
7763 static const double ROOT_TWO = std::sqrt(2.0);
7765 double result = 0.0;
7766 assert(p >= 0 && p <= 1);
7767 if (p < 0 || p > 1) {
7771 result = -erfc_inv(2.0 * p);
7778 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7779 double sb = stddev.point;
7780 double mn = mean.point / n;
7781 double mg_min = mn / 2.;
7782 double sg = std::min(mg_min / 4., sb / std::sqrt(n));
7783 double sg2 = sg * sg;
7784 double sb2 = sb * sb;
7786 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7790 double k0 = -n * nd;
7791 double k1 = sb2 - n * sg2 + nd;
7792 double det = k1 * k1 - 4 * sg2 * k0;
7793 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7796 auto var_out = [n, sb2, sg2](
double c) {
7798 return (nc / n) * (sb2 - nc * sg2);
7801 return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
7804 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7805 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7806 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7807 static std::random_device entropy;
7808 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7810 auto n =
static_cast<int>(last - first);
7812 auto mean = &Detail::mean<std::vector<double>::iterator>;
7813 auto stddev = &standard_deviation;
7815 #if defined(CATCH_CONFIG_USE_ASYNC)
7816 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7817 auto seed = entropy();
7818 return std::async(std::launch::async, [=] {
7819 std::mt19937 rng(seed);
7820 auto resampled = resample(rng, n_resamples, first, last, f);
7821 return bootstrap(confidence_level, first, last, resampled, f);
7825 auto mean_future = Estimate(mean);
7826 auto stddev_future = Estimate(stddev);
7828 auto mean_estimate = mean_future.get();
7829 auto stddev_estimate = stddev_future.get();
7831 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7832 auto seed = entropy();
7833 std::mt19937 rng(seed);
7834 auto resampled = resample(rng, n_resamples, first, last, f);
7835 return bootstrap(confidence_level, first, last, resampled, f);
7838 auto mean_estimate = Estimate(mean);
7839 auto stddev_estimate = Estimate(stddev);
7842 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7844 return { mean_estimate, stddev_estimate, outlier_variance };
7861 bool marginComparison(
double lhs,
double rhs,
double margin) {
7862 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7870 Approx::Approx (
double value )
7871 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7877 Approx Approx::custom() {
7881 Approx Approx::operator-()
const {
7883 temp.m_value = -temp.m_value;
7887 std::string Approx::toString()
const {
7888 ReusableStringStream rss;
7889 rss <<
"Approx( " << ::Catch::Detail::stringify( m_value ) <<
" )";
7893 bool Approx::equalityComparisonImpl(
const double other)
const {
7896 return marginComparison(m_value, other, m_margin)
7897 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7900 void Approx::setMargin(
double newMargin) {
7901 CATCH_ENFORCE(newMargin >= 0,
7902 "Invalid Approx::margin: " << newMargin <<
'.'
7903 <<
" Approx::Margin has to be non-negative.");
7904 m_margin = newMargin;
7907 void Approx::setEpsilon(
double newEpsilon) {
7908 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7909 "Invalid Approx::epsilon: " << newEpsilon <<
'.'
7910 <<
" Approx::epsilon has to be in [0, 1]");
7911 m_epsilon = newEpsilon;
7916 namespace literals {
7917 Detail::Approx
operator "" _a(
long double val) {
7918 return Detail::Approx(val);
7920 Detail::Approx
operator "" _a(
unsigned long long val) {
7921 return Detail::Approx(val);
7926 return value.toString();
7936 bool isDebuggerActive();
7939 #ifdef CATCH_PLATFORM_MAC
7941 #if defined(__i386__) || defined(__x86_64__)
7942 #define CATCH_TRAP() __asm__("int $3\n" : : )
7943 #elif defined(__aarch64__)
7944 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7947 #elif defined(CATCH_PLATFORM_IPHONE)
7950 #if defined(__i386__) || defined(__x86_64__)
7951 #define CATCH_TRAP() __asm__("int $3")
7952 #elif defined(__aarch64__)
7953 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7954 #elif defined(__arm__) && !defined(__thumb__)
7955 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7956 #elif defined(__arm__) && defined(__thumb__)
7957 #define CATCH_TRAP() __asm__(".inst 0xde01")
7960 #elif defined(CATCH_PLATFORM_LINUX)
7964 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7965 #define CATCH_TRAP() asm volatile ("int $3")
7969 #define CATCH_TRAP() raise(SIGTRAP)
7971 #elif defined(_MSC_VER)
7972 #define CATCH_TRAP() __debugbreak()
7973 #elif defined(__MINGW32__)
7974 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7975 #define CATCH_TRAP() DebugBreak()
7978 #ifndef CATCH_BREAK_INTO_DEBUGGER
7980 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7982 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7994 #if defined(CATCH_PLATFORM_WINDOWS)
7996 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
7997 # define CATCH_DEFINED_NOMINMAX
8000 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
8001 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
8002 # define WIN32_LEAN_AND_MEAN
8008 #include <windows.h>
8011 #ifdef CATCH_DEFINED_NOMINMAX
8014 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
8015 # undef WIN32_LEAN_AND_MEAN
8021 #if defined( CATCH_CONFIG_WINDOWS_SEH )
8027 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
8029 static void reset();
8034 static ULONG guaranteeSize;
8035 static PVOID exceptionHandlerHandle;
8040 #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
8046 struct FatalConditionHandler {
8049 static struct sigaction oldSigActions[];
8050 static stack_t oldSigStack;
8051 static char altStackMem[];
8053 static void handleSignal(
int sig );
8055 FatalConditionHandler();
8056 ~FatalConditionHandler();
8057 static void reset();
8065 struct FatalConditionHandler {
8077 struct IMutableContext;
8087 explicit RunContext( IConfigPtr
const& _config, IStreamingReporterPtr&& reporter );
8091 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8092 void testGroupEnded( std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8096 IConfigPtr config()
const;
8108 ResultWas::OfType resultType,
8111 void handleUnexpectedExceptionNotThrown
8114 void handleUnexpectedInflightException
8116 std::string
const& message,
8118 void handleIncomplete
8122 ResultWas::OfType resultType,
8125 bool sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions )
override;
8128 void sectionEndedEarly(
SectionEndInfo const& endInfo )
override;
8132 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8133 void benchmarkPreparing( std::string
const& name )
override;
8134 void benchmarkStarting(
BenchmarkInfo const& info )
override;
8136 void benchmarkFailed( std::string
const& error )
override;
8139 void pushScopedMessage(
MessageInfo const& message )
override;
8140 void popScopedMessage(
MessageInfo const& message )
override;
8142 void emplaceUnscopedMessage(
MessageBuilder const& builder )
override;
8144 std::string getCurrentTestName()
const override;
8148 void exceptionEarlyReported()
override;
8150 void handleFatalErrorCondition(
StringRef message )
override;
8152 bool lastAssertionPassed()
override;
8154 void assertionPassed()
override;
8158 bool aborting()
const final;
8162 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8163 void invokeActiveTestCase();
8165 void resetAssertionInfo();
8166 bool testForMissingAssertions(
Counts& assertions );
8171 ResultWas::OfType resultType,
8179 void handleUnfinishedSections();
8183 TestCase const* m_activeTestCase =
nullptr;
8184 ITracker* m_testCaseTracker =
nullptr;
8187 IConfigPtr m_config;
8189 IStreamingReporterPtr m_reporter;
8190 std::vector<MessageInfo> m_messages;
8191 std::vector<ScopedMessage> m_messageScopes;
8193 std::vector<SectionEndInfo> m_unfinishedSections;
8194 std::vector<ITracker*> m_activeSections;
8196 bool m_lastAssertionPassed =
false;
8197 bool m_shouldReportUnexpected =
true;
8198 bool m_includeSuccessfulResults;
8201 void seedRng(
IConfig const& config);
8202 unsigned int rngSeed();
8210 expr.streamReconstructedExpression( os );
8215 LazyExpression::LazyExpression(
bool isNegated )
8216 : m_isNegated( isNegated )
8219 LazyExpression::LazyExpression( LazyExpression
const& other ) : m_isNegated( other.m_isNegated ) {}
8221 LazyExpression::operator bool()
const {
8222 return m_transientExpression !=
nullptr;
8225 auto operator << ( std::ostream& os, LazyExpression
const& lazyExpr ) -> std::ostream& {
8226 if( lazyExpr.m_isNegated )
8230 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8231 os <<
"(" << *lazyExpr.m_transientExpression <<
")";
8233 os << *lazyExpr.m_transientExpression;
8236 os <<
"{** error - unchecked empty expression requested **}";
8241 AssertionHandler::AssertionHandler
8242 ( StringRef
const& macroName,
8243 SourceLineInfo
const& lineInfo,
8244 StringRef capturedExpression,
8245 ResultDisposition::Flags resultDisposition )
8246 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8247 m_resultCapture( getResultCapture() )
8250 void AssertionHandler::handleExpr( ITransientExpression
const& expr ) {
8251 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8253 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef
const& message) {
8254 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8257 auto AssertionHandler::allowThrows() const ->
bool {
8258 return getCurrentContext().getConfig()->allowThrows();
8261 void AssertionHandler::complete() {
8263 if( m_reaction.shouldDebugBreak ) {
8269 CATCH_BREAK_INTO_DEBUGGER();
8271 if (m_reaction.shouldThrow) {
8272 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8275 CATCH_ERROR(
"Test failure requires aborting test!" );
8279 void AssertionHandler::setCompleted() {
8283 void AssertionHandler::handleUnexpectedInflightException() {
8284 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8287 void AssertionHandler::handleExceptionThrownAsExpected() {
8288 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8290 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8291 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8294 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8295 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8298 void AssertionHandler::handleThrowingCallSkipped() {
8299 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8304 void handleExceptionMatchExpr( AssertionHandler& handler, std::string
const& str, StringRef
const& matcherString ) {
8305 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8313 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression
const & _lazyExpression):
8314 lazyExpression(_lazyExpression),
8315 resultType(_resultType) {}
8317 std::string AssertionResultData::reconstructExpression()
const {
8319 if( reconstructedExpression.empty() ) {
8320 if( lazyExpression ) {
8321 ReusableStringStream rss;
8322 rss << lazyExpression;
8323 reconstructedExpression = rss.str();
8326 return reconstructedExpression;
8329 AssertionResult::AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data )
8331 m_resultData( data )
8335 bool AssertionResult::succeeded()
const {
8336 return Catch::isOk( m_resultData.resultType );
8340 bool AssertionResult::isOk()
const {
8341 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8344 ResultWas::OfType AssertionResult::getResultType()
const {
8345 return m_resultData.resultType;
8348 bool AssertionResult::hasExpression()
const {
8349 return !m_info.capturedExpression.empty();
8352 bool AssertionResult::hasMessage()
const {
8353 return !m_resultData.message.empty();
8356 std::string AssertionResult::getExpression()
const {
8358 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8359 if (isFalseTest(m_info.resultDisposition)) {
8362 expr += m_info.capturedExpression;
8363 if (isFalseTest(m_info.resultDisposition)) {
8369 std::string AssertionResult::getExpressionInMacro()
const {
8371 if( m_info.macroName.empty() )
8372 expr =
static_cast<std::string
>(m_info.capturedExpression);
8374 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8375 expr += m_info.macroName;
8377 expr += m_info.capturedExpression;
8383 bool AssertionResult::hasExpandedExpression()
const {
8384 return hasExpression() && getExpandedExpression() != getExpression();
8387 std::string AssertionResult::getExpandedExpression()
const {
8388 std::string expr = m_resultData.reconstructExpression();
8394 std::string AssertionResult::getMessage()
const {
8395 return m_resultData.message;
8397 SourceLineInfo AssertionResult::getSourceInfo()
const {
8398 return m_info.lineInfo;
8401 StringRef AssertionResult::getTestMacroName()
const {
8402 return m_info.macroName;
8411 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8416 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher
const& matcher, StringRef
const& matcherString ) {
8417 std::string exceptionMessage = Catch::translateActiveException();
8418 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8419 handler.handleExpr( expr );
8431 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8432 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8433 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8435 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8438 #pragma clang diagnostic push
8439 #pragma clang diagnostic ignored "-Wweak-vtables"
8440 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8441 #pragma clang diagnostic ignored "-Wshadow"
8455 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8456 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8459 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8460 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8463 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8464 #ifdef __has_include
8465 #if __has_include(<optional>) && __cplusplus >= 201703L
8467 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8489 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8490 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8495 namespace TextFlow {
8497 inline auto isWhitespace(
char c) ->
bool {
8498 static std::string chars =
" \t\n\r";
8499 return chars.find(c) != std::string::npos;
8501 inline auto isBreakableBefore(
char c) ->
bool {
8502 static std::string chars =
"[({<|";
8503 return chars.find(c) != std::string::npos;
8505 inline auto isBreakableAfter(
char c) ->
bool {
8506 static std::string chars =
"])}>.,:;*+-=&/\\";
8507 return chars.find(c) != std::string::npos;
8513 std::vector<std::string> m_strings;
8514 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8515 size_t m_indent = 0;
8516 size_t m_initialIndent = std::string::npos;
8523 size_t m_stringIndex = 0;
8528 bool m_suffix =
false;
8532 m_stringIndex(stringIndex) {}
8534 auto line()
const -> std::string
const& {
return m_column.m_strings[m_stringIndex]; }
8536 auto isBoundary(
size_t at)
const ->
bool {
8538 assert(at <= line().size());
8540 return at == line().size() ||
8541 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8542 isBreakableBefore(line()[at]) ||
8543 isBreakableAfter(line()[at - 1]);
8547 assert(m_stringIndex < m_column.m_strings.size());
8550 auto width = m_column.m_width - indent();
8552 if (line()[m_pos] ==
'\n') {
8555 while (m_end < line().size() && line()[m_end] !=
'\n')
8558 if (m_end < m_pos + width) {
8559 m_len = m_end - m_pos;
8562 while (len > 0 && !isBoundary(m_pos + len))
8564 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8576 auto indent()
const ->
size_t {
8577 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8578 return initial == std::string::npos ? m_column.m_indent : initial;
8581 auto addIndentAndSuffix(std::string
const &plain)
const -> std::string {
8582 return std::string(indent(),
' ') + (m_suffix ? plain +
"-" : plain);
8586 using difference_type = std::ptrdiff_t;
8587 using value_type = std::string;
8588 using pointer = value_type * ;
8589 using reference = value_type & ;
8590 using iterator_category = std::forward_iterator_tag;
8593 assert(m_column.m_width > m_column.m_indent);
8594 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8600 auto operator *()
const -> std::string {
8601 assert(m_stringIndex < m_column.m_strings.size());
8602 assert(m_pos <= m_end);
8603 return addIndentAndSuffix(line().substr(m_pos, m_len));
8608 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8611 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8614 if (m_pos == line().size()) {
8618 if (m_stringIndex < m_column.m_strings.size())
8622 auto operator ++(
int) ->
iterator {
8628 auto operator ==(
iterator const& other)
const ->
bool {
8630 m_pos == other.m_pos &&
8631 m_stringIndex == other.m_stringIndex &&
8632 &m_column == &other.m_column;
8634 auto operator !=(
iterator const& other)
const ->
bool {
8635 return !operator==(other);
8640 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8642 auto width(
size_t newWidth) ->
Column& {
8643 assert(newWidth > 0);
8647 auto indent(
size_t newIndent) ->
Column& {
8648 m_indent = newIndent;
8651 auto initialIndent(
size_t newIndent) ->
Column& {
8652 m_initialIndent = newIndent;
8656 auto width() const ->
size_t {
return m_width; }
8657 auto begin() const -> iterator {
return iterator(*
this); }
8658 auto end() const -> iterator {
return { *
this, m_strings.size() }; }
8660 inline friend std::ostream& operator << (std::ostream& os, Column
const& col) {
8662 for (
auto line : col) {
8672 auto operator + (Column
const& other)->Columns;
8674 auto toString() const -> std::
string {
8675 std::ostringstream oss;
8690 std::vector<Column> m_columns;
8698 std::vector<Column>
const& m_columns;
8699 std::vector<Column::iterator> m_iterators;
8700 size_t m_activeIterators;
8703 : m_columns(columns.m_columns),
8704 m_activeIterators(0) {
8705 m_iterators.reserve(m_columns.size());
8707 for (
auto const& col : m_columns)
8708 m_iterators.push_back(col.end());
8712 using difference_type = std::ptrdiff_t;
8713 using value_type = std::string;
8714 using pointer = value_type * ;
8715 using reference = value_type & ;
8716 using iterator_category = std::forward_iterator_tag;
8719 : m_columns(columns.m_columns),
8720 m_activeIterators(m_columns.size()) {
8721 m_iterators.reserve(m_columns.size());
8723 for (
auto const& col : m_columns)
8724 m_iterators.push_back(col.begin());
8727 auto operator ==(
iterator const& other)
const ->
bool {
8728 return m_iterators == other.m_iterators;
8730 auto operator !=(
iterator const& other)
const ->
bool {
8731 return m_iterators != other.m_iterators;
8733 auto operator *()
const -> std::string {
8734 std::string row, padding;
8736 for (
size_t i = 0; i < m_columns.size(); ++i) {
8737 auto width = m_columns[i].width();
8738 if (m_iterators[i] != m_columns[i].end()) {
8739 std::string col = *m_iterators[i];
8740 row += padding + col;
8741 if (col.size() < width)
8742 padding = std::string(width - col.size(),
' ');
8746 padding += std::string(width,
' ');
8752 for (
size_t i = 0; i < m_columns.size(); ++i) {
8753 if (m_iterators[i] != m_columns[i].end())
8758 auto operator ++(
int) ->
iterator {
8767 auto end() const -> iterator {
return { *
this, iterator::EndTag() }; }
8770 m_columns.push_back(col);
8773 auto operator + (Column
const& col) -> Columns {
8774 Columns combined = *
this;
8779 inline friend std::ostream& operator << (std::ostream& os, Columns
const& cols) {
8782 for (
auto line : cols) {
8792 auto toString() const -> std::
string {
8793 std::ostringstream oss;
8799 inline auto Column::operator + (Column
const& other) -> Columns {
8817 #include <algorithm>
8819 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8820 #define CATCH_PLATFORM_WINDOWS
8823 namespace Catch {
namespace clara {
8827 template<
typename L>
8830 template<
typename ClassT,
typename ReturnT,
typename...
Args>
8832 static const bool isValid =
false;
8835 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8837 static const bool isValid =
true;
8838 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8839 using ReturnType = ReturnT;
8847 std::string m_exeName;
8848 std::vector<std::string> m_args;
8851 Args(
int argc,
char const*
const* argv )
8852 : m_exeName(argv[0]),
8853 m_args(argv + 1, argv + argc) {}
8855 Args( std::initializer_list<std::string> args )
8856 : m_exeName( *args.begin() ),
8857 m_args( args.begin()+1, args.end() )
8860 auto exeName()
const -> std::string {
8867 enum class TokenType {
8875 inline auto isOptPrefix(
char c ) ->
bool {
8877 #ifdef CATCH_PLATFORM_WINDOWS
8885 using Iterator = std::vector<std::string>::const_iterator;
8888 std::vector<Token> m_tokenBuffer;
8891 m_tokenBuffer.resize( 0 );
8894 while( it != itEnd && it->empty() )
8898 auto const &next = *it;
8899 if( isOptPrefix( next[0] ) ) {
8900 auto delimiterPos = next.find_first_of(
" :=" );
8901 if( delimiterPos != std::string::npos ) {
8902 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8903 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8905 if( next[1] !=
'-' && next.size() > 2 ) {
8906 std::string opt =
"- ";
8907 for(
size_t i = 1; i < next.size(); ++i ) {
8909 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8912 m_tokenBuffer.push_back( { TokenType::Option, next } );
8916 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8924 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8928 explicit operator bool()
const {
8929 return !m_tokenBuffer.empty() || it != itEnd;
8932 auto count()
const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8934 auto operator*()
const ->
Token {
8935 assert( !m_tokenBuffer.empty() );
8936 return m_tokenBuffer.front();
8939 auto operator->()
const ->
Token const * {
8940 assert( !m_tokenBuffer.empty() );
8941 return &m_tokenBuffer.front();
8945 if( m_tokenBuffer.size() >= 2 ) {
8946 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8959 Ok, LogicError, RuntimeError
8966 virtual void enforceOk()
const = 0;
8971 template<
typename T>
8974 auto value()
const -> T
const & {
8983 if( m_type == ResultBase::Ok )
8984 new( &m_value ) T( other.m_value );
8988 new( &m_value ) T( value );
8992 if( m_type == ResultBase::Ok )
8994 ResultBase::operator=(other);
8995 if( m_type == ResultBase::Ok )
8996 new( &m_value ) T( other.m_value );
9013 using ResultBase::ResultBase;
9016 template<
typename T =
void>
9019 template<
typename U>
9022 m_errorMessage( other.errorMessage() )
9024 assert( type() != ResultBase::Ok );
9027 template<
typename U>
9028 static auto ok( U
const &value ) ->
BasicResult {
return { ResultBase::Ok, value }; }
9029 static auto ok() ->
BasicResult {
return { ResultBase::Ok }; }
9030 static auto logicError( std::string
const &message ) ->
BasicResult {
return { ResultBase::LogicError, message }; }
9031 static auto runtimeError( std::string
const &message ) ->
BasicResult {
return { ResultBase::RuntimeError, message }; }
9033 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9034 auto type()
const -> ResultBase::Type {
return m_type; }
9035 auto errorMessage()
const -> std::string {
return m_errorMessage; }
9038 void enforceOk()
const override {
9042 assert( m_type != ResultBase::LogicError );
9043 assert( m_type != ResultBase::RuntimeError );
9044 if( m_type != ResultBase::Ok )
9048 std::string m_errorMessage;
9050 BasicResult( ResultBase::Type type, std::string
const &message )
9052 m_errorMessage(message)
9054 assert( m_type != ResultBase::Ok );
9058 using ResultBase::m_type;
9061 enum class ParseResultType {
9062 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9070 m_remainingTokens( remainingTokens )
9073 auto type()
const -> ParseResultType {
return m_type; }
9074 auto remainingTokens()
const ->
TokenStream {
return m_remainingTokens; }
9077 ParseResultType m_type;
9090 template<
typename T>
9091 inline auto convertInto( std::string
const &source, T& target ) ->
ParserResult {
9092 std::stringstream ss;
9096 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9098 return ParserResult::ok( ParseResultType::Matched );
9100 inline auto convertInto( std::string
const &source, std::string& target ) -> ParserResult {
9102 return ParserResult::ok( ParseResultType::Matched );
9104 inline auto convertInto( std::string
const &source,
bool &target ) -> ParserResult {
9105 std::string srcLC = source;
9106 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9107 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9109 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9112 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9113 return ParserResult::ok( ParseResultType::Matched );
9115 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9116 template<
typename T>
9117 inline auto convertInto( std::string
const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9119 auto result = convertInto( source, temp );
9121 target = std::move(temp);
9136 virtual auto isContainer()
const ->
bool {
return false; }
9137 virtual auto isFlag()
const ->
bool {
return false; }
9140 virtual auto setValue( std::string
const &arg ) ->
ParserResult = 0;
9144 virtual auto isFlag()
const ->
bool {
return true; }
9147 template<
typename T>
9153 auto setValue( std::string
const &arg ) ->
ParserResult override {
9154 return convertInto( arg, m_ref );
9158 template<
typename T>
9160 std::vector<T> &m_ref;
9162 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9164 auto isContainer()
const ->
bool override {
return true; }
9166 auto setValue( std::string
const &arg ) ->
ParserResult override {
9168 auto result = convertInto( arg, temp );
9170 m_ref.push_back( temp );
9182 return ParserResult::ok( ParseResultType::Matched );
9186 template<
typename ReturnType>
9188 static_assert( std::is_same<ReturnType, ParserResult>::value,
"Lambda must return void or clara::ParserResult" );
9190 template<
typename L,
typename ArgType>
9191 static auto invoke( L
const &lambda, ArgType
const &arg ) ->
ParserResult {
9192 return lambda( arg );
9198 template<
typename L,
typename ArgType>
9199 static auto invoke( L
const &lambda, ArgType
const &arg ) ->
ParserResult {
9201 return ParserResult::ok( ParseResultType::Matched );
9205 template<
typename ArgType,
typename L>
9206 inline auto invokeLambda( L
const &lambda, std::string
const &arg ) ->
ParserResult {
9208 auto result = convertInto( arg, temp );
9211 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9214 template<
typename L>
9219 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9221 auto setValue( std::string
const &arg ) ->
ParserResult override {
9222 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9226 template<
typename L>
9240 enum class Optionality { Optional, Required };
9247 virtual auto validate()
const ->
Result {
return Result::ok(); }
9249 virtual auto cardinality()
const ->
size_t {
return 1; }
9252 return parse( args.exeName(),
TokenStream( args ) );
9256 template<
typename DerivedT>
9259 template<
typename T>
9260 auto operator|( T
const &other )
const ->
Parser;
9262 template<
typename T>
9263 auto operator+( T
const &other )
const ->
Parser;
9267 template<
typename DerivedT>
9270 Optionality m_optionality = Optionality::Optional;
9271 std::shared_ptr<BoundRef> m_ref;
9273 std::string m_description;
9275 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &ref ) : m_ref( ref ) {}
9278 template<
typename T>
9284 template<
typename LambdaT>
9285 ParserRefImpl( LambdaT
const &ref, std::string
const &hint )
9290 auto operator()( std::string
const &description ) -> DerivedT & {
9291 m_description = description;
9292 return static_cast<DerivedT &
>( *this );
9295 auto optional() -> DerivedT & {
9296 m_optionality = Optionality::Optional;
9297 return static_cast<DerivedT &
>( *this );
9300 auto required() -> DerivedT & {
9301 m_optionality = Optionality::Required;
9302 return static_cast<DerivedT &
>( *this );
9305 auto isOptional()
const ->
bool {
9306 return m_optionality == Optionality::Optional;
9309 auto cardinality()
const ->
size_t override {
9310 if( m_ref->isContainer() )
9316 auto hint()
const -> std::string {
return m_hint; }
9320 std::shared_ptr<std::string> m_name;
9321 std::shared_ptr<BoundValueRefBase> m_ref;
9323 template<
typename LambdaT>
9324 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9325 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9329 ExeName() : m_name( std::make_shared<std::string>(
"<executable>" ) ) {}
9332 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9335 template<
typename LambdaT>
9337 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9342 return InternalParseResult::ok(
ParseState( ParseResultType::NoMatch, tokens ) );
9345 auto name()
const -> std::string {
return *m_name; }
9346 auto set( std::string
const& newName ) ->
ParserResult {
9348 auto lastSlash = newName.find_last_of(
"\\/" );
9349 auto filename = ( lastSlash == std::string::npos )
9351 : newName.substr( lastSlash+1 );
9355 return m_ref->setValue( filename );
9357 return ParserResult::ok( ParseResultType::Matched );
9363 using ParserRefImpl::ParserRefImpl;
9366 auto validationResult = validate();
9367 if( !validationResult )
9370 auto remainingTokens = tokens;
9371 auto const &token = *remainingTokens;
9372 if( token.type != TokenType::Argument )
9373 return InternalParseResult::ok(
ParseState( ParseResultType::NoMatch, remainingTokens ) );
9375 assert( !m_ref->isFlag() );
9378 auto result = valueRef->setValue( remainingTokens->token );
9382 return InternalParseResult::ok(
ParseState( ParseResultType::Matched, ++remainingTokens ) );
9386 inline auto normaliseOpt( std::string
const &optName ) -> std::string {
9387 #ifdef CATCH_PLATFORM_WINDOWS
9388 if( optName[0] ==
'/' )
9389 return "-" + optName.substr( 1 );
9397 std::vector<std::string> m_optNames;
9400 template<
typename LambdaT>
9403 explicit Opt(
bool &ref ) :
ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9405 template<
typename LambdaT>
9406 Opt( LambdaT
const &ref, std::string
const &hint ) :
ParserRefImpl( ref, hint ) {}
9408 template<
typename T>
9411 auto operator[]( std::string
const &optName ) ->
Opt & {
9412 m_optNames.push_back( optName );
9416 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9417 std::ostringstream oss;
9419 for(
auto const &opt : m_optNames ) {
9426 if( !m_hint.empty() )
9427 oss <<
" <" << m_hint <<
">";
9428 return { { oss.str(), m_description } };
9431 auto isMatch( std::string
const &optToken )
const ->
bool {
9432 auto normalisedToken = normaliseOpt( optToken );
9433 for(
auto const &name : m_optNames ) {
9434 if( normaliseOpt( name ) == normalisedToken )
9440 using ParserBase::parse;
9443 auto validationResult = validate();
9444 if( !validationResult )
9447 auto remainingTokens = tokens;
9448 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9449 auto const &token = *remainingTokens;
9450 if( isMatch(token.token ) ) {
9451 if( m_ref->isFlag() ) {
9453 auto result = flagRef->setFlag(
true );
9456 if( result.value() == ParseResultType::ShortCircuitAll )
9457 return InternalParseResult::ok(
ParseState( result.value(), remainingTokens ) );
9461 if( !remainingTokens )
9462 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9463 auto const &argToken = *remainingTokens;
9464 if( argToken.type != TokenType::Argument )
9465 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9466 auto result = valueRef->setValue( argToken.token );
9469 if( result.value() == ParseResultType::ShortCircuitAll )
9470 return InternalParseResult::ok(
ParseState( result.value(), remainingTokens ) );
9472 return InternalParseResult::ok(
ParseState( ParseResultType::Matched, ++remainingTokens ) );
9475 return InternalParseResult::ok(
ParseState( ParseResultType::NoMatch, remainingTokens ) );
9478 auto validate()
const ->
Result override {
9479 if( m_optNames.empty() )
9480 return Result::logicError(
"No options supplied to Opt" );
9481 for(
auto const &name : m_optNames ) {
9483 return Result::logicError(
"Option name cannot be empty" );
9484 #ifdef CATCH_PLATFORM_WINDOWS
9485 if( name[0] !=
'-' && name[0] !=
'/' )
9486 return Result::logicError(
"Option name must begin with '-' or '/'" );
9488 if( name[0] !=
'-' )
9489 return Result::logicError(
"Option name must begin with '-'" );
9492 return ParserRefImpl::validate();
9497 Help(
bool &showHelpFlag )
9498 :
Opt([&](
bool flag ) {
9499 showHelpFlag = flag;
9500 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9503 static_cast<Opt &
>( *this )
9504 (
"display usage information")
9505 [
"-?"][
"-h"][
"--help"]
9513 std::vector<Opt> m_options;
9514 std::vector<Arg> m_args;
9517 m_exeName = exeName;
9521 auto operator|=(
Arg const &arg ) ->
Parser & {
9522 m_args.push_back(arg);
9526 auto operator|=(
Opt const &opt ) ->
Parser & {
9527 m_options.push_back(opt);
9532 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9533 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9537 template<
typename T>
9538 auto operator|( T
const &other )
const ->
Parser {
9539 return Parser( *
this ) |= other;
9543 template<
typename T>
9544 auto operator+=( T
const &other ) ->
Parser & {
return operator|=( other ); }
9545 template<
typename T>
9546 auto operator+( T
const &other )
const ->
Parser {
return operator|( other ); }
9548 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9549 std::vector<HelpColumns> cols;
9550 for (
auto const &o : m_options) {
9551 auto childCols = o.getHelpColumns();
9552 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9557 void writeToStream( std::ostream &os )
const {
9558 if (!m_exeName.name().empty()) {
9559 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9560 bool required =
true, first =
true;
9561 for(
auto const &arg : m_args ) {
9566 if( arg.isOptional() && required ) {
9570 os <<
"<" << arg.hint() <<
">";
9571 if( arg.cardinality() == 0 )
9576 if( !m_options.empty() )
9578 os <<
"\n\nwhere options are:" << std::endl;
9581 auto rows = getHelpColumns();
9582 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9583 size_t optWidth = 0;
9584 for(
auto const &cols : rows )
9585 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9587 optWidth = (std::min)(optWidth, consoleWidth/2);
9589 for(
auto const &cols : rows ) {
9594 os << row << std::endl;
9598 friend auto operator<<( std::ostream &os,
Parser const &parser ) -> std::ostream& {
9599 parser.writeToStream( os );
9603 auto validate()
const ->
Result override {
9604 for(
auto const &opt : m_options ) {
9605 auto result = opt.validate();
9609 for(
auto const &arg : m_args ) {
9610 auto result = arg.validate();
9614 return Result::ok();
9617 using ParserBase::parse;
9625 const size_t totalParsers = m_options.size() + m_args.size();
9626 assert( totalParsers < 512 );
9628 ParserInfo parseInfos[512];
9632 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9633 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9636 m_exeName.set( exeName );
9638 auto result = InternalParseResult::ok(
ParseState( ParseResultType::NoMatch, tokens ) );
9639 while( result.value().remainingTokens() ) {
9640 bool tokenParsed =
false;
9642 for(
size_t i = 0; i < totalParsers; ++i ) {
9643 auto& parseInfo = parseInfos[i];
9644 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9645 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9648 if (result.value().type() != ParseResultType::NoMatch) {
9656 if( result.value().type() == ParseResultType::ShortCircuitAll )
9659 return InternalParseResult::runtimeError(
"Unrecognised token: " + result.value().remainingTokens()->token );
9666 template<
typename DerivedT>
9667 template<
typename T>
9669 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9674 using detail::Parser;
9686 using detail::ExeName;
9692 using detail::ParseResultType;
9695 using detail::ParserResult;
9701 #pragma clang diagnostic pop
9705 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9706 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9707 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9713 clara::Parser makeCommandLineParser( ConfigData& config );
9723 clara::Parser makeCommandLineParser( ConfigData& config ) {
9725 using namespace clara;
9727 auto const setWarning = [&]( std::string
const& warning ) {
9728 auto warningSet = [&]() {
9729 if( warning ==
"NoAssertions" )
9730 return WarnAbout::NoAssertions;
9732 if ( warning ==
"NoTests" )
9733 return WarnAbout::NoTests;
9735 return WarnAbout::Nothing;
9738 if (warningSet == WarnAbout::Nothing)
9739 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9740 config.warnings =
static_cast<WarnAbout::What
>( config.warnings | warningSet );
9741 return ParserResult::ok( ParseResultType::Matched );
9743 auto const loadTestNamesFromFile = [&]( std::string
const& filename ) {
9744 std::ifstream f( filename.c_str() );
9746 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'" );
9749 while( std::getline( f, line ) ) {
9751 if( !line.empty() && !startsWith( line,
'#' ) ) {
9752 if( !startsWith( line,
'"' ) )
9753 line =
'"' + line + '"';
9754 config.testsOrTags.push_back( line );
9755 config.testsOrTags.emplace_back(
"," );
9759 if(!config.testsOrTags.empty())
9760 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9762 return ParserResult::ok( ParseResultType::Matched );
9764 auto const setTestOrder = [&]( std::string
const& order ) {
9765 if( startsWith(
"declared", order ) )
9766 config.runOrder = RunTests::InDeclarationOrder;
9767 else if( startsWith(
"lexical", order ) )
9768 config.runOrder = RunTests::InLexicographicalOrder;
9769 else if( startsWith(
"random", order ) )
9770 config.runOrder = RunTests::InRandomOrder;
9772 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'" );
9773 return ParserResult::ok( ParseResultType::Matched );
9775 auto const setRngSeed = [&]( std::string
const& seed ) {
9776 if( seed !=
"time" )
9777 return clara::detail::convertInto( seed, config.rngSeed );
9778 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9779 return ParserResult::ok( ParseResultType::Matched );
9781 auto const setColourUsage = [&]( std::string
const& useColour ) {
9782 auto mode = toLower( useColour );
9785 config.useColour = UseColour::Yes;
9786 else if( mode ==
"no" )
9787 config.useColour = UseColour::No;
9788 else if( mode ==
"auto" )
9789 config.useColour = UseColour::Auto;
9791 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9792 return ParserResult::ok( ParseResultType::Matched );
9794 auto const setWaitForKeypress = [&]( std::string
const& keypress ) {
9795 auto keypressLc = toLower( keypress );
9796 if (keypressLc ==
"never")
9797 config.waitForKeypress = WaitForKeypress::Never;
9798 else if( keypressLc ==
"start" )
9799 config.waitForKeypress = WaitForKeypress::BeforeStart;
9800 else if( keypressLc ==
"exit" )
9801 config.waitForKeypress = WaitForKeypress::BeforeExit;
9802 else if( keypressLc ==
"both" )
9803 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9805 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9806 return ParserResult::ok( ParseResultType::Matched );
9808 auto const setVerbosity = [&]( std::string
const& verbosity ) {
9809 auto lcVerbosity = toLower( verbosity );
9810 if( lcVerbosity ==
"quiet" )
9811 config.verbosity = Verbosity::Quiet;
9812 else if( lcVerbosity ==
"normal" )
9813 config.verbosity = Verbosity::Normal;
9814 else if( lcVerbosity ==
"high" )
9815 config.verbosity = Verbosity::High;
9817 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9818 return ParserResult::ok( ParseResultType::Matched );
9820 auto const setReporter = [&]( std::string
const& reporter ) {
9821 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
9823 auto lcReporter = toLower( reporter );
9824 auto result = factories.find( lcReporter );
9826 if( factories.end() != result )
9827 config.reporterName = lcReporter;
9829 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9830 return ParserResult::ok( ParseResultType::Matched );
9834 = ExeName( config.processName )
9835 | Help( config.showHelp )
9836 | Opt( config.listTests )
9837 ["-l"]["--list-tests"]
9838 (
"list all/matching test cases" )
9839 | Opt( config.listTags )
9840 ["-t"]["--list-tags"]
9841 (
"list all/matching tags" )
9842 | Opt( config.showSuccessfulTests )
9844 (
"include successful tests in output" )
9845 | Opt( config.shouldDebugBreak )
9847 (
"break into debugger on failure" )
9848 | Opt( config.noThrow )
9850 (
"skip exception tests" )
9851 | Opt( config.showInvisibles )
9852 ["-i"]["--invisibles"]
9853 (
"show invisibles (tabs, newlines)" )
9854 | Opt( config.outputFilename,
"filename" )
9856 (
"output filename" )
9857 | Opt( setReporter,
"name" )
9858 ["-r"]["--reporter"]
9859 (
"reporter to use (defaults to console)" )
9860 | Opt( config.name,
"name" )
9863 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9865 (
"abort at first failure" )
9866 | Opt( [&](
int x ){ config.abortAfter = x; },
"no. failures" )
9868 (
"abort after x failures" )
9869 | Opt( setWarning,
"warning name" )
9871 (
"enable warnings" )
9872 | Opt( [&](
bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; },
"yes|no" )
9873 [
"-d"][
"--durations"]
9874 (
"show test durations" )
9875 | Opt( config.minDuration,
"seconds" )
9876 ["-D"]["--min-duration"]
9877 (
"show test durations for tests taking at least the given number of seconds" )
9878 | Opt( loadTestNamesFromFile,
"filename" )
9879 ["-f"]["--input-file"]
9880 (
"load test names to run from a file" )
9881 | Opt( config.filenamesAsTags )
9882 ["-#"]["--filenames-as-tags"]
9883 (
"adds a tag for the filename" )
9884 | Opt( config.sectionsToRun,
"section name" )
9886 (
"specify section to run" )
9887 | Opt( setVerbosity,
"quiet|normal|high" )
9888 ["-v"]["--verbosity"]
9889 (
"set output verbosity" )
9890 | Opt( config.listTestNamesOnly )
9891 ["--list-test-names-only"]
9892 (
"list all/matching test cases names only" )
9893 | Opt( config.listReporters )
9894 ["--list-reporters"]
9895 (
"list all reporters" )
9896 | Opt( setTestOrder,
"decl|lex|rand" )
9898 (
"test case order (defaults to decl)" )
9899 | Opt( setRngSeed,
"'time'|number" )
9901 (
"set a specific seed for random numbers" )
9902 | Opt( setColourUsage,
"yes|no" )
9904 (
"should output be colourised" )
9905 | Opt( config.libIdentify )
9907 (
"report name and version according to libidentify standard" )
9908 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9909 ["--wait-for-keypress"]
9910 (
"waits for a keypress before exiting" )
9911 | Opt( config.benchmarkSamples,
"samples" )
9912 ["--benchmark-samples"]
9913 (
"number of samples to collect (default: 100)" )
9914 | Opt( config.benchmarkResamples,
"resamples" )
9915 ["--benchmark-resamples"]
9916 (
"number of resamples for the bootstrap (default: 100000)" )
9917 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9918 ["--benchmark-confidence-interval"]
9919 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9920 | Opt( config.benchmarkNoAnalysis )
9921 ["--benchmark-no-analysis"]
9922 (
"perform only measurements; do not perform any analysis" )
9923 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9924 ["--benchmark-warmup-time"]
9925 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9926 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9927 (
"which test or tests to use" );
9941 bool SourceLineInfo::operator == ( SourceLineInfo
const& other )
const noexcept {
9942 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9944 bool SourceLineInfo::operator < ( SourceLineInfo
const& other )
const noexcept {
9947 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9950 std::ostream& operator << ( std::ostream& os, SourceLineInfo
const& info ) {
9952 os << info.file <<
'(' << info.line <<
')';
9954 os << info.file <<
':' << info.line;
9959 std::string StreamEndStop::operator+()
const {
9960 return std::string();
9963 NonCopyable::NonCopyable() =
default;
9964 NonCopyable::~NonCopyable() =
default;
9972 Config::Config( ConfigData
const& data )
9974 m_stream( openStream() )
9980 for (
auto& elem : m_data.testsOrTags) {
9983 for (
auto& elem : m_data.sectionsToRun) {
9987 TestSpecParser parser(ITagAliasRegistry::get());
9988 if (!m_data.testsOrTags.empty()) {
9989 m_hasTestFilters =
true;
9990 for (
auto const& testOrTags : m_data.testsOrTags) {
9991 parser.parse(testOrTags);
9994 m_testSpec = parser.testSpec();
9997 std::string
const& Config::getFilename()
const {
9998 return m_data.outputFilename ;
10001 bool Config::listTests()
const {
return m_data.listTests; }
10002 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
10003 bool Config::listTags()
const {
return m_data.listTags; }
10004 bool Config::listReporters()
const {
return m_data.listReporters; }
10006 std::string Config::getProcessName()
const {
return m_data.processName; }
10007 std::string
const& Config::getReporterName()
const {
return m_data.reporterName; }
10009 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
10010 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
10012 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
10013 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
10015 bool Config::showHelp()
const {
return m_data.showHelp; }
10018 bool Config::allowThrows()
const {
return !m_data.noThrow; }
10019 std::ostream& Config::stream()
const {
return m_stream->stream(); }
10020 std::string Config::name()
const {
return m_data.name.empty() ? m_data.processName : m_data.name; }
10021 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
10022 bool Config::warnAboutMissingAssertions()
const {
return !!(m_data.warnings & WarnAbout::NoAssertions); }
10023 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings & WarnAbout::NoTests); }
10024 ShowDurations::OrNot Config::showDurations()
const {
return m_data.showDurations; }
10025 double Config::minDuration()
const {
return m_data.minDuration; }
10026 RunTests::InWhatOrder Config::runOrder()
const {
return m_data.runOrder; }
10027 unsigned int Config::rngSeed()
const {
return m_data.rngSeed; }
10028 UseColour::YesOrNo Config::useColour()
const {
return m_data.useColour; }
10029 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
10030 int Config::abortAfter()
const {
return m_data.abortAfter; }
10031 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
10032 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
10034 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
10035 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
10036 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
10037 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
10038 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10040 IStream
const* Config::openStream() {
10041 return Catch::makeStream(m_data.outputFilename);
10048 #if defined(__clang__)
10049 # pragma clang diagnostic push
10050 # pragma clang diagnostic ignored "-Wexit-time-destructors"
10075 virtual void use( Colour::Code _colourCode ) = 0;
10079 void use( Colour::Code )
override {}
10083 return &s_instance;
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 )
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;
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();
10163 #elif defined( CATCH_CONFIG_COLOUR_ANSI )
10165 #include <unistd.h>
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" );
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();
10243 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
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();
10270 if (impl !=
nullptr) {
10271 impl->use( _colourCode );
10275 std::ostream& operator << ( std::ostream& os, Colour
const& ) {
10281 #if defined(__clang__)
10282 # pragma clang diagnostic pop
10294 return m_resultCapture;
10296 IRunner* getRunner()
override {
10300 IConfigPtr
const& getConfig()
const override {
10307 void setResultCapture(
IResultCapture* resultCapture )
override {
10308 m_resultCapture = resultCapture;
10310 void setRunner(
IRunner* runner )
override {
10313 void setConfig( IConfigPtr
const& config )
override {
10320 IConfigPtr m_config;
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;
10354 void writeToDebugConsole( std::string
const& text );
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 ) {
10380 Catch::cout() << text;
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__
10399 # include <sys/sysctl.h>
10403 #ifdef __apple_build_version__
10409 bool isDebuggerActive(){
10411 struct kinfo_proc info;
10417 info.kp_proc.p_flag = 0;
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;
10437 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10440 bool isDebuggerActive() {
10447 #elif defined(CATCH_PLATFORM_LINUX)
10459 bool isDebuggerActive(){
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 ) {
10470 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
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; }
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;
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));
10554 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int>
const& values );
10558 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10563 std::vector<StringRef> parseEnums(
StringRef enums );
10576 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
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();
10641 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10642 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10659 std::string translateActiveException()
const override;
10660 std::string tryTranslators()
const;
10663 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
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 {
10687 return tryTranslators();
10689 @catch (NSException *exception) {
10690 return Catch::Detail::stringify( [exception description] );
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());
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!");
10746 #if defined(__GNUC__)
10747 # pragma GCC diagnostic push
10748 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10751 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10755 void reportFatal(
char const *
const message ) {
10756 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10762 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10771 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10772 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10773 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10774 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10777 LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10778 for (
auto const& def : signalDefs) {
10779 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10780 reportFatal(def.name);
10785 return EXCEPTION_CONTINUE_SEARCH;
10788 FatalConditionHandler::FatalConditionHandler() {
10792 guaranteeSize = 32 * 1024;
10793 exceptionHandlerHandle =
nullptr;
10795 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10797 SetThreadStackGuarantee(&guaranteeSize);
10800 void FatalConditionHandler::reset() {
10802 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
10803 SetThreadStackGuarantee(&guaranteeSize);
10804 exceptionHandlerHandle =
nullptr;
10809 FatalConditionHandler::~FatalConditionHandler() {
10813 bool FatalConditionHandler::isSet =
false;
10814 ULONG FatalConditionHandler::guaranteeSize = 0;
10815 PVOID FatalConditionHandler::exceptionHandlerHandle =
nullptr;
10819 #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
10823 struct SignalDefs {
10830 static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
10832 static SignalDefs signalDefs[] = {
10833 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10834 { SIGILL,
"SIGILL - Illegal instruction signal" },
10835 { SIGFPE,
"SIGFPE - Floating point error signal" },
10836 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10837 { SIGTERM,
"SIGTERM - Termination request signal" },
10838 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10841 void FatalConditionHandler::handleSignal(
int sig ) {
10842 char const * name =
"<unknown signal>";
10843 for (
auto const& def : signalDefs) {
10844 if (sig == def.id) {
10854 FatalConditionHandler::FatalConditionHandler() {
10857 sigStack.ss_sp = altStackMem;
10858 sigStack.ss_size = sigStackSize;
10859 sigStack.ss_flags = 0;
10860 sigaltstack(&sigStack, &oldSigStack);
10861 struct sigaction sa = { };
10863 sa.sa_handler = handleSignal;
10864 sa.sa_flags = SA_ONSTACK;
10865 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
10866 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
10870 FatalConditionHandler::~FatalConditionHandler() {
10874 void FatalConditionHandler::reset() {
10877 for( std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i ) {
10878 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10881 sigaltstack(&oldSigStack,
nullptr);
10886 bool FatalConditionHandler::isSet =
false;
10887 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
10888 stack_t FatalConditionHandler::oldSigStack = {};
10889 char FatalConditionHandler::altStackMem[sigStackSize] = {};
10896 void FatalConditionHandler::reset() {}
10901 #if defined(__GNUC__)
10902 # pragma GCC diagnostic pop
10912 IGeneratorTracker::~IGeneratorTracker() {}
10914 const char* GeneratorException::what() const noexcept {
10918 namespace Generators {
10920 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10922 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker& {
10923 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10932 IResultCapture::~IResultCapture() =
default;
10938 IConfig::~IConfig() =
default;
10944 IExceptionTranslator::~IExceptionTranslator() =
default;
10945 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() =
default;
10951 IRegistryHub::~IRegistryHub() =
default;
10952 IMutableRegistryHub::~IMutableRegistryHub() =
default;
10962 using Reporters = std::vector<IStreamingReporterPtr>;
10963 Reporters m_listeners;
10964 IStreamingReporterPtr m_reporter =
nullptr;
10970 void addListener( IStreamingReporterPtr&& listener );
10971 void addReporter( IStreamingReporterPtr&& reporter );
10977 void noMatchingTestCases( std::string
const& spec )
override;
10979 void reportInvalidArguments(std::string
const&arg)
override;
10981 static std::set<Verbosity> getSupportedVerbosities();
10983 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
10984 void benchmarkPreparing(std::string
const& name)
override;
10985 void benchmarkStarting(
BenchmarkInfo const& benchmarkInfo )
override;
10987 void benchmarkFailed(std::string
const&)
override;
10990 void testRunStarting(
TestRunInfo const& testRunInfo )
override;
10991 void testGroupStarting(
GroupInfo const& groupInfo )
override;
10992 void testCaseStarting(
TestCaseInfo const& testInfo )
override;
10993 void sectionStarting(
SectionInfo const& sectionInfo )
override;
10994 void assertionStarting(
AssertionInfo const& assertionInfo )
override;
10997 bool assertionEnded(
AssertionStats const& assertionStats )
override;
10998 void sectionEnded(
SectionStats const& sectionStats )
override;
10999 void testCaseEnded(
TestCaseStats const& testCaseStats )
override;
11000 void testGroupEnded(
TestGroupStats const& testGroupStats )
override;
11001 void testRunEnded(
TestRunStats const& testRunStats )
override;
11003 void skipTest(
TestCaseInfo const& testInfo )
override;
11004 bool isMulti()
const override;
11013 ReporterConfig::ReporterConfig( IConfigPtr
const& _fullConfig )
11014 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11016 ReporterConfig::ReporterConfig( IConfigPtr
const& _fullConfig, std::ostream& _stream )
11017 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11019 std::ostream& ReporterConfig::stream()
const {
return *m_stream; }
11020 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
11022 TestRunInfo::TestRunInfo( std::string
const& _name ) : name( _name ) {}
11024 GroupInfo::GroupInfo( std::string
const& _name,
11025 std::size_t _groupIndex,
11026 std::size_t _groupsCount )
11028 groupIndex( _groupIndex ),
11029 groupsCounts( _groupsCount )
11032 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
11033 std::vector<MessageInfo>
const& _infoMessages,
11034 Totals
const& _totals )
11035 : assertionResult( _assertionResult ),
11036 infoMessages( _infoMessages ),
11039 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11041 if( assertionResult.hasMessage() ) {
11044 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11045 builder << assertionResult.getMessage();
11046 builder.m_info.message = builder.m_stream.str();
11048 infoMessages.push_back( builder.m_info );
11052 AssertionStats::~AssertionStats() =
default;
11054 SectionStats::SectionStats( SectionInfo
const& _sectionInfo,
11055 Counts
const& _assertions,
11056 double _durationInSeconds,
11057 bool _missingAssertions )
11058 : sectionInfo( _sectionInfo ),
11059 assertions( _assertions ),
11060 durationInSeconds( _durationInSeconds ),
11061 missingAssertions( _missingAssertions )
11064 SectionStats::~SectionStats() =
default;
11066 TestCaseStats::TestCaseStats( TestCaseInfo
const& _testInfo,
11067 Totals
const& _totals,
11068 std::string
const& _stdOut,
11069 std::string
const& _stdErr,
11071 : testInfo( _testInfo ),
11075 aborting( _aborting )
11078 TestCaseStats::~TestCaseStats() =
default;
11080 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11081 Totals
const& _totals,
11083 : groupInfo( _groupInfo ),
11085 aborting( _aborting )
11088 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11089 : groupInfo( _groupInfo ),
11093 TestGroupStats::~TestGroupStats() =
default;
11095 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11096 Totals
const& _totals,
11098 : runInfo( _runInfo ),
11100 aborting( _aborting )
11103 TestRunStats::~TestRunStats() =
default;
11105 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
11106 bool IStreamingReporter::isMulti()
const {
return false; }
11108 IReporterFactory::~IReporterFactory() =
default;
11109 IReporterRegistry::~IReporterRegistry() =
default;
11116 IRunner::~IRunner() =
default;
11122 ITestInvoker::~ITestInvoker() =
default;
11123 ITestCaseRegistry::~ITestCaseRegistry() =
default;
11128 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11129 #include <crtdbg.h>
11133 LeakDetector::LeakDetector() {
11134 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11135 flag |= _CRTDBG_LEAK_CHECK_DF;
11136 flag |= _CRTDBG_ALLOC_MEM_DF;
11137 _CrtSetDbgFlag(flag);
11138 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11139 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11141 _CrtSetBreakAlloc(-1);
11147 Catch::LeakDetector::LeakDetector() {}
11151 Catch::LeakDetector::~LeakDetector() {
11163 std::size_t listTests( Config
const& config );
11165 std::size_t listTestsNamesOnly( Config
const& config );
11168 void add( std::string
const& spelling );
11169 std::string all()
const;
11171 std::set<std::string> spellings;
11172 std::size_t count = 0;
11175 std::size_t listTags(
Config const& config );
11177 std::size_t listReporters();
11187 using namespace clara::TextFlow;
11192 #include <algorithm>
11197 std::size_t listTests( Config
const& config ) {
11198 TestSpec
const& testSpec = config.testSpec();
11199 if( config.hasTestFilters() )
11200 Catch::cout() <<
"Matching test cases:\n";
11202 Catch::cout() <<
"All available test cases:\n";
11205 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11206 for(
auto const& testCaseInfo : matchedTestCases ) {
11207 Colour::Code colour = testCaseInfo.isHidden()
11208 ? Colour::SecondaryText
11210 Colour colourGuard( colour );
11212 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11213 if( config.verbosity() >= Verbosity::High ) {
11214 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11215 std::string description = testCaseInfo.description;
11216 if( description.empty() )
11217 description =
"(NO DESCRIPTION)";
11218 Catch::cout() << Column( description ).indent(4) << std::endl;
11220 if( !testCaseInfo.tags.empty() )
11221 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) <<
"\n";
11224 if( !config.hasTestFilters() )
11225 Catch::cout() << pluralise( matchedTestCases.size(),
"test case" ) <<
'\n' << std::endl;
11227 Catch::cout() << pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11228 return matchedTestCases.size();
11231 std::size_t listTestsNamesOnly( Config
const& config ) {
11232 TestSpec
const& testSpec = config.testSpec();
11233 std::size_t matchedTests = 0;
11234 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11235 for(
auto const& testCaseInfo : matchedTestCases ) {
11237 if( startsWith( testCaseInfo.name,
'#' ) )
11238 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11240 Catch::cout() << testCaseInfo.name;
11241 if ( config.verbosity() >= Verbosity::High )
11242 Catch::cout() <<
"\t@" << testCaseInfo.lineInfo;
11243 Catch::cout() << std::endl;
11245 return matchedTests;
11248 void TagInfo::add( std::string
const& spelling ) {
11250 spellings.insert( spelling );
11253 std::string TagInfo::all()
const {
11255 for (
auto const& spelling : spellings) {
11257 size += spelling.size() + 2;
11260 std::string out; out.reserve(size);
11261 for (
auto const& spelling : spellings) {
11269 std::size_t listTags( Config
const& config ) {
11270 TestSpec
const& testSpec = config.testSpec();
11271 if( config.hasTestFilters() )
11272 Catch::cout() <<
"Tags for matching test cases:\n";
11274 Catch::cout() <<
"All available tags:\n";
11277 std::map<std::string, TagInfo> tagCounts;
11279 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11280 for(
auto const& testCase : matchedTestCases ) {
11281 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11282 std::string lcaseTagName = toLower( tagName );
11283 auto countIt = tagCounts.find( lcaseTagName );
11284 if( countIt == tagCounts.end() )
11285 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11286 countIt->second.add( tagName );
11290 for(
auto const& tagCount : tagCounts ) {
11291 ReusableStringStream rss;
11292 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11293 auto str = rss.str();
11294 auto wrapper = Column( tagCount.second.all() )
11295 .initialIndent( 0 )
11296 .indent( str.size() )
11297 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11298 Catch::cout() << str << wrapper <<
'\n';
11300 Catch::cout() << pluralise( tagCounts.size(),
"tag" ) <<
'\n' << std::endl;
11301 return tagCounts.size();
11304 std::size_t listReporters() {
11305 Catch::cout() <<
"Available reporters:\n";
11306 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
11307 std::size_t maxNameLen = 0;
11308 for(
auto const& factoryKvp : factories )
11309 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11311 for(
auto const& factoryKvp : factories ) {
11313 << Column( factoryKvp.first +
":" )
11315 .width( 5+maxNameLen )
11316 + Column( factoryKvp.second->getDescription() )
11319 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11322 Catch::cout() << std::endl;
11323 return factories.size();
11326 Option<std::size_t> list( std::shared_ptr<Config>
const& config ) {
11327 Option<std::size_t> listedCount;
11328 getCurrentMutableContext().setConfig( config );
11329 if( config->listTests() )
11330 listedCount = listedCount.valueOr(0) + listTests( *config );
11331 if( config->listTestNamesOnly() )
11332 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11333 if( config->listTags() )
11334 listedCount = listedCount.valueOr(0) + listTags( *config );
11335 if( config->listReporters() )
11336 listedCount = listedCount.valueOr(0) + listReporters();
11337 return listedCount;
11345 namespace Matchers {
11348 std::string MatcherUntypedBase::toString()
const {
11349 if( m_cachedToString.empty() )
11350 m_cachedToString = describe();
11351 return m_cachedToString;
11354 MatcherUntypedBase::~MatcherUntypedBase() =
default;
11359 using namespace Matchers;
11360 using Matchers::Impl::MatcherBase;
11367 namespace Matchers {
11368 namespace Exception {
11370 bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11371 return ex.what() == m_message;
11374 std::string ExceptionMessageMatcher::describe()
const {
11375 return "exception message matches \"" + m_message + "\"";
11379 Exception::ExceptionMessageMatcher Message(std::string
const& message) {
11380 return Exception::ExceptionMessageMatcher(message);
11392 bool isnan(
float f);
11393 bool isnan(
double d);
11402 template <
typename T>
11403 std::string to_string(T
const& t) {
11404 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11405 return std::to_string(t);
11407 ReusableStringStream rss;
11415 #include <algorithm>
11421 #include <type_traits>
11428 int32_t convert(
float f) {
11429 static_assert(
sizeof(
float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11431 std::memcpy(&i, &f,
sizeof(f));
11435 int64_t convert(
double d) {
11436 static_assert(
sizeof(
double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11438 std::memcpy(&i, &d,
sizeof(d));
11442 template <
typename FP>
11443 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11446 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11450 auto lc = convert(lhs);
11451 auto rc = convert(rhs);
11453 if ((lc < 0) != (rc < 0)) {
11458 auto ulpDiff = std::abs(lc - rc);
11459 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11462 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11464 float nextafter(
float x,
float y) {
11465 return ::nextafterf(x, y);
11468 double nextafter(
double x,
double y) {
11469 return ::nextafter(x, y);
11474 template <
typename FP>
11475 FP step(FP start, FP direction, uint64_t steps) {
11476 for (uint64_t i = 0; i < steps; ++i) {
11477 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11478 start = Catch::nextafter(start, direction);
11480 start = std::nextafter(start, direction);
11488 bool marginComparison(
double lhs,
double rhs,
double margin) {
11489 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11492 template <
typename FloatingPo
int>
11493 void write(std::ostream& out, FloatingPoint num) {
11494 out << std::scientific
11495 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11501 namespace Matchers {
11502 namespace Floating {
11504 enum class FloatingPointKind : uint8_t {
11509 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11510 :m_target{ target }, m_margin{ margin } {
11511 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.'
11512 <<
" Margin has to be non-negative.");
11517 bool WithinAbsMatcher::match(
double const& matchee)
const {
11518 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11521 std::string WithinAbsMatcher::describe()
const {
11522 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11525 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11526 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11527 CATCH_ENFORCE(m_type == FloatingPointKind::Double
11528 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11529 "Provided ULP is impossibly large for a float comparison.");
11532 #if defined(__clang__)
11533 #pragma clang diagnostic push
11535 #pragma clang diagnostic ignored "-Wunreachable-code"
11538 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11540 case FloatingPointKind::Float:
11541 return almostEqualUlps<float>(
static_cast<float>(matchee),
static_cast<float>(m_target), m_ulps);
11542 case FloatingPointKind::Double:
11543 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11545 CATCH_INTERNAL_ERROR(
"Unknown FloatingPointKind value" );
11549 #if defined(__clang__)
11550 #pragma clang diagnostic pop
11553 std::string WithinUlpsMatcher::describe()
const {
11554 std::stringstream ret;
11556 ret <<
"is within " << m_ulps <<
" ULPs of ";
11558 if (m_type == FloatingPointKind::Float) {
11559 write(ret,
static_cast<float>(m_target));
11562 write(ret, m_target);
11566 if (m_type == FloatingPointKind::Double) {
11567 write(ret, step(m_target,
static_cast<double>(-INFINITY), m_ulps));
11569 write(ret, step(m_target,
static_cast<double>( INFINITY), m_ulps));
11572 write(ret, step(
static_cast<float>(m_target),
static_cast<float>(-INFINITY), m_ulps));
11574 write(ret, step(
static_cast<float>(m_target),
static_cast<float>( INFINITY), m_ulps));
11581 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11583 m_epsilon(epsilon){
11584 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11585 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
");
11588 bool WithinRelMatcher::match(double const& matchee) const {
11589 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11590 return marginComparison(matchee, m_target,
11591 std::isinf(relMargin)? 0 : relMargin);
11594 std::string WithinRelMatcher::describe() const {
11595 Catch::ReusableStringStream sstr;
11596 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
";
11600 }// namespace Floating
11602 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11603 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11606 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11607 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11610 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11611 return Floating::WithinAbsMatcher(target, margin);
11614 Floating::WithinRelMatcher WithinRel(double target, double eps) {
11615 return Floating::WithinRelMatcher(target, eps);
11618 Floating::WithinRelMatcher WithinRel(double target) {
11619 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11622 Floating::WithinRelMatcher WithinRel(float target, float eps) {
11623 return Floating::WithinRelMatcher(target, eps);
11626 Floating::WithinRelMatcher WithinRel(float target) {
11627 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11630 } // namespace Matchers
11631 } // namespace Catch
11633 // end catch_matchers_floating.cpp
11634 // start catch_matchers_generic.cpp
11636 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11637 if (desc.empty()) {
11638 return "matches undescribed predicate
";
11640 return "matches predicate: \
"" + desc +
'"';
11649 namespace Matchers {
11651 namespace StdString {
11653 CasedString::CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity )
11654 : m_caseSensitivity( caseSensitivity ),
11655 m_str( adjustString( str ) )
11657 std::string CasedString::adjustString( std::string
const& str )
const {
11658 return m_caseSensitivity == CaseSensitive::No
11662 std::string CasedString::caseSensitivitySuffix()
const {
11663 return m_caseSensitivity == CaseSensitive::No
11664 ?
" (case insensitive)"
11668 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
11669 : m_comparator( comparator ),
11670 m_operation( operation ) {
11673 std::string StringMatcherBase::describe()
const {
11674 std::string description;
11675 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11676 m_comparator.caseSensitivitySuffix().size());
11677 description += m_operation;
11678 description += ": \"";
11679 description += m_comparator.m_str;
11680 description += "\"";
11681 description += m_comparator.caseSensitivitySuffix();
11682 return description;
11685 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11687 bool EqualsMatcher::match( std::string
const& source )
const {
11688 return m_comparator.adjustString( source ) == m_comparator.m_str;
11691 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11693 bool ContainsMatcher::match( std::string
const& source )
const {
11694 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11697 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11699 bool StartsWithMatcher::match( std::string
const& source )
const {
11700 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11703 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11705 bool EndsWithMatcher::match( std::string
const& source )
const {
11706 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11709 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11711 bool RegexMatcher::match(std::string
const& matchee)
const {
11712 auto flags = std::regex::ECMAScript;
11713 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11714 flags |= std::regex::icase;
11716 auto reg = std::regex(m_regex, flags);
11717 return std::regex_match(matchee, reg);
11720 std::string RegexMatcher::describe()
const {
11721 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11726 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11727 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11729 StdString::ContainsMatcher Contains( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11730 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11732 StdString::EndsWithMatcher EndsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11733 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11735 StdString::StartsWithMatcher StartsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11736 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11739 StdString::RegexMatcher Matches(std::string
const& regex, CaseSensitive::Choice caseSensitivity) {
11740 return StdString::RegexMatcher(regex, caseSensitivity);
11751 bool uncaught_exceptions();
11760 MessageInfo::MessageInfo( StringRef
const& _macroName,
11761 SourceLineInfo
const& _lineInfo,
11762 ResultWas::OfType _type )
11763 : macroName( _macroName ),
11764 lineInfo( _lineInfo ),
11766 sequence( ++globalCount )
11769 bool MessageInfo::operator==( MessageInfo
const& other )
const {
11770 return sequence == other.sequence;
11773 bool MessageInfo::operator<( MessageInfo
const& other )
const {
11774 return sequence < other.sequence;
11778 unsigned int MessageInfo::globalCount = 0;
11782 Catch::MessageBuilder::MessageBuilder( StringRef
const& macroName,
11783 SourceLineInfo
const& lineInfo,
11784 ResultWas::OfType type )
11785 :m_info(macroName, lineInfo, type) {}
11789 ScopedMessage::ScopedMessage( MessageBuilder
const& builder )
11790 : m_info( builder.m_info ), m_moved()
11792 m_info.message = builder.m_stream.str();
11793 getResultCapture().pushScopedMessage( m_info );
11796 ScopedMessage::ScopedMessage( ScopedMessage&& old )
11797 : m_info( old.m_info ), m_moved()
11799 old.m_moved =
true;
11802 ScopedMessage::~ScopedMessage() {
11803 if ( !uncaught_exceptions() && !m_moved ){
11804 getResultCapture().popScopedMessage(m_info);
11808 Capturer::Capturer( StringRef macroName, SourceLineInfo
const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11809 auto trimmed = [&] (
size_t start,
size_t end) {
11810 while (names[start] ==
',' || isspace(
static_cast<unsigned char>(names[start]))) {
11813 while (names[end] ==
',' || isspace(
static_cast<unsigned char>(names[end]))) {
11816 return names.substr(start, end - start + 1);
11818 auto skipq = [&] (
size_t start,
char quote) {
11819 for (
auto i = start + 1; i < names.size() ; ++i) {
11820 if (names[i] == quote)
11822 if (names[i] ==
'\\')
11825 CATCH_INTERNAL_ERROR(
"CAPTURE parsing encountered unmatched quote");
11829 std::stack<char> openings;
11830 for (
size_t pos = 0; pos < names.size(); ++pos) {
11831 char c = names[pos];
11849 pos = skipq(pos, c);
11852 if (start != pos && openings.empty()) {
11853 m_messages.emplace_back(macroName, lineInfo, resultType);
11854 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11855 m_messages.back().message += " := ";
11860 assert(openings.empty() &&
"Mismatched openings");
11861 m_messages.emplace_back(macroName, lineInfo, resultType);
11862 m_messages.back().message =
static_cast<std::string
>(trimmed(start, names.size() - 1));
11863 m_messages.back().message += " := ";
11865 Capturer::~Capturer() {
11866 if ( !uncaught_exceptions() ){
11867 assert( m_captured == m_messages.size() );
11868 for(
size_t i = 0; i < m_captured; ++i )
11869 m_resultCapture.popScopedMessage( m_messages[i] );
11873 void Capturer::captureValue(
size_t index, std::string
const& value ) {
11874 assert( index < m_messages.size() );
11875 m_messages[index].message += value;
11876 m_resultCapture.pushScopedMessage( m_messages[index] );
11885 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11886 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11895 std::ostream& m_originalStream;
11896 std::ostream& m_redirectionStream;
11897 std::streambuf* m_prevBuf;
11900 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11909 auto str()
const -> std::string;
11921 auto str()
const -> std::string;
11934 std::string& m_redirectedCout;
11935 std::string& m_redirectedCerr;
11940 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11956 std::FILE* getFile();
11957 std::string getContents();
11960 std::FILE* m_file =
nullptr;
11961 #if defined(_MSC_VER)
11962 char m_buffer[L_tmpnam] = { 0 };
11973 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
11977 int m_originalStdout = -1;
11978 int m_originalStderr = -1;
11981 std::string& m_stdoutDest;
11982 std::string& m_stderrDest;
11995 #include <stdexcept>
11997 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11998 #if defined(_MSC_VER)
12002 #define fileno _fileno
12004 #include <unistd.h>
12010 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12011 : m_originalStream( originalStream ),
12012 m_redirectionStream( redirectionStream ),
12013 m_prevBuf( m_originalStream.rdbuf() )
12015 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12018 RedirectedStream::~RedirectedStream() {
12019 m_originalStream.rdbuf( m_prevBuf );
12022 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
12023 auto RedirectedStdOut::str() const -> std::
string {
return m_rss.str(); }
12025 RedirectedStdErr::RedirectedStdErr()
12026 : m_cerr( Catch::cerr(), m_rss.get() ),
12027 m_clog( Catch::clog(), m_rss.get() )
12029 auto RedirectedStdErr::str() const -> std::
string {
return m_rss.str(); }
12031 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12032 : m_redirectedCout(redirectedCout),
12033 m_redirectedCerr(redirectedCerr)
12036 RedirectedStreams::~RedirectedStreams() {
12037 m_redirectedCout += m_redirectedStdOut.str();
12038 m_redirectedCerr += m_redirectedStdErr.str();
12041 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12043 #if defined(_MSC_VER)
12044 TempFile::TempFile() {
12045 if (tmpnam_s(m_buffer)) {
12046 CATCH_RUNTIME_ERROR(
"Could not get a temp filename");
12048 if (fopen_s(&m_file, m_buffer,
"w")) {
12050 if (strerror_s(buffer, errno)) {
12051 CATCH_RUNTIME_ERROR(
"Could not translate errno to a string");
12053 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12057 TempFile::TempFile() {
12058 m_file = std::tmpfile();
12060 CATCH_RUNTIME_ERROR(
"Could not create a temp file.");
12066 TempFile::~TempFile() {
12068 std::fclose(m_file);
12071 #if defined(_MSC_VER)
12072 std::remove(m_buffer);
12076 FILE* TempFile::getFile() {
12080 std::string TempFile::getContents() {
12081 std::stringstream sstr;
12082 char buffer[100] = {};
12083 std::rewind(m_file);
12084 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12090 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12091 m_originalStdout(dup(1)),
12092 m_originalStderr(dup(2)),
12093 m_stdoutDest(stdout_dest),
12094 m_stderrDest(stderr_dest) {
12095 dup2(fileno(m_stdoutFile.getFile()), 1);
12096 dup2(fileno(m_stderrFile.getFile()), 2);
12099 OutputRedirect::~OutputRedirect() {
12100 Catch::cout() << std::flush;
12104 Catch::cerr() << std::flush;
12105 Catch::clog() << std::flush;
12108 dup2(m_originalStdout, 1);
12109 dup2(m_originalStderr, 2);
12111 m_stdoutDest += m_stdoutFile.getContents();
12112 m_stderrDest += m_stderrFile.getContents();
12119 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12120 #if defined(_MSC_VER)
12133 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12134 bool isnan(
float f) {
12135 return std::isnan(f);
12137 bool isnan(
double d) {
12138 return std::isnan(d);
12142 bool isnan(
float f) {
12143 return std::_isnan(f);
12145 bool isnan(
double d) {
12146 return std::_isnan(d);
12158 #if defined(_MSC_VER)
12159 #pragma warning(push)
12160 #pragma warning(disable:4146)
12163 uint32_t rotate_right(uint32_t val, uint32_t count) {
12164 const uint32_t mask = 31;
12166 return (val >> count) | (val << (-count & mask));
12169 #if defined(_MSC_VER)
12170 #pragma warning(pop)
12175 SimplePcg32::SimplePcg32(result_type seed_) {
12179 void SimplePcg32::seed(result_type seed_) {
12186 void SimplePcg32::discard(uint64_t skip) {
12189 for (uint64_t s = 0; s < skip; ++s) {
12190 static_cast<void>((*this)());
12194 SimplePcg32::result_type SimplePcg32::operator()() {
12196 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12197 const auto output = rotate_right(xorshifted, m_state >> 59u);
12200 m_state = m_state * 6364136223846793005ULL + s_inc;
12205 bool operator==(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12206 return lhs.m_state == rhs.m_state;
12209 bool operator!=(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12210 return lhs.m_state != rhs.m_state;
12220 #include <algorithm>
12228 std::vector<TestCase> sortTests( IConfig
const& config, std::vector<TestCase>
const& unsortedTestCases );
12230 bool isThrowSafe( TestCase
const& testCase, IConfig
const& config );
12231 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config );
12233 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12235 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config );
12236 std::vector<TestCase>
const& getAllTestCasesSorted( IConfig
const& config );
12242 virtual void registerTest(
TestCase const& testCase );
12244 std::vector<TestCase>
const& getAllTests()
const override;
12245 std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const override;
12248 std::vector<TestCase> m_functions;
12249 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12250 mutable std::vector<TestCase> m_sortedFunctions;
12251 std::size_t m_unnamedCount = 0;
12252 std::ios_base::Init m_ostreamInit;
12258 void(*m_testAsFunction)();
12262 void invoke()
const override;
12265 std::string extractClassName(
StringRef const& classOrQualifiedMethodName );
12284 IStreamingReporterPtr create( std::string
const& name, IConfigPtr
const& config )
const override;
12286 void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory );
12287 void registerListener( IReporterFactoryPtr
const& factory );
12289 FactoryMap
const& getFactories()
const override;
12290 Listeners
const& getListeners()
const override;
12293 FactoryMap m_factories;
12294 Listeners m_listeners;
12324 TagAlias const* find( std::string
const& alias )
const override;
12325 std::string expandAliases( std::string
const& unexpandedTestSpec )
const override;
12326 void add( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo );
12329 std::map<std::string, TagAlias> m_registry;
12338 #include <exception>
12343 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12345 void add(std::exception_ptr
const& exception) noexcept;
12346 std::vector<std::exception_ptr>
const& getExceptions()
const noexcept;
12348 std::vector<std::exception_ptr> m_exceptions;
12364 void cleanupSingletons();
12366 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12369 static auto getInternal() ->
Singleton* {
12370 static Singleton* s_instance =
nullptr;
12371 if( !s_instance ) {
12373 addSingleton( s_instance );
12379 static auto get() -> InterfaceT
const& {
12380 return *getInternal();
12382 static auto getMutable() -> MutableInterfaceT& {
12383 return *getInternal();
12400 return m_reporterRegistry;
12403 return m_testCaseRegistry;
12406 return m_exceptionTranslatorRegistry;
12409 return m_tagAliasRegistry;
12412 return m_exceptionRegistry;
12416 void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory )
override {
12417 m_reporterRegistry.registerReporter( name, factory );
12419 void registerListener( IReporterFactoryPtr
const& factory )
override {
12420 m_reporterRegistry.registerListener( factory );
12422 void registerTest(
TestCase const& testInfo )
override {
12423 m_testCaseRegistry.registerTest( testInfo );
12426 m_exceptionTranslatorRegistry.registerTranslator( translator );
12428 void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo )
override {
12429 m_tagAliasRegistry.add( alias, tag, lineInfo );
12431 void registerStartupException() noexcept
override {
12432 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12433 m_exceptionRegistry.add(std::current_exception());
12435 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12439 return m_enumValuesRegistry;
12455 return RegistryHubSingleton::get();
12457 IMutableRegistryHub& getMutableRegistryHub() {
12458 return RegistryHubSingleton::getMutable();
12461 cleanupSingletons();
12464 std::string translateActiveException() {
12465 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12474 ReporterRegistry::~ReporterRegistry() =
default;
12476 IStreamingReporterPtr ReporterRegistry::create( std::string
const& name, IConfigPtr
const& config )
const {
12477 auto it = m_factories.find( name );
12478 if( it == m_factories.end() )
12480 return it->second->create( ReporterConfig( config ) );
12483 void ReporterRegistry::registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory ) {
12484 m_factories.emplace(name, factory);
12486 void ReporterRegistry::registerListener( IReporterFactoryPtr
const& factory ) {
12487 m_listeners.push_back( factory );
12490 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12491 return m_factories;
12493 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12494 return m_listeners;
12503 bool isOk( ResultWas::OfType resultType ) {
12504 return ( resultType & ResultWas::FailureBit ) == 0;
12506 bool isJustInfo(
int flags ) {
12507 return flags == ResultWas::Info;
12510 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12511 return static_cast<ResultDisposition::Flags
>(
static_cast<int>( lhs ) |
static_cast<int>( rhs ) );
12514 bool shouldContinueOnFailure(
int flags ) {
return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
12515 bool shouldSuppressFailure(
int flags ) {
return ( flags & ResultDisposition::SuppressFail ) != 0; }
12522 #include <algorithm>
12527 namespace Generators {
12529 GeneratorBasePtr m_generator;
12532 : TrackerBase( nameAndLocation, ctx, parent )
12537 std::shared_ptr<GeneratorTracker> tracker;
12539 ITracker& currentTracker = ctx.currentTracker();
12551 if (currentTracker.nameAndLocation() == nameAndLocation) {
12552 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12553 assert(thisTracker);
12554 assert(thisTracker->isGeneratorTracker());
12555 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12556 }
else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12557 assert( childTracker );
12558 assert( childTracker->isGeneratorTracker() );
12559 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12561 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12562 currentTracker.addChild( tracker );
12565 if( !tracker->isComplete() ) {
12573 bool isGeneratorTracker()
const override {
return true; }
12574 auto hasGenerator()
const ->
bool override {
12575 return !!m_generator;
12577 void close()
override {
12578 TrackerBase::close();
12586 const bool should_wait_for_child =
12587 !m_children.empty() &&
12588 std::find_if( m_children.begin(),
12590 []( TestCaseTracking::ITrackerPtr tracker ) {
12591 return tracker->hasStarted();
12592 } ) == m_children.end();
12598 if ( should_wait_for_child ||
12599 ( m_runState == CompletedSuccessfully &&
12600 m_generator->next() ) ) {
12601 m_children.clear();
12602 m_runState = Executing;
12607 auto getGenerator()
const -> GeneratorBasePtr
const&
override {
12608 return m_generator;
12610 void setGenerator( GeneratorBasePtr&& generator )
override {
12611 m_generator = std::move( generator );
12614 GeneratorTracker::~GeneratorTracker() {}
12617 RunContext::RunContext(IConfigPtr
const& _config, IStreamingReporterPtr&& reporter)
12618 : m_runInfo(_config->name()),
12619 m_context(getCurrentMutableContext()),
12621 m_reporter(std::move(reporter)),
12622 m_lastAssertionInfo{ StringRef(), SourceLineInfo(
"",0), StringRef(), ResultDisposition::Normal },
12623 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12625 m_context.setRunner(
this);
12626 m_context.setConfig(m_config);
12627 m_context.setResultCapture(
this);
12628 m_reporter->testRunStarting(m_runInfo);
12631 RunContext::~RunContext() {
12632 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12635 void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12636 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12639 void RunContext::testGroupEnded(std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12640 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12643 Totals RunContext::runTest(TestCase
const& testCase) {
12644 Totals prevTotals = m_totals;
12646 std::string redirectedCout;
12647 std::string redirectedCerr;
12649 auto const& testInfo = testCase.getTestCaseInfo();
12651 m_reporter->testCaseStarting(testInfo);
12653 m_activeTestCase = &testCase;
12655 ITracker& rootTracker = m_trackerContext.startRun();
12656 assert(rootTracker.isSectionTracker());
12657 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12659 m_trackerContext.startCycle();
12660 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12661 runCurrentTest(redirectedCout, redirectedCerr);
12662 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12664 Totals deltaTotals = m_totals.delta(prevTotals);
12665 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12666 deltaTotals.assertions.failed++;
12667 deltaTotals.testCases.passed--;
12668 deltaTotals.testCases.failed++;
12670 m_totals.testCases += deltaTotals.testCases;
12671 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12677 m_activeTestCase =
nullptr;
12678 m_testCaseTracker =
nullptr;
12680 return deltaTotals;
12683 IConfigPtr RunContext::config()
const {
12687 IStreamingReporter& RunContext::reporter()
const {
12688 return *m_reporter;
12691 void RunContext::assertionEnded(AssertionResult
const & result) {
12692 if (result.getResultType() == ResultWas::Ok) {
12693 m_totals.assertions.passed++;
12694 m_lastAssertionPassed =
true;
12695 }
else if (!result.isOk()) {
12696 m_lastAssertionPassed =
false;
12697 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12698 m_totals.assertions.failedButOk++;
12700 m_totals.assertions.failed++;
12703 m_lastAssertionPassed =
true;
12708 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12710 if (result.getResultType() != ResultWas::Warning)
12711 m_messageScopes.clear();
12714 resetAssertionInfo();
12715 m_lastResult = result;
12717 void RunContext::resetAssertionInfo() {
12718 m_lastAssertionInfo.macroName = StringRef();
12719 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12722 bool RunContext::sectionStarted(SectionInfo
const & sectionInfo, Counts & assertions) {
12723 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12724 if (!sectionTracker.isOpen())
12726 m_activeSections.push_back(§ionTracker);
12728 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12730 m_reporter->sectionStarting(sectionInfo);
12732 assertions = m_totals.assertions;
12736 auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker& {
12737 using namespace Generators;
12738 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12739 TestCaseTracking::NameAndLocation(
static_cast<std::string
>(generatorName), lineInfo ) );
12740 m_lastAssertionInfo.lineInfo = lineInfo;
12744 bool RunContext::testForMissingAssertions(Counts& assertions) {
12745 if (assertions.total() != 0)
12747 if (!m_config->warnAboutMissingAssertions())
12749 if (m_trackerContext.currentTracker().hasChildren())
12751 m_totals.assertions.failed++;
12752 assertions.failed++;
12756 void RunContext::sectionEnded(SectionEndInfo
const & endInfo) {
12757 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12758 bool missingAssertions = testForMissingAssertions(assertions);
12760 if (!m_activeSections.empty()) {
12761 m_activeSections.back()->close();
12762 m_activeSections.pop_back();
12765 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12766 m_messages.clear();
12767 m_messageScopes.clear();
12770 void RunContext::sectionEndedEarly(SectionEndInfo
const & endInfo) {
12771 if (m_unfinishedSections.empty())
12772 m_activeSections.back()->fail();
12774 m_activeSections.back()->close();
12775 m_activeSections.pop_back();
12777 m_unfinishedSections.push_back(endInfo);
12780 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12781 void RunContext::benchmarkPreparing(std::string
const& name) {
12782 m_reporter->benchmarkPreparing(name);
12784 void RunContext::benchmarkStarting( BenchmarkInfo
const& info ) {
12785 m_reporter->benchmarkStarting( info );
12787 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12788 m_reporter->benchmarkEnded( stats );
12790 void RunContext::benchmarkFailed(std::string
const & error) {
12791 m_reporter->benchmarkFailed(error);
12795 void RunContext::pushScopedMessage(MessageInfo
const & message) {
12796 m_messages.push_back(message);
12799 void RunContext::popScopedMessage(MessageInfo
const & message) {
12800 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12803 void RunContext::emplaceUnscopedMessage( MessageBuilder
const& builder ) {
12804 m_messageScopes.emplace_back( builder );
12807 std::string RunContext::getCurrentTestName()
const {
12808 return m_activeTestCase
12809 ? m_activeTestCase->getTestCaseInfo().name
12813 const AssertionResult * RunContext::getLastResult()
const {
12814 return &(*m_lastResult);
12817 void RunContext::exceptionEarlyReported() {
12818 m_shouldReportUnexpected =
false;
12821 void RunContext::handleFatalErrorCondition( StringRef message ) {
12823 m_reporter->fatalErrorEncountered(message);
12827 AssertionResultData tempResult( ResultWas::FatalErrorCondition, {
false } );
12828 tempResult.message =
static_cast<std::string
>(message);
12829 AssertionResult result(m_lastAssertionInfo, tempResult);
12831 assertionEnded(result);
12833 handleUnfinishedSections();
12836 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12837 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12840 assertions.failed = 1;
12841 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12842 m_reporter->sectionEnded(testCaseSectionStats);
12844 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12846 Totals deltaTotals;
12847 deltaTotals.testCases.failed = 1;
12848 deltaTotals.assertions.failed = 1;
12849 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12854 m_totals.testCases.failed++;
12855 testGroupEnded(std::string(), m_totals, 1, 1);
12856 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12859 bool RunContext::lastAssertionPassed() {
12860 return m_lastAssertionPassed;
12863 void RunContext::assertionPassed() {
12864 m_lastAssertionPassed =
true;
12865 ++m_totals.assertions.passed;
12866 resetAssertionInfo();
12867 m_messageScopes.clear();
12870 bool RunContext::aborting()
const {
12871 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12874 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12875 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12876 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12877 m_reporter->sectionStarting(testCaseSection);
12878 Counts prevAssertions = m_totals.assertions;
12879 double duration = 0;
12880 m_shouldReportUnexpected =
true;
12881 m_lastAssertionInfo = {
"TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12883 seedRng(*m_config);
12887 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12888 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12889 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12892 invokeActiveTestCase();
12894 OutputRedirect r(redirectedCout, redirectedCerr);
12896 invokeActiveTestCase();
12900 invokeActiveTestCase();
12902 duration = timer.getElapsedSeconds();
12903 } CATCH_CATCH_ANON (TestFailureException&) {
12905 } CATCH_CATCH_ALL {
12908 if( m_shouldReportUnexpected ) {
12909 AssertionReaction dummyReaction;
12910 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
12913 Counts assertions = m_totals.assertions - prevAssertions;
12914 bool missingAssertions = testForMissingAssertions(assertions);
12916 m_testCaseTracker->close();
12917 handleUnfinishedSections();
12918 m_messages.clear();
12919 m_messageScopes.clear();
12921 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
12922 m_reporter->sectionEnded(testCaseSectionStats);
12925 void RunContext::invokeActiveTestCase() {
12926 FatalConditionHandler fatalConditionHandler;
12927 m_activeTestCase->invoke();
12928 fatalConditionHandler.reset();
12931 void RunContext::handleUnfinishedSections() {
12934 for (
auto it = m_unfinishedSections.rbegin(),
12935 itEnd = m_unfinishedSections.rend();
12939 m_unfinishedSections.clear();
12942 void RunContext::handleExpr(
12943 AssertionInfo
const& info,
12944 ITransientExpression
const& expr,
12945 AssertionReaction& reaction
12947 m_reporter->assertionStarting( info );
12949 bool negated = isFalseTest( info.resultDisposition );
12950 bool result = expr.getResult() != negated;
12953 if (!m_includeSuccessfulResults) {
12957 reportExpr(info, ResultWas::Ok, &expr, negated);
12961 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
12962 populateReaction( reaction );
12965 void RunContext::reportExpr(
12966 AssertionInfo
const &info,
12967 ResultWas::OfType resultType,
12968 ITransientExpression
const *expr,
12971 m_lastAssertionInfo = info;
12972 AssertionResultData data( resultType, LazyExpression( negated ) );
12974 AssertionResult assertionResult{ info, data };
12975 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
12977 assertionEnded( assertionResult );
12980 void RunContext::handleMessage(
12981 AssertionInfo
const& info,
12982 ResultWas::OfType resultType,
12983 StringRef
const& message,
12984 AssertionReaction& reaction
12986 m_reporter->assertionStarting( info );
12988 m_lastAssertionInfo = info;
12990 AssertionResultData data( resultType, LazyExpression(
false ) );
12991 data.message =
static_cast<std::string
>(message);
12992 AssertionResult assertionResult{ m_lastAssertionInfo, data };
12993 assertionEnded( assertionResult );
12994 if( !assertionResult.isOk() )
12995 populateReaction( reaction );
12997 void RunContext::handleUnexpectedExceptionNotThrown(
12998 AssertionInfo
const& info,
12999 AssertionReaction& reaction
13001 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13004 void RunContext::handleUnexpectedInflightException(
13005 AssertionInfo
const& info,
13006 std::string
const& message,
13007 AssertionReaction& reaction
13009 m_lastAssertionInfo = info;
13011 AssertionResultData data( ResultWas::ThrewException, LazyExpression(
false ) );
13012 data.message = message;
13013 AssertionResult assertionResult{ info, data };
13014 assertionEnded( assertionResult );
13015 populateReaction( reaction );
13018 void RunContext::populateReaction( AssertionReaction& reaction ) {
13019 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13020 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13023 void RunContext::handleIncomplete(
13024 AssertionInfo
const& info
13026 m_lastAssertionInfo = info;
13028 AssertionResultData data( ResultWas::ThrewException, LazyExpression(
false ) );
13029 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13030 AssertionResult assertionResult{ info, data };
13031 assertionEnded( assertionResult );
13033 void RunContext::handleNonExpr(
13034 AssertionInfo
const &info,
13035 ResultWas::OfType resultType,
13036 AssertionReaction &reaction
13038 m_lastAssertionInfo = info;
13040 AssertionResultData data( resultType, LazyExpression(
false ) );
13041 AssertionResult assertionResult{ info, data };
13042 assertionEnded( assertionResult );
13044 if( !assertionResult.isOk() )
13045 populateReaction( reaction );
13048 IResultCapture& getResultCapture() {
13049 if (
auto* capture = getCurrentContext().getResultCapture())
13052 CATCH_INTERNAL_ERROR(
"No result capture instance");
13055 void seedRng(IConfig
const& config) {
13056 if (config.rngSeed() != 0) {
13057 std::srand(config.rngSeed());
13058 rng().seed(config.rngSeed());
13062 unsigned int rngSeed() {
13063 return getCurrentContext().getConfig()->rngSeed();
13072 Section::Section( SectionInfo
const& info )
13074 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13079 Section::~Section() {
13080 if( m_sectionIncluded ) {
13081 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13082 if( uncaught_exceptions() )
13083 getResultCapture().sectionEndedEarly( endInfo );
13085 getResultCapture().sectionEnded( endInfo );
13090 Section::operator bool()
const {
13091 return m_sectionIncluded;
13100 SectionInfo::SectionInfo
13101 ( SourceLineInfo
const& _lineInfo,
13102 std::string
const& _name )
13104 lineInfo( _lineInfo )
13123 void showHelp()
const;
13124 void libIdentify();
13126 int applyCommandLine(
int argc,
char const *
const * argv );
13127 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13128 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13131 void useConfigData(
ConfigData const& configData );
13133 template<
typename CharT>
13134 int run(
int argc, CharT
const *
const argv[]) {
13135 if (m_startupExceptions)
13137 int returnCode = applyCommandLine(argc, argv);
13138 if (returnCode == 0)
13139 returnCode = run();
13154 std::shared_ptr<Config> m_config;
13155 bool m_startupExceptions =
false;
13171 Version(
unsigned int _majorVersion,
13172 unsigned int _minorVersion,
13173 unsigned int _patchNumber,
13174 char const *
const _branchName,
13175 unsigned int _buildNumber );
13177 unsigned int const majorVersion;
13178 unsigned int const minorVersion;
13179 unsigned int const patchNumber;
13182 char const *
const branchName;
13183 unsigned int const buildNumber;
13185 friend std::ostream& operator << ( std::ostream& os,
Version const& version );
13188 Version const& libraryVersion();
13195 #include <iterator>
13200 const int MaxExitCode = 255;
13202 IStreamingReporterPtr createReporter(std::string
const& reporterName, IConfigPtr
const& config) {
13203 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13204 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13209 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13210 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13211 return createReporter(config->getReporterName(), config);
13219 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13220 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13221 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13222 for (
auto const& listener : listeners) {
13225 multi.addReporter(createReporter(config->getReporterName(), config));
13231 explicit TestGroup(std::shared_ptr<Config>
const& config)
13233 , m_context{config, makeReporter(config)}
13235 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13236 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13237 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13239 if (m_matches.empty() && invalidArgs.empty()) {
13240 for (
auto const& test : allTestCases)
13241 if (!test.isHidden())
13242 m_tests.emplace(&test);
13244 for (
auto const& match : m_matches)
13245 m_tests.insert(match.tests.begin(), match.tests.end());
13250 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13252 m_context.testGroupStarting(m_config->name(), 1, 1);
13253 for (
auto const& testCase : m_tests) {
13254 if (!m_context.aborting())
13255 totals += m_context.runTest(*testCase);
13257 m_context.reporter().skipTest(*testCase);
13260 for (
auto const& match : m_matches) {
13261 if (match.tests.empty()) {
13262 m_context.reporter().noMatchingTestCases(match.name);
13267 if (!invalidArgs.empty()) {
13268 for (
auto const& invalidArg: invalidArgs)
13269 m_context.reporter().reportInvalidArguments(invalidArg);
13272 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13277 using Tests = std::set<TestCase const*>;
13279 std::shared_ptr<Config> m_config;
13282 TestSpec::Matches m_matches;
13286 auto& tests =
const_cast<std::vector<TestCase>&
>(getAllTestCasesSorted(config));
13287 for (
auto& testCase : tests) {
13288 auto tags = testCase.tags;
13290 std::string filename = testCase.lineInfo.file;
13291 auto lastSlash = filename.find_last_of(
"\\/");
13292 if (lastSlash != std::string::npos) {
13293 filename.erase(0, lastSlash);
13297 auto lastDot = filename.find_last_of(
'.');
13298 if (lastDot != std::string::npos) {
13299 filename.erase(lastDot);
13302 tags.push_back(std::move(filename));
13303 setTags(testCase, tags);
13309 Session::Session() {
13310 static bool alreadyInstantiated =
false;
13311 if( alreadyInstantiated ) {
13312 CATCH_TRY { CATCH_INTERNAL_ERROR(
"Only one instance of Catch::Session can ever be used" ); }
13313 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13317 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13318 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13319 if ( !exceptions.empty() ) {
13321 getCurrentMutableContext().setConfig(m_config);
13323 m_startupExceptions =
true;
13324 Colour colourGuard( Colour::Red );
13325 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13327 for (
const auto& ex_ptr : exceptions ) {
13329 std::rethrow_exception(ex_ptr);
13330 }
catch ( std::exception
const& ex ) {
13331 Catch::cerr() << Column( ex.what() ).indent(2) <<
'\n';
13337 alreadyInstantiated =
true;
13338 m_cli = makeCommandLineParser( m_configData );
13340 Session::~Session() {
13344 void Session::showHelp()
const {
13346 <<
"\nCatch v" << libraryVersion() <<
"\n"
13347 << m_cli << std::endl
13348 <<
"For more detailed usage please see the project docs\n" << std::endl;
13350 void Session::libIdentify() {
13352 << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n"
13353 << std::left << std::setw(16) <<
"category: " <<
"testframework\n"
13354 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n"
13355 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13358 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13359 if( m_startupExceptions )
13362 auto result = m_cli.parse( clara::Args( argc, argv ) );
13365 getCurrentMutableContext().setConfig(m_config);
13367 << Colour( Colour::Red )
13368 <<
"\nError(s) in input:\n"
13369 << Column( result.errorMessage() ).indent( 2 )
13371 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13372 return MaxExitCode;
13375 if( m_configData.showHelp )
13377 if( m_configData.libIdentify )
13383 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13384 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13386 char **utf8Argv =
new char *[ argc ];
13388 for (
int i = 0; i < argc; ++i ) {
13389 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr );
13391 utf8Argv[ i ] =
new char[ bufSize ];
13393 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13396 int returnCode = applyCommandLine( argc, utf8Argv );
13398 for (
int i = 0; i < argc; ++i )
13399 delete [] utf8Argv[ i ];
13401 delete [] utf8Argv;
13407 void Session::useConfigData( ConfigData
const& configData ) {
13408 m_configData = configData;
13412 int Session::run() {
13413 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13414 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13415 static_cast<void>(std::getchar());
13417 int exitCode = runInternal();
13418 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13419 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13420 static_cast<void>(std::getchar());
13425 clara::Parser
const& Session::cli()
const {
13428 void Session::cli( clara::Parser
const& newParser ) {
13431 ConfigData& Session::configData() {
13432 return m_configData;
13434 Config& Session::config() {
13436 m_config = std::make_shared<Config>( m_configData );
13440 int Session::runInternal() {
13441 if( m_startupExceptions )
13444 if (m_configData.showHelp || m_configData.libIdentify) {
13451 seedRng( *m_config );
13453 if( m_configData.filenamesAsTags )
13454 applyFilenamesAsTags( *m_config );
13457 if( Option<std::size_t> listed = list( m_config ) )
13458 return static_cast<int>( *listed );
13460 TestGroup tests { m_config };
13461 auto const totals = tests.execute();
13463 if( m_config->warnAboutNoTests() && totals.error == -1 )
13469 return (std::min) (MaxExitCode, (std::max) (totals.error,
static_cast<int>(totals.assertions.failed)));
13471 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13472 catch( std::exception& ex ) {
13473 Catch::cerr() << ex.what() << std::endl;
13474 return MaxExitCode;
13488 static auto getSingletons() -> std::vector<ISingleton*>*& {
13489 static std::vector<ISingleton*>* g_singletons =
nullptr;
13490 if( !g_singletons )
13491 g_singletons =
new std::vector<ISingleton*>();
13492 return g_singletons;
13496 ISingleton::~ISingleton() {}
13498 void addSingleton(ISingleton* singleton ) {
13499 getSingletons()->push_back( singleton );
13501 void cleanupSingletons() {
13502 auto& singletons = getSingletons();
13503 for(
auto singleton : *singletons )
13506 singletons =
nullptr;
13513 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13515 void StartupExceptionRegistry::add( std::exception_ptr
const& exception ) noexcept {
13517 m_exceptions.push_back(exception);
13518 } CATCH_CATCH_ALL {
13524 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions() const noexcept {
13525 return m_exceptions;
13534 #include <iostream>
13542 Catch::IStream::~IStream() =
default;
13544 namespace Detail {
namespace {
13545 template<
typename WriterF, std::
size_t bufferSize=256>
13547 char data[bufferSize];
13552 setp( data, data +
sizeof(data) );
13556 StreamBufImpl::sync();
13560 int overflow(
int c )
override {
13564 if( pbase() == epptr() )
13565 m_writer( std::string( 1,
static_cast<char>( c ) ) );
13567 sputc(
static_cast<char>( c ) );
13572 int sync()
override {
13573 if( pbase() != pptr() ) {
13574 m_writer( std::string( pbase(),
static_cast<std::string::size_type
>( pptr() - pbase() ) ) );
13575 setp( pbase(), epptr() );
13585 void operator()( std::string
const&str ) {
13586 writeToDebugConsole( str );
13593 mutable std::ofstream m_ofs;
13596 m_ofs.open( filename.c_str() );
13597 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13601 std::ostream& stream()
const override {
13609 mutable std::ostream m_os;
13613 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13617 std::ostream& stream()
const override {
return m_os; }
13623 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13624 mutable std::ostream m_os;
13628 m_os( m_streamBuf.get() )
13634 std::ostream& stream()
const override {
return m_os; }
13642 if( filename.empty() )
13643 return new Detail::CoutStream();
13644 else if( filename[0] ==
'%' ) {
13645 if( filename ==
"%debug" )
13646 return new Detail::DebugOutStream();
13648 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13651 return new Detail::FileStream( filename );
13656 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13657 std::vector<std::size_t> m_unused;
13658 std::ostringstream m_referenceStream;
13660 auto add() -> std::size_t {
13661 if( m_unused.empty() ) {
13662 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13663 return m_streams.size()-1;
13666 auto index = m_unused.back();
13667 m_unused.pop_back();
13672 void release( std::size_t index ) {
13673 m_streams[index]->copyfmt( m_referenceStream );
13674 m_unused.push_back(index);
13678 ReusableStringStream::ReusableStringStream()
13683 ReusableStringStream::~ReusableStringStream() {
13684 static_cast<std::ostringstream*
>( m_oss )->str(
"");
13686 Singleton<StringStreams>::getMutable().release( m_index );
13689 auto ReusableStringStream::str() const -> std::
string {
13690 return static_cast<std::ostringstream*
>( m_oss )->str();
13695 #ifndef CATCH_CONFIG_NOSTDOUT
13696 std::ostream& cout() {
return std::cout; }
13697 std::ostream& cerr() {
return std::cerr; }
13698 std::ostream& clog() {
return std::clog; }
13704 #include <algorithm>
13713 char toLowerCh(
char c) {
13714 return static_cast<char>( std::tolower(
static_cast<unsigned char>(c) ) );
13718 bool startsWith( std::string
const& s, std::string
const& prefix ) {
13719 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13721 bool startsWith( std::string
const& s,
char prefix ) {
13722 return !s.empty() && s[0] == prefix;
13724 bool endsWith( std::string
const& s, std::string
const& suffix ) {
13725 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13727 bool endsWith( std::string
const& s,
char suffix ) {
13728 return !s.empty() && s[s.size()-1] == suffix;
13730 bool contains( std::string
const& s, std::string
const& infix ) {
13731 return s.find( infix ) != std::string::npos;
13733 void toLowerInPlace( std::string& s ) {
13734 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13736 std::string toLower( std::string
const& s ) {
13737 std::string lc = s;
13738 toLowerInPlace( lc );
13741 std::string trim( std::string
const& str ) {
13742 static char const* whitespaceChars =
"\n\r\t ";
13743 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13744 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13746 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13749 StringRef trim(StringRef ref) {
13750 const auto is_ws = [](
char c) {
13751 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r';
13753 size_t real_begin = 0;
13754 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13755 size_t real_end = ref.size();
13756 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13758 return ref.substr(real_begin, real_end - real_begin);
13761 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
13762 bool replaced =
false;
13763 std::size_t i = str.find( replaceThis );
13764 while( i != std::string::npos ) {
13766 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13767 if( i < str.size()-withThis.size() )
13768 i = str.find( replaceThis, i+withThis.size() );
13770 i = std::string::npos;
13775 std::vector<StringRef> splitStringRef( StringRef str,
char delimiter ) {
13776 std::vector<StringRef> subStrings;
13777 std::size_t start = 0;
13778 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13779 if( str[pos] == delimiter ) {
13780 if( pos - start > 1 )
13781 subStrings.push_back( str.substr( start, pos-start ) );
13785 if( start < str.size() )
13786 subStrings.push_back( str.substr( start, str.size()-start ) );
13790 pluralise::pluralise( std::size_t count, std::string
const& label )
13791 : m_count( count ),
13795 std::ostream& operator << ( std::ostream& os, pluralise
const& pluraliser ) {
13796 os << pluraliser.m_count <<
' ' << pluraliser.m_label;
13797 if( pluraliser.m_count != 1 )
13806 #include <algorithm>
13812 StringRef::StringRef(
char const* rawChars ) noexcept
13813 : StringRef( rawChars,
static_cast<StringRef::size_type
>(std::strlen(rawChars) ) )
13816 auto StringRef::c_str() const ->
char const* {
13817 CATCH_ENFORCE(isNullTerminated(),
"Called StringRef::c_str() on a non-null-terminated instance");
13820 auto StringRef::data() const noexcept ->
char const* {
13824 auto StringRef::substr( size_type start, size_type size )
const noexcept -> StringRef {
13825 if (start < m_size) {
13826 return StringRef(m_start + start, (std::min)(m_size - start, size));
13828 return StringRef();
13831 auto StringRef::operator == ( StringRef
const& other )
const noexcept ->
bool {
13832 return m_size == other.m_size
13833 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13836 auto operator << ( std::ostream& os, StringRef
const& str ) -> std::ostream& {
13837 return os.write(str.data(), str.size());
13840 auto operator+=( std::string& lhs, StringRef
const& rhs ) -> std::string& {
13841 lhs.append(rhs.data(), rhs.size());
13850 TagAlias::TagAlias(std::string
const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13857 RegistrarForTagAliases::RegistrarForTagAliases(
char const* alias,
char const* tag, SourceLineInfo
const& lineInfo) {
13859 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13860 } CATCH_CATCH_ALL {
13862 getMutableRegistryHub().registerStartupException();
13874 TagAliasRegistry::~TagAliasRegistry() {}
13876 TagAlias
const* TagAliasRegistry::find( std::string
const& alias )
const {
13877 auto it = m_registry.find( alias );
13878 if( it != m_registry.end() )
13879 return &(it->second);
13884 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
13885 std::string expandedTestSpec = unexpandedTestSpec;
13886 for(
auto const& registryKvp : m_registry ) {
13887 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13888 if( pos != std::string::npos ) {
13889 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13890 registryKvp.second.tag +
13891 expandedTestSpec.substr( pos + registryKvp.first.size() );
13894 return expandedTestSpec;
13897 void TagAliasRegistry::add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo ) {
13898 CATCH_ENFORCE( startsWith(alias,
"[@") && endsWith(alias,
']'),
13899 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
13901 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13902 "error: tag alias, '" << alias <<
"' already registered.\n"
13903 <<
"\tFirst seen at: " << find(alias)->lineInfo <<
"\n"
13904 <<
"\tRedefined at: " << lineInfo );
13907 ITagAliasRegistry::~ITagAliasRegistry() {}
13909 ITagAliasRegistry
const& ITagAliasRegistry::get() {
13910 return getRegistryHub().getTagAliasRegistry();
13918 #include <exception>
13919 #include <algorithm>
13925 TestCaseInfo::SpecialProperties parseSpecialTag( std::string
const& tag ) {
13926 if( startsWith( tag,
'.' ) ||
13928 return TestCaseInfo::IsHidden;
13929 else if( tag ==
"!throws" )
13930 return TestCaseInfo::Throws;
13931 else if( tag ==
"!shouldfail" )
13932 return TestCaseInfo::ShouldFail;
13933 else if( tag ==
"!mayfail" )
13934 return TestCaseInfo::MayFail;
13935 else if( tag ==
"!nonportable" )
13936 return TestCaseInfo::NonPortable;
13937 else if( tag ==
"!benchmark" )
13938 return static_cast<TestCaseInfo::SpecialProperties
>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
13940 return TestCaseInfo::None;
13942 bool isReservedTag( std::string
const& tag ) {
13943 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum(
static_cast<unsigned char>(tag[0]) );
13945 void enforceNotReservedTag( std::string
const& tag, SourceLineInfo
const& _lineInfo ) {
13946 CATCH_ENFORCE( !isReservedTag(tag),
13947 "Tag name: [" << tag <<
"] is not allowed.\n"
13948 <<
"Tag names starting with non alphanumeric characters are reserved\n"
13953 TestCase makeTestCase( ITestInvoker* _testCase,
13954 std::string
const& _className,
13955 NameAndTags
const& nameAndTags,
13956 SourceLineInfo
const& _lineInfo )
13958 bool isHidden =
false;
13961 std::vector<std::string> tags;
13962 std::string desc, tag;
13963 bool inTag =
false;
13964 for (
char c : nameAndTags.tags) {
13973 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
13974 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
13976 else if( prop == TestCaseInfo::None )
13977 enforceNotReservedTag( tag, _lineInfo );
13982 if (startsWith(tag,
'.') && tag.size() > 1) {
13985 tags.push_back( tag );
13995 tags.insert( tags.end(), {
".",
"!hide" } );
13998 TestCaseInfo info(
static_cast<std::string
>(nameAndTags.name), _className, desc, tags, _lineInfo );
13999 return TestCase( _testCase, std::move(info) );
14002 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14003 std::sort(begin(tags), end(tags));
14004 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14005 testCaseInfo.lcaseTags.clear();
14007 for(
auto const& tag : tags ) {
14008 std::string lcaseTag = toLower( tag );
14009 testCaseInfo.properties =
static_cast<TestCaseInfo::SpecialProperties
>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14010 testCaseInfo.lcaseTags.push_back( lcaseTag );
14012 testCaseInfo.tags = std::move(tags);
14015 TestCaseInfo::TestCaseInfo( std::string
const& _name,
14016 std::string
const& _className,
14017 std::string
const& _description,
14018 std::vector<std::string>
const& _tags,
14019 SourceLineInfo
const& _lineInfo )
14021 className( _className ),
14022 description( _description ),
14023 lineInfo( _lineInfo ),
14026 setTags( *
this, _tags );
14029 bool TestCaseInfo::isHidden()
const {
14030 return ( properties & IsHidden ) != 0;
14032 bool TestCaseInfo::throws()
const {
14033 return ( properties & Throws ) != 0;
14035 bool TestCaseInfo::okToFail()
const {
14036 return ( properties & (ShouldFail | MayFail ) ) != 0;
14038 bool TestCaseInfo::expectedToFail()
const {
14039 return ( properties & (ShouldFail ) ) != 0;
14042 std::string TestCaseInfo::tagsAsString()
const {
14045 std::size_t full_size = 2 * tags.size();
14046 for (
const auto& tag : tags) {
14047 full_size += tag.size();
14049 ret.reserve(full_size);
14050 for (
const auto& tag : tags) {
14051 ret.push_back(
'[');
14053 ret.push_back(
']');
14059 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
14061 TestCase TestCase::withName( std::string
const& _newName )
const {
14062 TestCase other( *
this );
14063 other.name = _newName;
14067 void TestCase::invoke()
const {
14071 bool TestCase::operator == ( TestCase
const& other )
const {
14072 return test.get() == other.test.get() &&
14073 name == other.name &&
14074 className == other.className;
14077 bool TestCase::operator < ( TestCase
const& other )
const {
14078 return name < other.name;
14081 TestCaseInfo
const& TestCase::getTestCaseInfo()
const
14090 #include <algorithm>
14105 uint64_t operator()(
TestCase const& t)
const {
14107 static constexpr uint64_t prime = 1099511628211;
14108 uint64_t hash = basis;
14109 for (
const char c : t.name) {
14118 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases ) {
14119 switch( config.runOrder() ) {
14120 case RunTests::InDeclarationOrder:
14124 case RunTests::InLexicographicalOrder: {
14125 std::vector<TestCase> sorted = unsortedTestCases;
14126 std::sort( sorted.begin(), sorted.end() );
14130 case RunTests::InRandomOrder: {
14132 TestHasher h( rng() );
14134 using hashedTest = std::pair<uint64_t, TestCase const*>;
14135 std::vector<hashedTest> indexed_tests;
14136 indexed_tests.reserve( unsortedTestCases.size() );
14138 for (
auto const& testCase : unsortedTestCases) {
14139 indexed_tests.emplace_back(h(testCase), &testCase);
14142 std::sort(indexed_tests.begin(), indexed_tests.end(),
14143 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14144 if (lhs.first == rhs.first) {
14145 return lhs.second->name < rhs.second->name;
14147 return lhs.first < rhs.first;
14150 std::vector<TestCase> sorted;
14151 sorted.reserve( indexed_tests.size() );
14153 for (
auto const& hashed : indexed_tests) {
14154 sorted.emplace_back(*hashed.second);
14160 return unsortedTestCases;
14163 bool isThrowSafe( TestCase
const& testCase, IConfig
const& config ) {
14164 return !testCase.throws() || config.allowThrows();
14167 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config ) {
14168 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14171 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14172 std::set<TestCase> seenFunctions;
14173 for(
auto const&
function : functions ) {
14174 auto prev = seenFunctions.insert(
function );
14175 CATCH_ENFORCE( prev.second,
14176 "error: TEST_CASE( \"" <<
function.name <<
"\" ) already defined.\n"
14177 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n"
14178 <<
"\tRedefined at " <<
function.getTestCaseInfo().lineInfo );
14182 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config ) {
14183 std::vector<TestCase> filtered;
14184 filtered.reserve( testCases.size() );
14185 for (
auto const& testCase : testCases) {
14186 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14187 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14188 filtered.push_back(testCase);
14193 std::vector<TestCase>
const& getAllTestCasesSorted( IConfig
const& config ) {
14194 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14197 void TestRegistry::registerTest( TestCase
const& testCase ) {
14198 std::string name = testCase.getTestCaseInfo().name;
14199 if( name.empty() ) {
14200 ReusableStringStream rss;
14201 rss <<
"Anonymous test case " << ++m_unnamedCount;
14202 return registerTest( testCase.withName( rss.str() ) );
14204 m_functions.push_back( testCase );
14207 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14208 return m_functions;
14210 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted( IConfig
const& config )
const {
14211 if( m_sortedFunctions.empty() )
14212 enforceNoDuplicateTestCases( m_functions );
14214 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14215 m_sortedFunctions = sortTests( config, m_functions );
14216 m_currentSortOrder = config.runOrder();
14218 return m_sortedFunctions;
14222 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14224 void TestInvokerAsFunction::invoke()
const {
14225 m_testAsFunction();
14228 std::string extractClassName( StringRef
const& classOrQualifiedMethodName ) {
14229 std::string className(classOrQualifiedMethodName);
14230 if( startsWith( className,
'&' ) )
14232 std::size_t lastColons = className.rfind(
"::" );
14233 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14234 if( penultimateColons == std::string::npos )
14235 penultimateColons = 1;
14236 className = className.substr( penultimateColons, lastColons-penultimateColons );
14245 #include <algorithm>
14247 #include <stdexcept>
14251 #if defined(__clang__)
14252 # pragma clang diagnostic push
14253 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14257 namespace TestCaseTracking {
14259 NameAndLocation::NameAndLocation( std::string
const& _name, SourceLineInfo
const& _location )
14261 location( _location )
14264 ITracker::~ITracker() =
default;
14266 ITracker& TrackerContext::startRun() {
14267 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}", CATCH_INTERNAL_LINEINFO ), *
this,
nullptr );
14268 m_currentTracker =
nullptr;
14269 m_runState = Executing;
14270 return *m_rootTracker;
14273 void TrackerContext::endRun() {
14274 m_rootTracker.reset();
14275 m_currentTracker =
nullptr;
14276 m_runState = NotStarted;
14279 void TrackerContext::startCycle() {
14280 m_currentTracker = m_rootTracker.get();
14281 m_runState = Executing;
14283 void TrackerContext::completeCycle() {
14284 m_runState = CompletedCycle;
14287 bool TrackerContext::completedCycle()
const {
14288 return m_runState == CompletedCycle;
14290 ITracker& TrackerContext::currentTracker() {
14291 return *m_currentTracker;
14293 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14294 m_currentTracker = tracker;
14297 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14298 ITracker(nameAndLocation),
14303 bool TrackerBase::isComplete()
const {
14304 return m_runState == CompletedSuccessfully || m_runState == Failed;
14306 bool TrackerBase::isSuccessfullyCompleted()
const {
14307 return m_runState == CompletedSuccessfully;
14309 bool TrackerBase::isOpen()
const {
14310 return m_runState != NotStarted && !isComplete();
14312 bool TrackerBase::hasChildren()
const {
14313 return !m_children.empty();
14316 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14317 m_children.push_back( child );
14320 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14321 auto it = std::find_if( m_children.begin(), m_children.end(),
14322 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14324 tracker->nameAndLocation().location == nameAndLocation.location &&
14325 tracker->nameAndLocation().name == nameAndLocation.name;
14327 return( it != m_children.end() )
14331 ITracker& TrackerBase::parent() {
14332 assert( m_parent );
14336 void TrackerBase::openChild() {
14337 if( m_runState != ExecutingChildren ) {
14338 m_runState = ExecutingChildren;
14340 m_parent->openChild();
14344 bool TrackerBase::isSectionTracker()
const {
return false; }
14345 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14347 void TrackerBase::open() {
14348 m_runState = Executing;
14351 m_parent->openChild();
14354 void TrackerBase::close() {
14357 while( &m_ctx.currentTracker() !=
this )
14358 m_ctx.currentTracker().close();
14360 switch( m_runState ) {
14361 case NeedsAnotherRun:
14365 m_runState = CompletedSuccessfully;
14367 case ExecutingChildren:
14368 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const& t){ return t->isComplete(); }) )
14369 m_runState = CompletedSuccessfully;
14373 case CompletedSuccessfully:
14375 CATCH_INTERNAL_ERROR(
"Illogical state: " << m_runState );
14378 CATCH_INTERNAL_ERROR(
"Unknown state: " << m_runState );
14381 m_ctx.completeCycle();
14383 void TrackerBase::fail() {
14384 m_runState = Failed;
14386 m_parent->markAsNeedingAnotherRun();
14388 m_ctx.completeCycle();
14390 void TrackerBase::markAsNeedingAnotherRun() {
14391 m_runState = NeedsAnotherRun;
14394 void TrackerBase::moveToParent() {
14395 assert( m_parent );
14396 m_ctx.setCurrentTracker( m_parent );
14398 void TrackerBase::moveToThis() {
14399 m_ctx.setCurrentTracker(
this );
14402 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14403 : TrackerBase( nameAndLocation, ctx, parent ),
14404 m_trimmed_name(trim(nameAndLocation.name))
14407 while( !parent->isSectionTracker() )
14408 parent = &parent->parent();
14410 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14411 addNextFilters( parentSection.m_filters );
14415 bool SectionTracker::isComplete()
const {
14416 bool complete =
true;
14418 if (m_filters.empty()
14419 || m_filters[0] ==
""
14420 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14421 complete = TrackerBase::isComplete();
14426 bool SectionTracker::isSectionTracker()
const {
return true; }
14428 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14429 std::shared_ptr<SectionTracker> section;
14431 ITracker& currentTracker = ctx.currentTracker();
14432 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14433 assert( childTracker );
14434 assert( childTracker->isSectionTracker() );
14435 section = std::static_pointer_cast<SectionTracker>( childTracker );
14438 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14439 currentTracker.addChild( section );
14441 if( !ctx.completedCycle() )
14442 section->tryOpen();
14446 void SectionTracker::tryOpen() {
14447 if( !isComplete() )
14451 void SectionTracker::addInitialFilters( std::vector<std::string>
const& filters ) {
14452 if( !filters.empty() ) {
14453 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14454 m_filters.emplace_back(
"");
14455 m_filters.emplace_back(
"");
14456 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14459 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14460 if( filters.size() > 1 )
14461 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14466 using TestCaseTracking::ITracker;
14467 using TestCaseTracking::TrackerContext;
14468 using TestCaseTracking::SectionTracker;
14472 #if defined(__clang__)
14473 # pragma clang diagnostic pop
14480 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14481 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14484 NameAndTags::NameAndTags( StringRef
const& name_ , StringRef
const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14486 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo
const& lineInfo, StringRef
const& classOrMethod, NameAndTags
const& nameAndTags ) noexcept {
14488 getMutableRegistryHub()
14492 extractClassName( classOrMethod ),
14495 } CATCH_CATCH_ALL {
14497 getMutableRegistryHub().registerStartupException();
14501 AutoReg::~AutoReg() =
default;
14506 #include <algorithm>
14513 TestSpec::Pattern::Pattern( std::string
const& name )
14517 TestSpec::Pattern::~Pattern() =
default;
14519 std::string
const& TestSpec::Pattern::name()
const {
14523 TestSpec::NamePattern::NamePattern( std::string
const& name, std::string
const& filterString )
14524 : Pattern( filterString )
14525 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14528 bool TestSpec::NamePattern::matches( TestCaseInfo
const& testCase )
const {
14529 return m_wildcardPattern.matches( testCase.name );
14532 TestSpec::TagPattern::TagPattern( std::string
const& tag, std::string
const& filterString )
14533 : Pattern( filterString )
14534 , m_tag( toLower( tag ) )
14537 bool TestSpec::TagPattern::matches( TestCaseInfo
const& testCase )
const {
14538 return std::find(begin(testCase.lcaseTags),
14539 end(testCase.lcaseTags),
14540 m_tag) != end(testCase.lcaseTags);
14543 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14544 : Pattern( underlyingPattern->name() )
14545 , m_underlyingPattern( underlyingPattern )
14548 bool TestSpec::ExcludedPattern::matches( TestCaseInfo
const& testCase )
const {
14549 return !m_underlyingPattern->matches( testCase );
14552 bool TestSpec::Filter::matches( TestCaseInfo
const& testCase )
const {
14553 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const& p ){ return p->matches( testCase ); } );
14556 std::string TestSpec::Filter::name()
const {
14558 for(
auto const& p : m_patterns )
14563 bool TestSpec::hasFilters()
const {
14564 return !m_filters.empty();
14567 bool TestSpec::matches( TestCaseInfo
const& testCase )
const {
14568 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const& f ){ return f.matches( testCase ); } );
14571 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase>
const& testCases, IConfig
const& config )
const
14573 Matches matches( m_filters.size() );
14574 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter
const& filter ){
14575 std::vector<TestCase const*> currentMatches;
14576 for( auto const& test : testCases )
14577 if( isThrowSafe( test, config ) && filter.matches( test ) )
14578 currentMatches.emplace_back( &test );
14579 return FilterMatch{ filter.name(), currentMatches };
14584 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14585 return (m_invalidArgs);
14594 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14596 TestSpecParser& TestSpecParser::parse( std::string
const& arg ) {
14598 m_exclusion =
false;
14599 m_arg = m_tagAliases->expandAliases( arg );
14600 m_escapeChars.clear();
14601 m_substring.reserve(m_arg.size());
14602 m_patternName.reserve(m_arg.size());
14603 m_realPatternPos = 0;
14605 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14607 if( !visitChar( m_arg[m_pos] ) ){
14608 m_testSpec.m_invalidArgs.push_back(arg);
14614 TestSpec TestSpecParser::testSpec() {
14618 bool TestSpecParser::visitChar(
char c ) {
14619 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14621 addCharToPattern(c);
14623 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14629 if( processNoneChar( c ) )
14633 processNameChar( c );
14637 addCharToPattern(c);
14642 if( processOtherChar( c ) )
14648 if( !isControlChar( c ) ) {
14649 m_patternName += c;
14650 m_realPatternPos++;
14656 bool TestSpecParser::processNoneChar(
char c ) {
14661 m_exclusion =
true;
14664 startNewMode( Tag );
14667 startNewMode( QuotedName );
14670 startNewMode( Name );
14674 void TestSpecParser::processNameChar(
char c ) {
14676 if( m_substring ==
"exclude:" )
14677 m_exclusion =
true;
14680 startNewMode( Tag );
14683 bool TestSpecParser::processOtherChar(
char c ) {
14684 if( !isControlChar( c ) )
14690 void TestSpecParser::startNewMode( Mode mode ) {
14693 void TestSpecParser::endMode() {
14697 return addNamePattern();
14699 return addTagPattern();
14701 revertBackToLastMode();
14705 return startNewMode( None );
14708 void TestSpecParser::escape() {
14710 m_mode = EscapedName;
14711 m_escapeChars.push_back(m_realPatternPos);
14713 bool TestSpecParser::isControlChar(
char c )
const {
14726 return c ==
'[' || c ==
']';
14730 void TestSpecParser::addFilter() {
14731 if( !m_currentFilter.m_patterns.empty() ) {
14732 m_testSpec.m_filters.push_back( m_currentFilter );
14733 m_currentFilter = TestSpec::Filter();
14737 void TestSpecParser::saveLastMode() {
14741 void TestSpecParser::revertBackToLastMode() {
14745 bool TestSpecParser::separate() {
14746 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14749 m_pos = m_arg.size();
14750 m_substring.clear();
14751 m_patternName.clear();
14752 m_realPatternPos = 0;
14760 std::string TestSpecParser::preprocessPattern() {
14761 std::string token = m_patternName;
14762 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14763 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14764 m_escapeChars.clear();
14765 if (startsWith(token,
"exclude:")) {
14766 m_exclusion =
true;
14767 token = token.substr(8);
14770 m_patternName.clear();
14771 m_realPatternPos = 0;
14776 void TestSpecParser::addNamePattern() {
14777 auto token = preprocessPattern();
14779 if (!token.empty()) {
14780 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14782 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14783 m_currentFilter.m_patterns.push_back(pattern);
14785 m_substring.clear();
14786 m_exclusion =
false;
14790 void TestSpecParser::addTagPattern() {
14791 auto token = preprocessPattern();
14793 if (!token.empty()) {
14796 if (token.size() > 1 && token[0] ==
'.') {
14797 token.erase(token.begin());
14798 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14800 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14802 m_currentFilter.m_patterns.push_back(pattern);
14805 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14808 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14810 m_currentFilter.m_patterns.push_back(pattern);
14812 m_substring.clear();
14813 m_exclusion =
false;
14817 TestSpec parseTestSpec( std::string
const& arg ) {
14818 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14827 static const uint64_t nanosecondsInSecond = 1000000000;
14831 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14832 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14836 auto estimateClockResolution() -> uint64_t {
14838 static const uint64_t iterations = 1000000;
14840 auto startTime = getCurrentNanosecondsSinceEpoch();
14842 for( std::size_t i = 0; i < iterations; ++i ) {
14845 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14847 ticks = getCurrentNanosecondsSinceEpoch();
14848 }
while( ticks == baseTicks );
14850 auto delta = ticks - baseTicks;
14856 if (ticks > startTime + 3 * nanosecondsInSecond) {
14857 return sum / ( i + 1u );
14863 return sum/iterations;
14866 auto getEstimatedClockResolution() -> uint64_t {
14867 static auto s_resolution = estimateClockResolution();
14868 return s_resolution;
14871 void Timer::start() {
14872 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14874 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14875 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14877 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14878 return getElapsedNanoseconds()/1000;
14880 auto Timer::getElapsedMilliseconds() const ->
unsigned int {
14881 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14883 auto Timer::getElapsedSeconds() const ->
double {
14884 return getElapsedMicroseconds()/1000000.0;
14891 #if defined(__clang__)
14892 # pragma clang diagnostic push
14893 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14894 # pragma clang diagnostic ignored "-Wglobal-constructors"
14898 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14899 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
14909 const std::string unprintableString =
"{?}";
14912 const int hexThreshold = 255;
14915 enum Arch { Big, Little };
14917 static Arch which() {
14921 auto value = *
reinterpret_cast<char*
>(&one);
14922 return value ? Little : Big;
14927 std::string rawMemoryToString(
const void *
object, std::size_t size ) {
14929 int i = 0, end =
static_cast<int>( size ), inc = 1;
14930 if( Endianness::which() == Endianness::Little ) {
14935 unsigned char const *bytes =
static_cast<unsigned char const *
>(object);
14937 rss <<
"0x" << std::setfill(
'0') << std::hex;
14938 for( ; i != end; i += inc )
14939 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
14944 template<
typename T>
14945 std::string fpToString( T value,
int precision ) {
14946 if (Catch::isnan(value)) {
14950 ReusableStringStream rss;
14951 rss << std::setprecision( precision )
14954 std::string d = rss.str();
14955 std::size_t i = d.find_last_not_of(
'0' );
14956 if( i != std::string::npos && i != d.size()-1 ) {
14959 d = d.substr( 0, i+1 );
14970 std::string StringMaker<std::string>::convert(
const std::string& str) {
14971 if (!getCurrentContext().getConfig()->showInvisibles()) {
14972 return '"' + str + '"';
14975 std::string s(
"\"");
14976 for (
char c : str) {
14993 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
14994 std::string StringMaker<std::string_view>::convert(std::string_view str) {
14995 return ::Catch::Detail::stringify(std::string{ str });
14999 std::string StringMaker<char const*>::convert(
char const* str) {
15001 return ::Catch::Detail::stringify(std::string{ str });
15003 return{
"{null string}" };
15006 std::string StringMaker<char*>::convert(
char* str) {
15008 return ::Catch::Detail::stringify(std::string{ str });
15010 return{
"{null string}" };
15014 #ifdef CATCH_CONFIG_WCHAR
15015 std::string StringMaker<std::wstring>::convert(
const std::wstring& wstr) {
15017 s.reserve(wstr.size());
15018 for (
auto c : wstr) {
15019 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15021 return ::Catch::Detail::stringify(s);
15024 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15025 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15026 return StringMaker<std::wstring>::convert(std::wstring(str));
15030 std::string StringMaker<wchar_t const*>::convert(
wchar_t const * str) {
15032 return ::Catch::Detail::stringify(std::wstring{ str });
15034 return{
"{null string}" };
15037 std::string StringMaker<wchar_t *>::convert(
wchar_t * str) {
15039 return ::Catch::Detail::stringify(std::wstring{ str });
15041 return{
"{null string}" };
15046 #if defined(CATCH_CONFIG_CPP17_BYTE)
15048 std::string StringMaker<std::byte>::convert(std::byte value) {
15049 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15053 std::string StringMaker<int>::convert(
int value) {
15054 return ::Catch::Detail::stringify(
static_cast<long long>(value));
15056 std::string StringMaker<long>::convert(
long value) {
15057 return ::Catch::Detail::stringify(
static_cast<long long>(value));
15059 std::string StringMaker<long long>::convert(
long long value) {
15060 ReusableStringStream rss;
15062 if (value > Detail::hexThreshold) {
15063 rss <<
" (0x" << std::hex << value <<
')';
15068 std::string StringMaker<unsigned int>::convert(
unsigned int value) {
15069 return ::Catch::Detail::stringify(
static_cast<unsigned long long>(value));
15071 std::string StringMaker<unsigned long>::convert(
unsigned long value) {
15072 return ::Catch::Detail::stringify(
static_cast<unsigned long long>(value));
15074 std::string StringMaker<unsigned long long>::convert(
unsigned long long value) {
15075 ReusableStringStream rss;
15077 if (value > Detail::hexThreshold) {
15078 rss <<
" (0x" << std::hex << value <<
')';
15083 std::string StringMaker<bool>::convert(
bool b) {
15084 return b ?
"true" :
"false";
15087 std::string StringMaker<signed char>::convert(
signed char value) {
15088 if (value ==
'\r') {
15090 }
else if (value ==
'\f') {
15092 }
else if (value ==
'\n') {
15094 }
else if (value ==
'\t') {
15096 }
else if (
'\0' <= value && value <
' ') {
15097 return ::Catch::Detail::stringify(
static_cast<unsigned int>(value));
15099 char chstr[] =
"' '";
15104 std::string StringMaker<char>::convert(
char c) {
15105 return ::Catch::Detail::stringify(
static_cast<signed char>(c));
15107 std::string StringMaker<unsigned char>::convert(
unsigned char c) {
15108 return ::Catch::Detail::stringify(
static_cast<char>(c));
15111 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15115 int StringMaker<float>::precision = 5;
15117 std::string StringMaker<float>::convert(
float value) {
15118 return fpToString(value, precision) + 'f';
15121 int StringMaker<double>::precision = 10;
15123 std::string StringMaker<double>::convert(
double value) {
15124 return fpToString(value, precision);
15127 std::string ratio_string<std::atto>::symbol() {
return "a"; }
15128 std::string ratio_string<std::femto>::symbol() {
return "f"; }
15129 std::string ratio_string<std::pico>::symbol() {
return "p"; }
15130 std::string ratio_string<std::nano>::symbol() {
return "n"; }
15131 std::string ratio_string<std::micro>::symbol() {
return "u"; }
15132 std::string ratio_string<std::milli>::symbol() {
return "m"; }
15136 #if defined(__clang__)
15137 # pragma clang diagnostic pop
15145 Counts Counts::operator - ( Counts
const& other )
const {
15147 diff.passed = passed - other.passed;
15148 diff.failed = failed - other.failed;
15149 diff.failedButOk = failedButOk - other.failedButOk;
15153 Counts& Counts::operator += ( Counts
const& other ) {
15154 passed += other.passed;
15155 failed += other.failed;
15156 failedButOk += other.failedButOk;
15160 std::size_t Counts::total()
const {
15161 return passed + failed + failedButOk;
15163 bool Counts::allPassed()
const {
15164 return failed == 0 && failedButOk == 0;
15166 bool Counts::allOk()
const {
15167 return failed == 0;
15170 Totals Totals::operator - ( Totals
const& other )
const {
15172 diff.assertions = assertions - other.assertions;
15173 diff.testCases = testCases - other.testCases;
15177 Totals& Totals::operator += ( Totals
const& other ) {
15178 assertions += other.assertions;
15179 testCases += other.testCases;
15183 Totals Totals::delta( Totals
const& prevTotals )
const {
15184 Totals diff = *
this - prevTotals;
15185 if( diff.assertions.failed > 0 )
15186 ++diff.testCases.failed;
15187 else if( diff.assertions.failedButOk > 0 )
15188 ++diff.testCases.failedButOk;
15190 ++diff.testCases.passed;
15198 #include <exception>
15201 bool uncaught_exceptions() {
15202 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15204 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15205 return std::uncaught_exceptions() > 0;
15207 return std::uncaught_exception();
15219 (
unsigned int _majorVersion,
15220 unsigned int _minorVersion,
15221 unsigned int _patchNumber,
15222 char const *
const _branchName,
15223 unsigned int _buildNumber )
15224 : majorVersion( _majorVersion ),
15225 minorVersion( _minorVersion ),
15226 patchNumber( _patchNumber ),
15227 branchName( _branchName ),
15228 buildNumber( _buildNumber )
15231 std::ostream& operator << ( std::ostream& os, Version
const& version ) {
15232 os << version.majorVersion <<
'.'
15233 << version.minorVersion <<
'.'
15234 << version.patchNumber;
15236 if (version.branchName[0]) {
15237 os <<
'-' << version.branchName
15238 <<
'.' << version.buildNumber;
15243 Version
const& libraryVersion() {
15244 static Version version( 2, 13, 1,
"", 0 );
15254 WildcardPattern::WildcardPattern( std::string
const& pattern,
15255 CaseSensitive::Choice caseSensitivity )
15256 : m_caseSensitivity( caseSensitivity ),
15257 m_pattern( normaliseString( pattern ) )
15259 if( startsWith( m_pattern,
'*' ) ) {
15260 m_pattern = m_pattern.substr( 1 );
15261 m_wildcard = WildcardAtStart;
15263 if( endsWith( m_pattern,
'*' ) ) {
15264 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15265 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15269 bool WildcardPattern::matches( std::string
const& str )
const {
15270 switch( m_wildcard ) {
15272 return m_pattern == normaliseString( str );
15273 case WildcardAtStart:
15274 return endsWith( normaliseString( str ), m_pattern );
15275 case WildcardAtEnd:
15276 return startsWith( normaliseString( str ), m_pattern );
15277 case WildcardAtBothEnds:
15278 return contains( normaliseString( str ), m_pattern );
15280 CATCH_INTERNAL_ERROR(
"Unknown enum" );
15284 std::string WildcardPattern::normaliseString( std::string
const& str )
const {
15285 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15292 #include <type_traits>
15298 size_t trailingBytes(
unsigned char c) {
15299 if ((c & 0xE0) == 0xC0) {
15302 if ((c & 0xF0) == 0xE0) {
15305 if ((c & 0xF8) == 0xF0) {
15308 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15311 uint32_t headerValue(
unsigned char c) {
15312 if ((c & 0xE0) == 0xC0) {
15315 if ((c & 0xF0) == 0xE0) {
15318 if ((c & 0xF8) == 0xF0) {
15321 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15324 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15325 std::ios_base::fmtflags f(os.flags());
15327 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15328 <<
static_cast<int>(c);
15332 bool shouldNewline(XmlFormatting fmt) {
15333 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15336 bool shouldIndent(XmlFormatting fmt) {
15337 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15342 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15343 return static_cast<XmlFormatting
>(
15344 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15345 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15349 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15350 return static_cast<XmlFormatting
>(
15351 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15352 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15356 XmlEncode::XmlEncode( std::string
const& str, ForWhat forWhat )
15358 m_forWhat( forWhat )
15361 void XmlEncode::encodeTo( std::ostream& os )
const {
15365 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15366 unsigned char c = m_str[idx];
15368 case '<': os <<
"<";
break;
15369 case '&': os <<
"&";
break;
15373 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15380 if (m_forWhat == ForAttributes)
15391 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15392 hexEscapeChar(os, c);
15410 hexEscapeChar(os, c);
15414 auto encBytes = trailingBytes(c);
15416 if (idx + encBytes - 1 >= m_str.size()) {
15417 hexEscapeChar(os, c);
15424 uint32_t value = headerValue(c);
15425 for (std::size_t n = 1; n < encBytes; ++n) {
15426 unsigned char nc = m_str[idx + n];
15427 valid &= ((nc & 0xC0) == 0x80);
15428 value = (value << 6) | (nc & 0x3F);
15436 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15437 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15439 (value >= 0x110000)
15441 hexEscapeChar(os, c);
15446 for (std::size_t n = 0; n < encBytes; ++n) {
15447 os << m_str[idx + n];
15449 idx += encBytes - 1;
15455 std::ostream& operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15456 xmlEncode.encodeTo( os );
15460 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15461 : m_writer( writer ),
15465 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15466 : m_writer( other.m_writer ),
15469 other.m_writer =
nullptr;
15470 other.m_fmt = XmlFormatting::None;
15472 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15474 m_writer->endElement();
15476 m_writer = other.m_writer;
15477 other.m_writer =
nullptr;
15478 m_fmt = other.m_fmt;
15479 other.m_fmt = XmlFormatting::None;
15483 XmlWriter::ScopedElement::~ScopedElement() {
15485 m_writer->endElement(m_fmt);
15489 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string
const& text, XmlFormatting fmt ) {
15490 m_writer->writeText( text, fmt );
15494 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15496 writeDeclaration();
15499 XmlWriter::~XmlWriter() {
15500 while (!m_tags.empty()) {
15503 newlineIfNecessary();
15506 XmlWriter& XmlWriter::startElement( std::string
const& name, XmlFormatting fmt ) {
15508 newlineIfNecessary();
15509 if (shouldIndent(fmt)) {
15513 m_os <<
'<' << name;
15514 m_tags.push_back( name );
15515 m_tagIsOpen =
true;
15516 applyFormatting(fmt);
15520 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string
const& name, XmlFormatting fmt ) {
15521 ScopedElement scoped(
this, fmt );
15522 startElement( name, fmt );
15526 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15527 m_indent = m_indent.substr(0, m_indent.size() - 2);
15529 if( m_tagIsOpen ) {
15531 m_tagIsOpen =
false;
15533 newlineIfNecessary();
15534 if (shouldIndent(fmt)) {
15537 m_os <<
"</" << m_tags.back() <<
">";
15539 m_os << std::flush;
15540 applyFormatting(fmt);
15545 XmlWriter& XmlWriter::writeAttribute( std::string
const& name, std::string
const& attribute ) {
15546 if( !name.empty() && !attribute.empty() )
15547 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15551 XmlWriter& XmlWriter::writeAttribute( std::string
const& name,
bool attribute ) {
15552 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15556 XmlWriter& XmlWriter::writeText( std::string
const& text, XmlFormatting fmt) {
15557 if( !text.empty() ){
15558 bool tagWasOpen = m_tagIsOpen;
15560 if (tagWasOpen && shouldIndent(fmt)) {
15563 m_os << XmlEncode( text );
15564 applyFormatting(fmt);
15569 XmlWriter& XmlWriter::writeComment( std::string
const& text, XmlFormatting fmt) {
15571 if (shouldIndent(fmt)) {
15574 m_os <<
"<!--" << text <<
"-->";
15575 applyFormatting(fmt);
15579 void XmlWriter::writeStylesheetRef( std::string
const& url ) {
15580 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15583 XmlWriter& XmlWriter::writeBlankLine() {
15589 void XmlWriter::ensureTagClosed() {
15590 if( m_tagIsOpen ) {
15591 m_os << '>
' << std::flush;
15592 newlineIfNecessary();
15593 m_tagIsOpen = false;
15597 void XmlWriter::applyFormatting(XmlFormatting fmt) {
15598 m_needsNewline = shouldNewline(fmt);
15601 void XmlWriter::writeDeclaration() {
15602 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15605 void XmlWriter::newlineIfNecessary() {
15606 if( m_needsNewline ) {
15608 m_needsNewline = false;
15612 // end catch_xmlwriter.cpp
15613 // start catch_reporter_bases.cpp
15622 void prepareExpandedExpression(AssertionResult& result) {
15623 result.getExpandedExpression();
15626 // Because formatting using c++ streams is stateful, drop down to C is required
15627 // Alternatively we could use stringstream, but its performance is... not good.
15628 std::string getFormattedDuration( double duration ) {
15629 // Max exponent + 1 is required to represent the whole part
15630 // + 1 for decimal point
15631 // + 3 for the 3 decimal places
15632 // + 1 for null terminator
15633 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15634 char buffer[maxDoubleSize];
15636 // Save previous errno, to prevent sprintf from overwriting it
15639 sprintf_s(buffer, "%.3f", duration);
15641 std::sprintf(buffer, "%.3f", duration);
15643 return std::string(buffer);
15646 bool shouldShowDuration( IConfig const& config, double duration ) {
15647 if ( config.showDurations() == ShowDurations::Always ) {
15650 if ( config.showDurations() == ShowDurations::Never ) {
15653 const double min = config.minDuration();
15654 return min >= 0 && duration >= min;
15657 std::string serializeFilters( std::vector<std::string> const& container ) {
15658 ReusableStringStream oss;
15660 for (auto&& filter : container)
15672 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15673 :StreamingReporterBase(_config) {}
15675 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15676 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15679 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15681 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15685 } // end namespace Catch
15686 // end catch_reporter_bases.cpp
15687 // start catch_reporter_compact.cpp
15691 #ifdef CATCH_PLATFORM_MAC
15692 const char* failedString() { return "FAILED"; }
15693 const char* passedString() { return "PASSED"; }
15695 const char* failedString() { return "failed"; }
15696 const char* passedString() { return "passed"; }
15699 // Colour::LightGrey
15700 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15702 std::string bothOrAll( std::size_t count ) {
15703 return count == 1 ? std::string() :
15704 count == 2 ? "both " : "all " ;
15707 } // anon namespace
15711 // Colour, message variants:
15712 // - white: No tests ran.
15713 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15714 // - white: Passed [both/all] N test cases (no assertions).
15715 // - red: Failed N tests cases, failed M assertions.
15716 // - green: Passed [both/all] N tests cases with M assertions.
15717 void printTotals(std::ostream& out, const Totals& totals) {
15718 if (totals.testCases.total() == 0) {
15719 out << "No tests ran.";
15720 } else if (totals.testCases.failed == totals.testCases.total()) {
15721 Colour colour(Colour::ResultError);
15722 const std::string qualify_assertions_failed =
15723 totals.assertions.failed == totals.assertions.total() ?
15724 bothOrAll(totals.assertions.failed) : std::string();
15726 "Failed " << bothOrAll(totals.testCases.failed)
15727 << pluralise(totals.testCases.failed, "test case") << ", "
15728 "failed " << qualify_assertions_failed <<
15729 pluralise(totals.assertions.failed, "assertion") << '.
';
15730 } else if (totals.assertions.total() == 0) {
15732 "Passed " << bothOrAll(totals.testCases.total())
15733 << pluralise(totals.testCases.total(), "test case")
15734 << " (no assertions).";
15735 } else if (totals.assertions.failed) {
15736 Colour colour(Colour::ResultError);
15738 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15739 "failed " << pluralise(totals.assertions.failed, "assertion") << '.
';
15741 Colour colour(Colour::ResultSuccess);
15743 "Passed " << bothOrAll(totals.testCases.passed)
15744 << pluralise(totals.testCases.passed, "test case") <<
15745 " with " << pluralise(totals.assertions.passed, "assertion") << '.
';
15749 // Implementation of CompactReporter formatting
15750 class AssertionPrinter {
15752 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15753 AssertionPrinter(AssertionPrinter const&) = delete;
15754 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15756 , result(_stats.assertionResult)
15757 , messages(_stats.infoMessages)
15758 , itMessage(_stats.infoMessages.begin())
15759 , printInfoMessages(_printInfoMessages) {}
15764 itMessage = messages.begin();
15766 switch (result.getResultType()) {
15767 case ResultWas::Ok:
15768 printResultType(Colour::ResultSuccess, passedString());
15769 printOriginalExpression();
15770 printReconstructedExpression();
15771 if (!result.hasExpression())
15772 printRemainingMessages(Colour::None);
15774 printRemainingMessages();
15776 case ResultWas::ExpressionFailed:
15778 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15780 printResultType(Colour::Error, failedString());
15781 printOriginalExpression();
15782 printReconstructedExpression();
15783 printRemainingMessages();
15785 case ResultWas::ThrewException:
15786 printResultType(Colour::Error, failedString());
15787 printIssue("unexpected exception with message:");
15789 printExpressionWas();
15790 printRemainingMessages();
15792 case ResultWas::FatalErrorCondition:
15793 printResultType(Colour::Error, failedString());
15794 printIssue("fatal error condition with message:");
15796 printExpressionWas();
15797 printRemainingMessages();
15799 case ResultWas::DidntThrowException:
15800 printResultType(Colour::Error, failedString());
15801 printIssue("expected exception, got none");
15802 printExpressionWas();
15803 printRemainingMessages();
15805 case ResultWas::Info:
15806 printResultType(Colour::None, "info");
15808 printRemainingMessages();
15810 case ResultWas::Warning:
15811 printResultType(Colour::None, "warning");
15813 printRemainingMessages();
15815 case ResultWas::ExplicitFailure:
15816 printResultType(Colour::Error, failedString());
15817 printIssue("explicitly");
15818 printRemainingMessages(Colour::None);
15820 // These cases are here to prevent compiler warnings
15821 case ResultWas::Unknown:
15822 case ResultWas::FailureBit:
15823 case ResultWas::Exception:
15824 printResultType(Colour::Error, "** internal error **");
15830 void printSourceInfo() const {
15831 Colour colourGuard(Colour::FileName);
15832 stream << result.getSourceInfo() << ':
';
15835 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15836 if (!passOrFail.empty()) {
15838 Colour colourGuard(colour);
15839 stream << ' ' << passOrFail;
15845 void printIssue(std::string const& issue) const {
15846 stream << ' ' << issue;
15849 void printExpressionWas() {
15850 if (result.hasExpression()) {
15853 Colour colour(dimColour());
15854 stream << " expression was:";
15856 printOriginalExpression();
15860 void printOriginalExpression() const {
15861 if (result.hasExpression()) {
15862 stream << ' ' << result.getExpression();
15866 void printReconstructedExpression() const {
15867 if (result.hasExpandedExpression()) {
15869 Colour colour(dimColour());
15870 stream << " for: ";
15872 stream << result.getExpandedExpression();
15876 void printMessage() {
15877 if (itMessage != messages.end()) {
15878 stream << " '" << itMessage->message << '\'';
15883 void printRemainingMessages(Colour::Code colour = dimColour()) {
15884 if (itMessage == messages.end())
15887 const auto itEnd = messages.cend();
15888 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
15891 Colour colourGuard(colour);
15892 stream << " with
" << pluralise(N, "message
") << ':';
15895 while (itMessage != itEnd) {
15896 // If this assertion is a warning ignore any INFO messages
15897 if (printInfoMessages || itMessage->type != ResultWas::Info) {
15899 if (itMessage != itEnd) {
15900 Colour colourGuard(dimColour());
15910 std::ostream& stream;
15911 AssertionResult const& result;
15912 std::vector<MessageInfo> messages;
15913 std::vector<MessageInfo>::const_iterator itMessage;
15914 bool printInfoMessages;
15917 } // anon namespace
15919 std::string CompactReporter::getDescription() {
15920 return "Reports test results on a single line, suitable
for IDEs
";
15923 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
15924 stream << "No test cases matched
'" << spec << '\
'' << std::endl;
15927 void CompactReporter::assertionStarting(
AssertionInfo const& ) {}
15929 bool CompactReporter::assertionEnded(
AssertionStats const& _assertionStats ) {
15932 bool printInfoMessages =
true;
15935 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
15936 if( result.getResultType() != ResultWas::Warning )
15938 printInfoMessages =
false;
15941 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
15944 stream << std::endl;
15948 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
15949 double dur = _sectionStats.durationInSeconds;
15950 if ( shouldShowDuration( *m_config, dur ) ) {
15951 stream << getFormattedDuration( dur ) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
15955 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
15956 printTotals( stream, _testRunStats.totals );
15957 stream <<
'\n' << std::endl;
15958 StreamingReporterBase::testRunEnded( _testRunStats );
15961 CompactReporter::~CompactReporter() {}
15963 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
15972 #if defined(_MSC_VER)
15973 #pragma warning(push)
15974 #pragma warning(disable:4061)
15978 #if defined(__clang__)
15979 # pragma clang diagnostic push
15981 # pragma clang diagnostic ignored "-Wunused-function"
15996 result(_stats.assertionResult),
15997 colour(Colour::None),
15998 message(result.getMessage()),
15999 messages(_stats.infoMessages),
16000 printInfoMessages(_printInfoMessages) {
16001 switch (result.getResultType()) {
16002 case ResultWas::Ok:
16003 colour = Colour::Success;
16004 passOrFail =
"PASSED";
16006 if (_stats.infoMessages.size() == 1)
16007 messageLabel =
"with message";
16008 if (_stats.infoMessages.size() > 1)
16009 messageLabel =
"with messages";
16011 case ResultWas::ExpressionFailed:
16012 if (result.isOk()) {
16013 colour = Colour::Success;
16014 passOrFail =
"FAILED - but was ok";
16016 colour = Colour::Error;
16017 passOrFail =
"FAILED";
16019 if (_stats.infoMessages.size() == 1)
16020 messageLabel =
"with message";
16021 if (_stats.infoMessages.size() > 1)
16022 messageLabel =
"with messages";
16024 case ResultWas::ThrewException:
16025 colour = Colour::Error;
16026 passOrFail =
"FAILED";
16027 messageLabel =
"due to unexpected exception with ";
16028 if (_stats.infoMessages.size() == 1)
16029 messageLabel +=
"message";
16030 if (_stats.infoMessages.size() > 1)
16031 messageLabel +=
"messages";
16033 case ResultWas::FatalErrorCondition:
16034 colour = Colour::Error;
16035 passOrFail =
"FAILED";
16036 messageLabel =
"due to a fatal error condition";
16038 case ResultWas::DidntThrowException:
16039 colour = Colour::Error;
16040 passOrFail =
"FAILED";
16041 messageLabel =
"because no exception was thrown where one was expected";
16043 case ResultWas::Info:
16044 messageLabel =
"info";
16046 case ResultWas::Warning:
16047 messageLabel =
"warning";
16049 case ResultWas::ExplicitFailure:
16050 passOrFail =
"FAILED";
16051 colour = Colour::Error;
16052 if (_stats.infoMessages.size() == 1)
16053 messageLabel =
"explicitly with message";
16054 if (_stats.infoMessages.size() > 1)
16055 messageLabel =
"explicitly with messages";
16058 case ResultWas::Unknown:
16059 case ResultWas::FailureBit:
16060 case ResultWas::Exception:
16061 passOrFail =
"** internal error **";
16062 colour = Colour::Error;
16067 void print()
const {
16069 if (stats.totals.assertions.total() > 0) {
16071 printOriginalExpression();
16072 printReconstructedExpression();
16080 void printResultType()
const {
16081 if (!passOrFail.empty()) {
16082 Colour colourGuard(colour);
16083 stream << passOrFail <<
":\n";
16086 void printOriginalExpression()
const {
16087 if (result.hasExpression()) {
16088 Colour colourGuard(Colour::OriginalExpression);
16090 stream << result.getExpressionInMacro();
16094 void printReconstructedExpression()
const {
16095 if (result.hasExpandedExpression()) {
16096 stream <<
"with expansion:\n";
16097 Colour colourGuard(Colour::ReconstructedExpression);
16098 stream <<
Column(result.getExpandedExpression()).indent(2) <<
'\n';
16101 void printMessage()
const {
16102 if (!messageLabel.empty())
16103 stream << messageLabel <<
':' <<
'\n';
16104 for (
auto const& msg : messages) {
16106 if (printInfoMessages || msg.type != ResultWas::Info)
16107 stream <<
Column(msg.message).indent(2) <<
'\n';
16110 void printSourceInfo()
const {
16111 Colour colourGuard(Colour::FileName);
16112 stream << result.getSourceInfo() <<
": ";
16115 std::ostream& stream;
16118 Colour::Code colour;
16119 std::string passOrFail;
16120 std::string messageLabel;
16121 std::string message;
16122 std::vector<MessageInfo> messages;
16123 bool printInfoMessages;
16126 std::size_t makeRatio(std::size_t number, std::size_t total) {
16127 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16128 return (ratio == 0 && number > 0) ? 1 : ratio;
16131 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16132 if (i > j && i > k)
16141 enum Justification { Left, Right };
16144 Justification justification;
16158 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16159 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16160 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16161 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16163 double m_inNanoseconds;
16167 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16168 : m_inNanoseconds(inNanoseconds),
16170 if (m_units == Unit::Auto) {
16171 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16172 m_units = Unit::Nanoseconds;
16173 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16174 m_units = Unit::Microseconds;
16175 else if (m_inNanoseconds < s_nanosecondsInASecond)
16176 m_units = Unit::Milliseconds;
16177 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16178 m_units = Unit::Seconds;
16180 m_units = Unit::Minutes;
16185 auto value()
const ->
double {
16187 case Unit::Microseconds:
16188 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16189 case Unit::Milliseconds:
16190 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16191 case Unit::Seconds:
16192 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16193 case Unit::Minutes:
16194 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16196 return m_inNanoseconds;
16199 auto unitsAsString()
const -> std::string {
16201 case Unit::Nanoseconds:
16203 case Unit::Microseconds:
16205 case Unit::Milliseconds:
16207 case Unit::Seconds:
16209 case Unit::Minutes:
16212 return "** internal error **";
16216 friend auto operator << (std::ostream& os,
Duration const& duration) -> std::ostream& {
16217 return os << duration.value() <<
' ' << duration.unitsAsString();
16223 std::ostream& m_os;
16224 std::vector<ColumnInfo> m_columnInfos;
16225 std::ostringstream m_oss;
16226 int m_currentColumn = -1;
16227 bool m_isOpen =
false;
16230 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16232 m_columnInfos( std::move( columnInfos ) ) {}
16234 auto columnInfos()
const -> std::vector<ColumnInfo>
const& {
16235 return m_columnInfos;
16241 *
this << RowBreak();
16245 for (
auto const& info : m_columnInfos) {
16246 headerCols +=
Column(info.name).width(
static_cast<std::size_t
>(info.width - 2));
16247 headerCols += spacer;
16249 m_os << headerCols <<
'\n';
16251 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16256 *
this << RowBreak();
16262 template<
typename T>
16269 auto colStr = tp.m_oss.str();
16270 const auto strSize = colStr.size();
16273 if (tp.m_currentColumn ==
static_cast<int>(tp.m_columnInfos.size() - 1)) {
16274 tp.m_currentColumn = -1;
16277 tp.m_currentColumn++;
16279 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16280 auto padding = (strSize + 1 <
static_cast<std::size_t
>(colInfo.width))
16281 ? std::string(colInfo.width - (strSize + 1),
' ')
16283 if (colInfo.justification == ColumnInfo::Left)
16284 tp.m_os << colStr << padding <<
' ';
16286 tp.m_os << padding << colStr <<
' ';
16291 if (tp.m_currentColumn > 0) {
16293 tp.m_currentColumn = -1;
16302 [&config]() -> std::vector<ColumnInfo> {
16303 if (config.fullConfig()->benchmarkNoAnalysis())
16306 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16307 {
" samples", 14, ColumnInfo::Right },
16308 {
" iterations", 14, ColumnInfo::Right },
16309 {
" mean", 14, ColumnInfo::Right }
16315 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16316 {
"samples mean std dev", 14, ColumnInfo::Right },
16317 {
"iterations low mean low std dev", 14, ColumnInfo::Right },
16318 {
"estimated high mean high std dev", 14, ColumnInfo::Right }
16322 ConsoleReporter::~ConsoleReporter() =
default;
16324 std::string ConsoleReporter::getDescription() {
16325 return "Reports test results as plain lines of text";
16328 void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16329 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16332 void ConsoleReporter::reportInvalidArguments(std::string
const&arg){
16333 stream <<
"Invalid Filter: " << arg << std::endl;
16336 void ConsoleReporter::assertionStarting(AssertionInfo
const&) {}
16338 bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16339 AssertionResult
const& result = _assertionStats.assertionResult;
16341 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16344 if (!includeResults && result.getResultType() != ResultWas::Warning)
16349 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16351 stream << std::endl;
16355 void ConsoleReporter::sectionStarting(SectionInfo
const& _sectionInfo) {
16356 m_tablePrinter->close();
16357 m_headerPrinted =
false;
16358 StreamingReporterBase::sectionStarting(_sectionInfo);
16360 void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16361 m_tablePrinter->close();
16362 if (_sectionStats.missingAssertions) {
16364 Colour colour(Colour::ResultError);
16365 if (m_sectionStack.size() > 1)
16366 stream <<
"\nNo assertions in section";
16368 stream <<
"\nNo assertions in test case";
16369 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16371 double dur = _sectionStats.durationInSeconds;
16372 if (shouldShowDuration(*m_config, dur)) {
16373 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16375 if (m_headerPrinted) {
16376 m_headerPrinted =
false;
16378 StreamingReporterBase::sectionEnded(_sectionStats);
16381 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16382 void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16383 lazyPrintWithoutClosingBenchmarkTable();
16385 auto nameCol = Column(name).width(
static_cast<std::size_t
>(m_tablePrinter->columnInfos()[0].width - 2));
16387 bool firstLine =
true;
16388 for (
auto line : nameCol) {
16390 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16394 (*m_tablePrinter) << line << ColumnBreak();
16398 void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16399 (*m_tablePrinter) << info.samples << ColumnBreak()
16400 << info.iterations << ColumnBreak();
16401 if (!m_config->benchmarkNoAnalysis())
16402 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16404 void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16405 if (m_config->benchmarkNoAnalysis())
16407 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16411 (*m_tablePrinter) << ColumnBreak()
16412 << Duration(stats.mean.point.count()) << ColumnBreak()
16413 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16414 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16415 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16416 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16417 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16421 void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16422 Colour colour(Colour::Red);
16424 <<
"Benchmark failed (" << error <<
')'
16425 << ColumnBreak() << RowBreak();
16429 void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16430 m_tablePrinter->close();
16431 StreamingReporterBase::testCaseEnded(_testCaseStats);
16432 m_headerPrinted =
false;
16434 void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16435 if (currentGroupInfo.used) {
16436 printSummaryDivider();
16437 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16438 printTotals(_testGroupStats.totals);
16439 stream <<
'\n' << std::endl;
16441 StreamingReporterBase::testGroupEnded(_testGroupStats);
16443 void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16444 printTotalsDivider(_testRunStats.totals);
16445 printTotals(_testRunStats.totals);
16446 stream << std::endl;
16447 StreamingReporterBase::testRunEnded(_testRunStats);
16449 void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16450 StreamingReporterBase::testRunStarting(_testInfo);
16451 printTestFilters();
16454 void ConsoleReporter::lazyPrint() {
16456 m_tablePrinter->close();
16457 lazyPrintWithoutClosingBenchmarkTable();
16460 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16462 if (!currentTestRunInfo.used)
16463 lazyPrintRunInfo();
16464 if (!currentGroupInfo.used)
16465 lazyPrintGroupInfo();
16467 if (!m_headerPrinted) {
16468 printTestCaseAndSectionHeader();
16469 m_headerPrinted =
true;
16472 void ConsoleReporter::lazyPrintRunInfo() {
16473 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16474 Colour colour(Colour::SecondaryText);
16475 stream << currentTestRunInfo->name
16476 <<
" is a Catch v" << libraryVersion() <<
" host application.\n"
16477 <<
"Run with -? for options\n\n";
16479 if (m_config->rngSeed() != 0)
16480 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16482 currentTestRunInfo.used =
true;
16484 void ConsoleReporter::lazyPrintGroupInfo() {
16485 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16486 printClosedHeader(
"Group: " + currentGroupInfo->name);
16487 currentGroupInfo.used =
true;
16490 void ConsoleReporter::printTestCaseAndSectionHeader() {
16491 assert(!m_sectionStack.empty());
16492 printOpenHeader(currentTestCaseInfo->name);
16494 if (m_sectionStack.size() > 1) {
16495 Colour colourGuard(Colour::Headers);
16498 it = m_sectionStack.begin() + 1,
16499 itEnd = m_sectionStack.end();
16500 for (; it != itEnd; ++it)
16501 printHeaderString(it->name, 2);
16504 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16506 stream << getLineOfChars<
'-'>() <<
'\n';
16507 Colour colourGuard(Colour::FileName);
16508 stream << lineInfo <<
'\n';
16509 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16512 void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16513 printOpenHeader(_name);
16514 stream << getLineOfChars<
'.'>() <<
'\n';
16516 void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16517 stream << getLineOfChars<
'-'>() <<
'\n';
16519 Colour colourGuard(Colour::Headers);
16520 printHeaderString(_name);
16526 void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16527 std::size_t i = _string.find(
": ");
16528 if (i != std::string::npos)
16532 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16538 : label( std::move( _label ) ),
16539 colour( _colour ) {}
16543 std::string row = rss.str();
16544 for (
auto& oldRow : rows) {
16545 while (oldRow.size() < row.size())
16546 oldRow =
' ' + oldRow;
16547 while (oldRow.size() > row.size())
16550 rows.push_back(row);
16555 Colour::Code colour;
16556 std::vector<std::string> rows;
16560 void ConsoleReporter::printTotals(
Totals const& totals ) {
16561 if (totals.testCases.total() == 0) {
16562 stream <<
Colour(Colour::Warning) <<
"No tests ran\n";
16563 }
else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16564 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16566 << pluralise(totals.assertions.passed,
"assertion") <<
" in "
16567 << pluralise(totals.testCases.passed,
"test case") <<
')'
16571 std::vector<SummaryColumn> columns;
16572 columns.push_back(SummaryColumn(
"", Colour::None)
16573 .addRow(totals.testCases.total())
16574 .addRow(totals.assertions.total()));
16575 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16576 .addRow(totals.testCases.passed)
16577 .addRow(totals.assertions.passed));
16578 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16579 .addRow(totals.testCases.failed)
16580 .addRow(totals.assertions.failed));
16581 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16582 .addRow(totals.testCases.failedButOk)
16583 .addRow(totals.assertions.failedButOk));
16585 printSummaryRow(
"test cases", columns, 0);
16586 printSummaryRow(
"assertions", columns, 1);
16589 void ConsoleReporter::printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row) {
16590 for (
auto col : cols) {
16591 std::string value = col.rows[row];
16592 if (col.label.empty()) {
16593 stream << label <<
": ";
16597 stream << Colour(Colour::Warning) <<
"- none -";
16598 }
else if (value !=
"0") {
16599 stream << Colour(Colour::LightGrey) <<
" | ";
16600 stream << Colour(col.colour)
16601 << value <<
' ' << col.label;
16607 void ConsoleReporter::printTotalsDivider(Totals
const& totals) {
16608 if (totals.testCases.total() > 0) {
16609 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16610 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16611 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16612 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16613 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16614 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16615 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16617 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16618 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16619 if (totals.testCases.allPassed())
16620 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16622 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16624 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16628 void ConsoleReporter::printSummaryDivider() {
16629 stream << getLineOfChars<
'-'>() <<
'\n';
16632 void ConsoleReporter::printTestFilters() {
16633 if (m_config->testSpec().hasFilters()) {
16634 Colour guard(Colour::BrightYellow);
16635 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16639 CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16643 #if defined(_MSC_VER)
16644 #pragma warning(pop)
16647 #if defined(__clang__)
16648 # pragma clang diagnostic pop
16656 #include <algorithm>
16661 std::string getCurrentTimestamp() {
16665 std::time(&rawtime);
16666 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16669 std::tm timeInfo = {};
16670 gmtime_s(&timeInfo, &rawtime);
16673 timeInfo = std::gmtime(&rawtime);
16676 char timeStamp[timeStampSize];
16677 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16680 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16682 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16684 return std::string(timeStamp);
16687 std::string fileNameTag(
const std::vector<std::string> &tags) {
16688 auto it = std::find_if(begin(tags),
16690 [] (std::string
const& tag) {
return tag.front() ==
'#'; });
16691 if (it != tags.end())
16692 return it->substr(1);
16693 return std::string();
16697 JunitReporter::JunitReporter( ReporterConfig
const& _config )
16698 : CumulativeReporterBase( _config ),
16699 xml( _config.stream() )
16701 m_reporterPrefs.shouldRedirectStdOut =
true;
16702 m_reporterPrefs.shouldReportAllAssertions =
true;
16705 JunitReporter::~JunitReporter() {}
16707 std::string JunitReporter::getDescription() {
16708 return "Reports test results in an XML format that looks like Ant's junitreport target";
16711 void JunitReporter::noMatchingTestCases( std::string
const& ) {}
16713 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16714 CumulativeReporterBase::testRunStarting( runInfo );
16715 xml.startElement(
"testsuites" );
16718 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16719 suiteTimer.start();
16720 stdOutForSuite.clear();
16721 stdErrForSuite.clear();
16722 unexpectedExceptions = 0;
16723 CumulativeReporterBase::testGroupStarting( groupInfo );
16726 void JunitReporter::testCaseStarting( TestCaseInfo
const& testCaseInfo ) {
16727 m_okToFail = testCaseInfo.okToFail();
16730 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16731 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16732 unexpectedExceptions++;
16733 return CumulativeReporterBase::assertionEnded( assertionStats );
16736 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16737 stdOutForSuite += testCaseStats.stdOut;
16738 stdErrForSuite += testCaseStats.stdErr;
16739 CumulativeReporterBase::testCaseEnded( testCaseStats );
16742 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16743 double suiteTime = suiteTimer.getElapsedSeconds();
16744 CumulativeReporterBase::testGroupEnded( testGroupStats );
16745 writeGroup( *m_testGroups.back(), suiteTime );
16748 void JunitReporter::testRunEndedCumulative() {
16752 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16753 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
16755 TestGroupStats
const& stats = groupNode.value;
16756 xml.writeAttribute(
"name", stats.groupInfo.name );
16757 xml.writeAttribute(
"errors", unexpectedExceptions );
16758 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16759 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16760 xml.writeAttribute(
"hostname",
"tbd" );
16761 if( m_config->showDurations() == ShowDurations::Never )
16762 xml.writeAttribute(
"time",
"" );
16764 xml.writeAttribute(
"time", suiteTime );
16765 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16768 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16769 auto properties = xml.scopedElement(
"properties");
16770 if (m_config->hasTestFilters()) {
16771 xml.scopedElement(
"property")
16772 .writeAttribute(
"name",
"filters")
16773 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16775 if (m_config->rngSeed() != 0) {
16776 xml.scopedElement(
"property")
16777 .writeAttribute(
"name",
"random-seed")
16778 .writeAttribute(
"value", m_config->rngSeed());
16783 for(
auto const& child : groupNode.children )
16784 writeTestCase( *child );
16786 xml.scopedElement(
"system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16787 xml.scopedElement(
"system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16790 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16791 TestCaseStats
const& stats = testCaseNode.value;
16795 assert( testCaseNode.children.size() == 1 );
16796 SectionNode
const& rootSection = *testCaseNode.children.front();
16798 std::string className = stats.testInfo.className;
16800 if( className.empty() ) {
16801 className = fileNameTag(stats.testInfo.tags);
16802 if ( className.empty() )
16803 className =
"global";
16806 if ( !m_config->name().empty() )
16807 className = m_config->name() + "." + className;
16809 writeSection( className,
"", rootSection );
16812 void JunitReporter::writeSection( std::string
const& className,
16813 std::string
const& rootName,
16814 SectionNode
const& sectionNode ) {
16815 std::string name = trim( sectionNode.stats.sectionInfo.name );
16816 if( !rootName.empty() )
16817 name = rootName + '/' + name;
16819 if( !sectionNode.assertions.empty() ||
16820 !sectionNode.stdOut.empty() ||
16821 !sectionNode.stdErr.empty() ) {
16822 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
16823 if( className.empty() ) {
16824 xml.writeAttribute(
"classname", name );
16825 xml.writeAttribute(
"name",
"root" );
16828 xml.writeAttribute(
"classname", className );
16829 xml.writeAttribute(
"name", name );
16831 xml.writeAttribute(
"time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
16836 xml.writeAttribute(
"status",
"run" );
16838 writeAssertions( sectionNode );
16840 if( !sectionNode.stdOut.empty() )
16841 xml.scopedElement(
"system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
16842 if( !sectionNode.stdErr.empty() )
16843 xml.scopedElement(
"system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
16845 for(
auto const& childNode : sectionNode.childSections )
16846 if( className.empty() )
16847 writeSection( name,
"", *childNode );
16849 writeSection( className, name, *childNode );
16852 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
16853 for(
auto const& assertion : sectionNode.assertions )
16854 writeAssertion( assertion );
16857 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
16858 AssertionResult
const& result = stats.assertionResult;
16859 if( !result.isOk() ) {
16860 std::string elementName;
16861 switch( result.getResultType() ) {
16862 case ResultWas::ThrewException:
16863 case ResultWas::FatalErrorCondition:
16864 elementName =
"error";
16866 case ResultWas::ExplicitFailure:
16867 case ResultWas::ExpressionFailed:
16868 case ResultWas::DidntThrowException:
16869 elementName =
"failure";
16873 case ResultWas::Info:
16874 case ResultWas::Warning:
16875 case ResultWas::Ok:
16876 case ResultWas::Unknown:
16877 case ResultWas::FailureBit:
16878 case ResultWas::Exception:
16879 elementName =
"internalError";
16883 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
16885 xml.writeAttribute(
"message", result.getExpression() );
16886 xml.writeAttribute(
"type", result.getTestMacroName() );
16888 ReusableStringStream rss;
16889 if (stats.totals.assertions.total() > 0) {
16890 rss <<
"FAILED" <<
":\n";
16891 if (result.hasExpression()) {
16893 rss << result.getExpressionInMacro();
16896 if (result.hasExpandedExpression()) {
16897 rss <<
"with expansion:\n";
16898 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16904 if( !result.getMessage().empty() )
16905 rss << result.getMessage() <<
'\n';
16906 for(
auto const& msg : stats.infoMessages )
16907 if( msg.type == ResultWas::Info )
16908 rss << msg.message <<
'\n';
16910 rss <<
"at " << result.getSourceInfo();
16911 xml.writeText( rss.str(), XmlFormatting::Newline );
16915 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
16925 ListeningReporter::ListeningReporter() {
16927 m_preferences.shouldReportAllAssertions =
true;
16930 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
16931 m_listeners.push_back( std::move( listener ) );
16934 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
16935 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
16936 m_reporter = std::move( reporter );
16937 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
16940 ReporterPreferences ListeningReporter::getPreferences()
const {
16941 return m_preferences;
16944 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
16945 return std::set<Verbosity>{ };
16948 void ListeningReporter::noMatchingTestCases( std::string
const& spec ) {
16949 for (
auto const& listener : m_listeners ) {
16950 listener->noMatchingTestCases( spec );
16952 m_reporter->noMatchingTestCases( spec );
16955 void ListeningReporter::reportInvalidArguments(std::string
const&arg){
16956 for (
auto const& listener : m_listeners ) {
16957 listener->reportInvalidArguments( arg );
16959 m_reporter->reportInvalidArguments( arg );
16962 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16963 void ListeningReporter::benchmarkPreparing( std::string
const& name ) {
16964 for (
auto const& listener : m_listeners) {
16965 listener->benchmarkPreparing(name);
16967 m_reporter->benchmarkPreparing(name);
16969 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
16970 for (
auto const& listener : m_listeners ) {
16971 listener->benchmarkStarting( benchmarkInfo );
16973 m_reporter->benchmarkStarting( benchmarkInfo );
16975 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
16976 for (
auto const& listener : m_listeners ) {
16977 listener->benchmarkEnded( benchmarkStats );
16979 m_reporter->benchmarkEnded( benchmarkStats );
16982 void ListeningReporter::benchmarkFailed( std::string
const& error ) {
16983 for (
auto const& listener : m_listeners) {
16984 listener->benchmarkFailed(error);
16986 m_reporter->benchmarkFailed(error);
16990 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
16991 for (
auto const& listener : m_listeners ) {
16992 listener->testRunStarting( testRunInfo );
16994 m_reporter->testRunStarting( testRunInfo );
16997 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16998 for (
auto const& listener : m_listeners ) {
16999 listener->testGroupStarting( groupInfo );
17001 m_reporter->testGroupStarting( groupInfo );
17004 void ListeningReporter::testCaseStarting( TestCaseInfo
const& testInfo ) {
17005 for (
auto const& listener : m_listeners ) {
17006 listener->testCaseStarting( testInfo );
17008 m_reporter->testCaseStarting( testInfo );
17011 void ListeningReporter::sectionStarting( SectionInfo
const& sectionInfo ) {
17012 for (
auto const& listener : m_listeners ) {
17013 listener->sectionStarting( sectionInfo );
17015 m_reporter->sectionStarting( sectionInfo );
17018 void ListeningReporter::assertionStarting( AssertionInfo
const& assertionInfo ) {
17019 for (
auto const& listener : m_listeners ) {
17020 listener->assertionStarting( assertionInfo );
17022 m_reporter->assertionStarting( assertionInfo );
17026 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17027 for(
auto const& listener : m_listeners ) {
17028 static_cast<void>( listener->assertionEnded( assertionStats ) );
17030 return m_reporter->assertionEnded( assertionStats );
17033 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
17034 for (
auto const& listener : m_listeners ) {
17035 listener->sectionEnded( sectionStats );
17037 m_reporter->sectionEnded( sectionStats );
17040 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17041 for (
auto const& listener : m_listeners ) {
17042 listener->testCaseEnded( testCaseStats );
17044 m_reporter->testCaseEnded( testCaseStats );
17047 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17048 for (
auto const& listener : m_listeners ) {
17049 listener->testGroupEnded( testGroupStats );
17051 m_reporter->testGroupEnded( testGroupStats );
17054 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17055 for (
auto const& listener : m_listeners ) {
17056 listener->testRunEnded( testRunStats );
17058 m_reporter->testRunEnded( testRunStats );
17061 void ListeningReporter::skipTest( TestCaseInfo
const& testInfo ) {
17062 for (
auto const& listener : m_listeners ) {
17063 listener->skipTest( testInfo );
17065 m_reporter->skipTest( testInfo );
17068 bool ListeningReporter::isMulti()
const {
17076 #if defined(_MSC_VER)
17077 #pragma warning(push)
17078 #pragma warning(disable:4061)
17084 XmlReporter::XmlReporter( ReporterConfig
const& _config )
17085 : StreamingReporterBase( _config ),
17086 m_xml(_config.stream())
17088 m_reporterPrefs.shouldRedirectStdOut =
true;
17089 m_reporterPrefs.shouldReportAllAssertions =
true;
17092 XmlReporter::~XmlReporter() =
default;
17094 std::string XmlReporter::getDescription() {
17095 return "Reports test results as an XML document";
17098 std::string XmlReporter::getStylesheetRef()
const {
17099 return std::string();
17102 void XmlReporter::writeSourceInfo( SourceLineInfo
const& sourceInfo ) {
17104 .writeAttribute(
"filename", sourceInfo.file )
17105 .writeAttribute(
"line", sourceInfo.line );
17108 void XmlReporter::noMatchingTestCases( std::string
const& s ) {
17109 StreamingReporterBase::noMatchingTestCases( s );
17112 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17113 StreamingReporterBase::testRunStarting( testInfo );
17114 std::string stylesheetRef = getStylesheetRef();
17115 if( !stylesheetRef.empty() )
17116 m_xml.writeStylesheetRef( stylesheetRef );
17117 m_xml.startElement(
"Catch" );
17118 if( !m_config->name().empty() )
17119 m_xml.writeAttribute(
"name", m_config->name() );
17120 if (m_config->testSpec().hasFilters())
17121 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17122 if( m_config->rngSeed() != 0 )
17123 m_xml.scopedElement(
"Randomness" )
17124 .writeAttribute(
"seed", m_config->rngSeed() );
17127 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17128 StreamingReporterBase::testGroupStarting( groupInfo );
17129 m_xml.startElement(
"Group" )
17130 .writeAttribute(
"name", groupInfo.name );
17133 void XmlReporter::testCaseStarting( TestCaseInfo
const& testInfo ) {
17134 StreamingReporterBase::testCaseStarting(testInfo);
17135 m_xml.startElement(
"TestCase" )
17136 .writeAttribute(
"name", trim( testInfo.name ) )
17137 .writeAttribute(
"description", testInfo.description )
17138 .writeAttribute(
"tags", testInfo.tagsAsString() );
17140 writeSourceInfo( testInfo.lineInfo );
17142 if ( m_config->showDurations() == ShowDurations::Always )
17143 m_testCaseTimer.start();
17144 m_xml.ensureTagClosed();
17147 void XmlReporter::sectionStarting( SectionInfo
const& sectionInfo ) {
17148 StreamingReporterBase::sectionStarting( sectionInfo );
17149 if( m_sectionDepth++ > 0 ) {
17150 m_xml.startElement(
"Section" )
17151 .writeAttribute(
"name", trim( sectionInfo.name ) );
17152 writeSourceInfo( sectionInfo.lineInfo );
17153 m_xml.ensureTagClosed();
17157 void XmlReporter::assertionStarting( AssertionInfo
const& ) { }
17159 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17161 AssertionResult
const& result = assertionStats.assertionResult;
17163 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17165 if( includeResults || result.getResultType() == ResultWas::Warning ) {
17167 for(
auto const& msg : assertionStats.infoMessages ) {
17168 if( msg.type == ResultWas::Info && includeResults ) {
17169 m_xml.scopedElement(
"Info" )
17170 .writeText( msg.message );
17171 }
else if ( msg.type == ResultWas::Warning ) {
17172 m_xml.scopedElement(
"Warning" )
17173 .writeText( msg.message );
17179 if( !includeResults && result.getResultType() != ResultWas::Warning )
17183 if( result.hasExpression() ) {
17184 m_xml.startElement(
"Expression" )
17185 .writeAttribute(
"success", result.succeeded() )
17186 .writeAttribute(
"type", result.getTestMacroName() );
17188 writeSourceInfo( result.getSourceInfo() );
17190 m_xml.scopedElement(
"Original" )
17191 .writeText( result.getExpression() );
17192 m_xml.scopedElement(
"Expanded" )
17193 .writeText( result.getExpandedExpression() );
17197 switch( result.getResultType() ) {
17198 case ResultWas::ThrewException:
17199 m_xml.startElement(
"Exception" );
17200 writeSourceInfo( result.getSourceInfo() );
17201 m_xml.writeText( result.getMessage() );
17202 m_xml.endElement();
17204 case ResultWas::FatalErrorCondition:
17205 m_xml.startElement(
"FatalErrorCondition" );
17206 writeSourceInfo( result.getSourceInfo() );
17207 m_xml.writeText( result.getMessage() );
17208 m_xml.endElement();
17210 case ResultWas::Info:
17211 m_xml.scopedElement(
"Info" )
17212 .writeText( result.getMessage() );
17214 case ResultWas::Warning:
17217 case ResultWas::ExplicitFailure:
17218 m_xml.startElement(
"Failure" );
17219 writeSourceInfo( result.getSourceInfo() );
17220 m_xml.writeText( result.getMessage() );
17221 m_xml.endElement();
17227 if( result.hasExpression() )
17228 m_xml.endElement();
17233 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17234 StreamingReporterBase::sectionEnded( sectionStats );
17235 if( --m_sectionDepth > 0 ) {
17236 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
17237 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17238 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17239 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17241 if ( m_config->showDurations() == ShowDurations::Always )
17242 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17244 m_xml.endElement();
17248 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17249 StreamingReporterBase::testCaseEnded( testCaseStats );
17250 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
17251 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17253 if ( m_config->showDurations() == ShowDurations::Always )
17254 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17256 if( !testCaseStats.stdOut.empty() )
17257 m_xml.scopedElement(
"StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17258 if( !testCaseStats.stdErr.empty() )
17259 m_xml.scopedElement(
"StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17261 m_xml.endElement();
17264 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17265 StreamingReporterBase::testGroupEnded( testGroupStats );
17267 m_xml.scopedElement(
"OverallResults" )
17268 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17269 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17270 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17271 m_xml.scopedElement(
"OverallResultsCases")
17272 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed )
17273 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed )
17274 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk );
17275 m_xml.endElement();
17278 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17279 StreamingReporterBase::testRunEnded( testRunStats );
17280 m_xml.scopedElement(
"OverallResults" )
17281 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17282 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17283 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17284 m_xml.scopedElement(
"OverallResultsCases")
17285 .writeAttribute(
"successes", testRunStats.totals.testCases.passed )
17286 .writeAttribute(
"failures", testRunStats.totals.testCases.failed )
17287 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk );
17288 m_xml.endElement();
17291 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17292 void XmlReporter::benchmarkPreparing(std::string
const& name) {
17293 m_xml.startElement(
"BenchmarkResults")
17294 .writeAttribute(
"name", name);
17297 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &info) {
17298 m_xml.writeAttribute(
"samples", info.samples)
17299 .writeAttribute(
"resamples", info.resamples)
17300 .writeAttribute(
"iterations", info.iterations)
17301 .writeAttribute(
"clockResolution", info.clockResolution)
17302 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17303 .writeComment(
"All values in nano seconds");
17306 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17307 m_xml.startElement(
"mean")
17308 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17309 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17310 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17311 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17312 m_xml.endElement();
17313 m_xml.startElement(
"standardDeviation")
17314 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17315 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17316 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17317 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17318 m_xml.endElement();
17319 m_xml.startElement(
"outliers")
17320 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17321 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17322 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17323 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17324 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17325 m_xml.endElement();
17326 m_xml.endElement();
17329 void XmlReporter::benchmarkFailed(std::string
const &error) {
17330 m_xml.scopedElement(
"failed").
17331 writeAttribute(
"message", error);
17332 m_xml.endElement();
17336 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17340 #if defined(_MSC_VER)
17341 #pragma warning(pop)
17346 LeakDetector leakDetector;
17350 #pragma clang diagnostic pop
17356 #ifdef CATCH_CONFIG_MAIN
17361 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17363 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17366 int main (
int argc,
char * argv[]) {
17375 int main (
int argc,
char *
const argv[]) {
17376 #if !CATCH_ARC_ENABLED
17377 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17380 Catch::registerTestMethods();
17383 #if !CATCH_ARC_ENABLED
17395 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17397 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17398 # undef CLARA_CONFIG_MAIN
17401 #if !defined(CATCH_CONFIG_DISABLE)
17404 #ifdef CATCH_CONFIG_PREFIX_ALL
17406 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17407 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17409 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17410 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17411 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17412 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17413 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17415 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17417 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17418 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17419 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17420 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17421 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17423 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17424 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17425 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17426 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17427 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17429 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17431 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17432 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17434 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17437 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17438 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17439 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17440 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17442 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17443 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17444 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17445 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17446 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17447 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17448 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17449 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17450 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17452 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17454 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17455 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17456 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17457 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17458 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17459 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17460 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17461 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17462 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17464 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17465 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17466 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17467 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17468 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17469 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17470 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17471 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17474 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17475 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
17476 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17478 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
17479 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17483 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17484 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17485 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17486 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17487 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17488 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17489 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17490 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17492 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17493 #define CATCH_BENCHMARK(...) \
17494 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__,,))
17495 #define CATCH_BENCHMARK_ADVANCED(name) \
17496 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17502 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17503 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17505 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17506 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17507 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17508 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17509 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17511 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17513 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17514 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17515 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17516 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17517 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17519 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17520 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17521 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17522 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17523 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17525 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17527 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17528 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17530 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17533 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17534 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17535 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17536 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17538 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17539 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17540 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17541 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17542 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17543 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17544 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17545 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17546 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17547 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17549 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17550 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17551 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17552 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17553 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17554 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17555 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17556 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17557 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17558 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17559 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17561 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17562 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17563 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17564 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17565 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17566 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17567 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17568 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17569 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17570 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17573 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17574 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17575 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17577 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
17578 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17583 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17586 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17587 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17589 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17590 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17591 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17592 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17593 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17594 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17596 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17597 #define BENCHMARK(...) \
17598 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__,,))
17599 #define BENCHMARK_ADVANCED(name) \
17600 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17609 #ifdef CATCH_CONFIG_PREFIX_ALL
17611 #define CATCH_REQUIRE( ... ) (void)(0)
17612 #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
17614 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17615 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17616 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17617 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17618 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17620 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17622 #define CATCH_CHECK( ... ) (void)(0)
17623 #define CATCH_CHECK_FALSE( ... ) (void)(0)
17624 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
17625 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17626 #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
17628 #define CATCH_CHECK_THROWS( ... ) (void)(0)
17629 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17630 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17631 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17632 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17634 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17636 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17637 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
17639 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17642 #define CATCH_INFO( msg ) (void)(0)
17643 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17644 #define CATCH_WARN( msg ) (void)(0)
17645 #define CATCH_CAPTURE( msg ) (void)(0)
17647 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17648 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17649 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
17650 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17651 #define CATCH_SECTION( ... )
17652 #define CATCH_DYNAMIC_SECTION( ... )
17653 #define CATCH_FAIL( ... ) (void)(0)
17654 #define CATCH_FAIL_CHECK( ... ) (void)(0)
17655 #define CATCH_SUCCEED( ... ) (void)(0)
17657 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17659 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17660 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17661 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17662 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17663 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17664 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17665 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17666 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17667 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17669 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17670 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17671 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17672 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17673 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17674 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17675 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17676 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17680 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17681 #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 )
17682 #define CATCH_GIVEN( desc )
17683 #define CATCH_AND_GIVEN( desc )
17684 #define CATCH_WHEN( desc )
17685 #define CATCH_AND_WHEN( desc )
17686 #define CATCH_THEN( desc )
17687 #define CATCH_AND_THEN( desc )
17689 #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
17690 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17695 #define REQUIRE( ... ) (void)(0)
17696 #define REQUIRE_FALSE( ... ) (void)(0)
17698 #define REQUIRE_THROWS( ... ) (void)(0)
17699 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17700 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17701 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17702 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17704 #define REQUIRE_NOTHROW( ... ) (void)(0)
17706 #define CHECK( ... ) (void)(0)
17707 #define CHECK_FALSE( ... ) (void)(0)
17708 #define CHECKED_IF( ... ) if (__VA_ARGS__)
17709 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17710 #define CHECK_NOFAIL( ... ) (void)(0)
17712 #define CHECK_THROWS( ... ) (void)(0)
17713 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17714 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17715 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17716 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17718 #define CHECK_NOTHROW( ... ) (void)(0)
17720 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17721 #define CHECK_THAT( arg, matcher ) (void)(0)
17723 #define REQUIRE_THAT( arg, matcher ) (void)(0)
17726 #define INFO( msg ) (void)(0)
17727 #define UNSCOPED_INFO( msg ) (void)(0)
17728 #define WARN( msg ) (void)(0)
17729 #define CAPTURE( msg ) (void)(0)
17731 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17732 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17733 #define METHOD_AS_TEST_CASE( method, ... )
17734 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17735 #define SECTION( ... )
17736 #define DYNAMIC_SECTION( ... )
17737 #define FAIL( ... ) (void)(0)
17738 #define FAIL_CHECK( ... ) (void)(0)
17739 #define SUCCEED( ... ) (void)(0)
17740 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17742 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17743 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17744 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17745 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17746 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17747 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17748 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17749 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17750 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17752 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17753 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17754 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17755 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17756 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17757 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17758 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17759 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17762 #define STATIC_REQUIRE( ... ) (void)(0)
17763 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17767 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17770 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
17771 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17773 #define GIVEN( desc )
17774 #define AND_GIVEN( desc )
17775 #define WHEN( desc )
17776 #define AND_WHEN( desc )
17777 #define THEN( desc )
17778 #define AND_THEN( desc )
17791 # pragma warning(pop)
17793 # pragma clang diagnostic pop
17795 #elif defined __GNUC__
17796 # pragma GCC diagnostic pop
Definition: catch.hpp:2555
Definition: catch.hpp:5399
Definition: catch.hpp:2231
Definition: catch.hpp:2659
Definition: catch.hpp:5319
Definition: catch.hpp:10290
Definition: catch.hpp:3085
Definition: catch.hpp:10556
Definition: catch.hpp:1571
Definition: catch.hpp:13608
Definition: catch.hpp:13622
Definition: catch.hpp:13592
Definition: catch.hpp:13546
Definition: catch.hpp:10057
Definition: catch.hpp:3028
Definition: catch.hpp:10655
Definition: catch.hpp:2345
Definition: catch.hpp:3926
Definition: catch.hpp:4299
Definition: catch.hpp:4163
Definition: catch.hpp:3974
Definition: catch.hpp:3852
Definition: catch.hpp:3993
Definition: catch.hpp:4017
Definition: catch.hpp:4714
Definition: catch.hpp:4258
Definition: catch.hpp:4605
Definition: catch.hpp:4627
Definition: catch.hpp:4669
Definition: catch.hpp:4202
Definition: catch.hpp:3960
Definition: catch.hpp:4127
Definition: catch.hpp:6327
Definition: catch.hpp:2533
Definition: catch.hpp:6072
Definition: catch.hpp:10961
Definition: catch.hpp:3777
Definition: catch.hpp:3406
Definition: catch.hpp:3502
Definition: catch.hpp:3250
Definition: catch.hpp:498
Definition: catch.hpp:4875
Definition: catch.hpp:4411
Definition: catch.hpp:11966
Definition: catch.hpp:11915
Definition: catch.hpp:11904
Definition: catch.hpp:11894
Definition: catch.hpp:11924
Definition: catch.hpp:6051
Definition: catch.hpp:12278
Definition: catch.hpp:1447
Definition: catch.hpp:8081
Definition: catch.hpp:2648
Definition: catch.hpp:2918
Definition: catch.hpp:13117
Definition: catch.hpp:4560
Definition: catch.hpp:12367
Definition: catch.hpp:12342
Definition: catch.hpp:613
Definition: catch.hpp:16222
Definition: catch.hpp:12321
Definition: catch.hpp:11946
Definition: catch.hpp:4809
Definition: catch.hpp:7489
Definition: catch.hpp:7601
Definition: catch.hpp:7552
Definition: catch.hpp:7527
Definition: catch.hpp:12257
Definition: catch.hpp:969
Definition: catch.hpp:12238
Definition: catch.hpp:5113
Definition: catch.hpp:5203
Definition: catch.hpp:2901
Definition: catch.hpp:2307
Definition: catch.hpp:5082
Definition: catch.hpp:6234
Definition: catch.hpp:6375
Definition: catch.hpp:6252
Definition: catch.hpp:6249
Definition: catch.hpp:15989
Definition: catch.hpp:16149
Definition: catch.hpp:10174
Definition: catch.hpp:12395
Definition: catch.hpp:13229
Definition: catch.hpp:10103
Definition: catch.hpp:8519
Definition: catch.hpp:8512
Definition: catch.hpp:8694
Definition: catch.hpp:8689
Definition: catch.hpp:8681
Definition: catch.hpp:9361
Definition: catch.hpp:8845
Definition: catch.hpp:9017
Definition: catch.hpp:9257
Definition: catch.hpp:9319
Definition: catch.hpp:9395
Definition: catch.hpp:9065
Definition: catch.hpp:9244
Definition: catch.hpp:9268
Definition: catch.hpp:8956
Definition: catch.hpp:8972
Definition: catch.hpp:8884
Definition: catch.hpp:4864
Definition: catch.hpp:1404
Definition: catch.hpp:2550
Definition: catch.hpp:5386
Definition: catch.hpp:5527
Definition: catch.hpp:993
Definition: catch.hpp:7294
Definition: catch.hpp:6616
Definition: catch.hpp:6599
Definition: catch.hpp:6551
Definition: catch.hpp:7393
Definition: catch.hpp:7077
Definition: catch.hpp:6786
Definition: catch.hpp:6657
Definition: catch.hpp:6667
Definition: catch.hpp:5434
Definition: catch.hpp:6903
Definition: catch.hpp:5455
Definition: catch.hpp:7200
Definition: catch.hpp:6824
Definition: catch.hpp:6468
Definition: catch.hpp:5614
Definition: catch.hpp:5625
Definition: catch.hpp:493
Definition: catch.hpp:5990
Definition: catch.hpp:6118
Definition: catch.hpp:5275
Definition: catch.hpp:6155
Definition: catch.hpp:2836
Definition: catch.hpp:5838
Definition: catch.hpp:5810
Definition: catch.hpp:5818
Definition: catch.hpp:5808
Definition: catch.hpp:2421
Definition: catch.hpp:1473
Definition: catch.hpp:1934
Definition: catch.hpp:14914
Definition: catch.hpp:13583
Definition: catch.hpp:8025
Definition: catch.hpp:12528
Definition: catch.hpp:3948
Definition: catch.hpp:4067
Definition: catch.hpp:5517
Definition: catch.hpp:4514
Definition: catch.hpp:4361
Definition: catch.hpp:3017
Definition: catch.hpp:3022
Definition: catch.hpp:3866
Definition: catch.hpp:4370
Definition: catch.hpp:1483
Definition: catch.hpp:2983
Definition: catch.hpp:2972
Definition: catch.hpp:5696
Definition: catch.hpp:5703
Definition: catch.hpp:2465
Definition: catch.hpp:4842
Definition: catch.hpp:12359
Definition: catch.hpp:1440
Definition: catch.hpp:5651
Definition: catch.hpp:5189
Definition: catch.hpp:587
Definition: catch.hpp:579
Definition: catch.hpp:2209
Definition: catch.hpp:5500
Definition: catch.hpp:7633
Definition: catch.hpp:3436
Definition: catch.hpp:3461
Definition: catch.hpp:3445
Definition: catch.hpp:3295
Definition: catch.hpp:3328
Definition: catch.hpp:3363
Definition: catch.hpp:3287
Definition: catch.hpp:3269
Definition: catch.hpp:3546
Definition: catch.hpp:3567
Definition: catch.hpp:3575
Definition: catch.hpp:3563
Definition: catch.hpp:3580
Definition: catch.hpp:3571
Definition: catch.hpp:3555
Definition: catch.hpp:3688
Definition: catch.hpp:3614
Definition: catch.hpp:3635
Definition: catch.hpp:3665
Definition: catch.hpp:3724
Definition: catch.hpp:2634
Definition: catch.hpp:2606
Definition: catch.hpp:2623
Definition: catch.hpp:556
Definition: catch.hpp:5481
Definition: catch.hpp:5494
Definition: catch.hpp:1384
Definition: catch.hpp:1360
Definition: catch.hpp:4495
Definition: catch.hpp:2883
Definition: catch.hpp:2867
Definition: catch.hpp:5543
Definition: catch.hpp:4490
Definition: catch.hpp:10765
Definition: catch.hpp:509
Definition: catch.hpp:541
Definition: catch.hpp:5736
Definition: catch.hpp:1622
Definition: catch.hpp:13655
Definition: catch.hpp:16535
Definition: catch.hpp:12307
Definition: catch.hpp:11167
Definition: catch.hpp:4774
Definition: catch.hpp:5560
Definition: catch.hpp:7474
Definition: catch.hpp:5974
Definition: catch.hpp:2528
Definition: catch.hpp:5580
Definition: catch.hpp:5513
Definition: catch.hpp:5597
Definition: catch.hpp:2849
Definition: catch.hpp:4500
Definition: catch.hpp:13168
Definition: catch.hpp:4505
Definition: catch.hpp:4484
Definition: catch.hpp:932
Definition: catch.hpp:16146
Definition: catch.hpp:16140
Definition: catch.hpp:10073
Definition: catch.hpp:10078
Definition: catch.hpp:16147
Definition: catch.hpp:14096
Definition: catch.hpp:9227
Definition: catch.hpp:9142
Definition: catch.hpp:9175
Definition: catch.hpp:9215
Definition: catch.hpp:9134
Definition: catch.hpp:9139
Definition: catch.hpp:9148
Definition: catch.hpp:9085
Definition: catch.hpp:9496
Definition: catch.hpp:9187
Definition: catch.hpp:9126
Definition: catch.hpp:9510
Definition: catch.hpp:8870
Definition: catch.hpp:8828
Definition: catch.hpp:2005
Definition: catch.hpp:2000
Definition: catch.hpp:935
Definition: catch.hpp:943
Definition: catch.hpp:2014
Definition: catch.hpp:3223
Definition: catch.hpp:2071
Definition: catch.hpp:934
Definition: catch.hpp:488