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 12 18 #define CATCH_VERSION_PATCH 1 21 # pragma clang system_header 22 #elif defined __GNUC__ 23 # pragma GCC system_header 29 # ifdef __ICC // icpc defines the __clang__ macro 30 # pragma warning(push) 31 # pragma warning(disable: 161 1682) 33 # pragma clang diagnostic push 34 # pragma clang diagnostic ignored "-Wpadded" 35 # pragma clang diagnostic ignored "-Wswitch-enum" 36 # pragma clang diagnostic ignored "-Wcovered-switch-default" 38 #elif defined __GNUC__ 42 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details 44 # pragma GCC diagnostic push 45 # pragma GCC diagnostic ignored "-Wunused-variable" 46 # pragma GCC diagnostic ignored "-Wpadded" 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 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 // Visual Studio 2015 or newer 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__) // Handle Clang masquerading for msvc 263 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) 264 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 265 # endif // MSVC_TRADITIONAL 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 329 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 332 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 333 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE 334 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 337 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) 338 # if defined(__clang__) && (__clang_major__ < 8) 342 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) 343 # define CATCH_CONFIG_NO_CPP17_VARIANT 345 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT 346 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) 348 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT 349 # endif // defined(__clang__) && (__clang_major__ < 8) 350 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) 351 #endif // defined(__has_include) 353 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) 354 # define CATCH_CONFIG_COUNTER 356 #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) 357 # define CATCH_CONFIG_WINDOWS_SEH 360 #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) 361 # define CATCH_CONFIG_POSIX_SIGNALS 364 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) 365 # define CATCH_CONFIG_WCHAR 368 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) 369 # define CATCH_CONFIG_CPP11_TO_STRING 372 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) 373 # define CATCH_CONFIG_CPP17_OPTIONAL 376 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 377 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 380 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) 381 # define CATCH_CONFIG_CPP17_STRING_VIEW 384 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) 385 # define CATCH_CONFIG_CPP17_VARIANT 388 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) 389 # define CATCH_CONFIG_CPP17_BYTE 392 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 393 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE 396 #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) 397 # define CATCH_CONFIG_NEW_CAPTURE 400 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 401 # define CATCH_CONFIG_DISABLE_EXCEPTIONS 404 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) 405 # define CATCH_CONFIG_POLYFILL_ISNAN 408 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) 409 # define CATCH_CONFIG_USE_ASYNC 412 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) 413 # define CATCH_CONFIG_ANDROID_LOGWRITE 416 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 417 # define CATCH_CONFIG_GLOBAL_NEXTAFTER 422 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) 423 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION 425 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) 426 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 428 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) 429 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS 431 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) 432 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS 434 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) 435 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS 437 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) 438 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS 443 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) 444 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) 447 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) 448 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 449 #elif defined(__clang__) && (__clang_major__ < 5) 450 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 453 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) 454 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 457 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 458 #define CATCH_TRY if ((true)) 459 #define CATCH_CATCH_ALL if ((false)) 460 #define CATCH_CATCH_ANON(type) if ((false)) 462 #define CATCH_TRY try 463 #define CATCH_CATCH_ALL catch (...) 464 #define CATCH_CATCH_ANON(type) catch (type) 467 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) 468 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 472 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line 473 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) 474 #ifdef CATCH_CONFIG_COUNTER 475 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) 477 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) 519 bool empty() const noexcept {
return file[0] ==
'\0'; }
547 #define CATCH_INTERNAL_LINEINFO \ 548 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) 559 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ 560 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 561 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 562 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ 563 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 577 virtual void invoke ()
const = 0;
586 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
587 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const&
config )
const = 0;
592 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
616 static constexpr
char const*
const s_empty =
"";
618 char const* m_start = s_empty;
622 constexpr
StringRef() noexcept = default;
624 StringRef(
char const* rawChars ) noexcept;
627 : m_start( rawChars ),
632 : m_start( stdString.c_str() ),
633 m_size( stdString.size() )
643 return !(*
this == other);
648 return m_start[
index];
652 constexpr
auto empty() const noexcept ->
bool {
661 auto c_str()
const ->
char const*;
670 auto data()
const noexcept ->
char const*;
673 return m_start[m_size] ==
'\0';
684 constexpr
auto operator "" _sr(
char const* rawChars, std::size_t
size ) noexcept ->
StringRef {
697 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ 698 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) 699 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) 700 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) 701 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) 702 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) 704 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 705 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ 707 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) 708 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) 710 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) 713 #define CATCH_REC_END(...) 714 #define CATCH_REC_OUT 716 #define CATCH_EMPTY() 717 #define CATCH_DEFER(id) id CATCH_EMPTY() 719 #define CATCH_REC_GET_END2() 0, CATCH_REC_END 720 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 721 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 722 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT 723 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) 724 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) 726 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 727 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) 728 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 730 #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__ ) 731 #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__ ) 732 #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__ ) 737 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 739 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 741 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) 742 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ 743 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ 744 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF 745 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) 746 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 747 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ 748 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) 751 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) 752 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ 753 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) 756 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ 757 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) 759 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) 761 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 762 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) 763 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) 765 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())) 766 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) 769 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ 770 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) 772 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) 773 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) 774 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) 775 #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) 776 #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) 777 #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) 778 #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, _4, _5, _6) 779 #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) 780 #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) 781 #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) 782 #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) 784 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N 786 #define INTERNAL_CATCH_TYPE_GEN\ 787 template<typename...> struct TypeList {};\ 788 template<typename...Ts>\ 789 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\ 790 template<template<typename...> class...> struct TemplateTypeList{};\ 791 template<template<typename...> class...Cs>\ 792 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\ 793 template<typename...>\ 795 template<typename...>\ 797 template<template<typename...> class, typename...>\ 799 template<template<typename...> class, typename>\ 802 template<typename T> \ 803 struct append<T> { using type = T; };\ 804 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\ 805 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\ 806 template< template<typename...> class L1, typename...E1, typename...Rest>\ 807 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\ 809 template< template<typename...> class Container, template<typename...> class List, typename...elems>\ 810 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\ 811 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\ 812 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\ 814 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\ 815 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\ 816 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\ 817 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; }; 819 #define INTERNAL_CATCH_NTTP_1(signature, ...)\ 820 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\ 821 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 822 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \ 823 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\ 824 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\ 825 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \ 827 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 828 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\ 829 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\ 830 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\ 831 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\ 832 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; }; 834 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName) 835 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\ 836 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 837 static void TestName() 838 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\ 839 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 840 static void TestName() 842 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName) 843 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\ 844 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 845 static void TestName() 846 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\ 847 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 848 static void TestName() 850 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\ 851 template<typename Type>\ 852 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\ 854 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 857 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\ 858 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 859 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\ 861 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 864 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\ 865 template<typename Type>\ 866 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 868 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 871 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\ 872 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 873 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 875 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 878 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName) 879 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\ 880 template<typename TestType> \ 881 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ 885 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\ 886 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 887 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ 891 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName) 892 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\ 893 template<typename TestType> \ 894 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test() 895 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\ 896 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 897 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test() 899 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 900 #define INTERNAL_CATCH_NTTP_0 901 #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) 902 #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__) 903 #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__) 904 #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__) 905 #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__) 906 #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__) 907 #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__) 908 #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__) 910 #define INTERNAL_CATCH_NTTP_0(signature) 911 #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__)) 912 #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__)) 913 #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__)) 914 #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__)) 915 #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__)) 916 #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__)) 917 #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__)) 918 #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__)) 925 #include <type_traits> 933 template <
typename Fun,
typename... Args>
935 template <
typename...>
939 template <
typename T>
942 template <
typename Fun,
typename... Args>
943 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
945 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 949 template <
typename Func,
typename U>
950 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
952 template <
typename Func,
typename U>
973 (obj.*m_testAsMethod)();
997 #if defined(CATCH_CONFIG_DISABLE) 998 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ 999 static void TestName() 1000 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ 1002 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1006 void TestName::test() 1007 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \ 1008 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1009 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1011 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1012 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1015 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1017 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1018 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1019 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__ ) 1021 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1022 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__ ) ) 1025 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1026 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1027 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__ ) 1029 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1030 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__ ) ) 1033 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1034 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1035 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__ ) 1037 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1038 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__ ) ) 1041 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1042 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1043 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__ ) 1045 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1046 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__ ) ) 1051 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ 1052 static void TestName(); \ 1053 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1054 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1055 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1056 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1057 static void TestName() 1058 #define INTERNAL_CATCH_TESTCASE( ... ) \ 1059 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) 1062 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ 1063 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1064 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1065 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1066 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1069 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ 1070 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1071 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1073 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1076 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \ 1078 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1079 void TestName::test() 1080 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ 1081 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) 1084 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ 1085 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1086 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1087 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \ 1088 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1091 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\ 1092 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1093 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1094 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1095 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1096 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1098 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1099 INTERNAL_CATCH_TYPE_GEN\ 1100 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1101 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1102 template<typename...Types> \ 1106 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1107 using expander = int[];\ 1108 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... }; \ 1111 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1112 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1117 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1118 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1120 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1121 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1122 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__ ) 1124 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1125 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__ ) ) 1128 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1129 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1130 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__ ) 1132 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1133 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__ ) ) 1136 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ 1137 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1138 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1139 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1140 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1141 template<typename TestType> static void TestFuncName(); \ 1143 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1144 INTERNAL_CATCH_TYPE_GEN \ 1145 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ 1146 template<typename... Types> \ 1148 void reg_tests() { \ 1150 using expander = int[]; \ 1151 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1152 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1153 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1154 (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++, 0)... };\ 1157 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1158 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; \ 1165 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1166 template<typename TestType> \ 1167 static void TestFuncName() 1169 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1170 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1171 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__) 1173 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1174 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__ ) ) 1177 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1178 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1179 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__) 1181 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1182 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__ ) ) 1185 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ 1186 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1187 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1188 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1189 template<typename TestType> static void TestFunc(); \ 1191 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1192 INTERNAL_CATCH_TYPE_GEN\ 1193 template<typename... Types> \ 1195 void reg_tests() { \ 1197 using expander = int[]; \ 1198 (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++, 0)... };\ 1201 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1202 using TestInit = typename convert<TestName, TmplList>::type; \ 1208 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1209 template<typename TestType> \ 1210 static void TestFunc() 1212 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ 1213 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 ) 1215 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1216 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1217 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1218 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1219 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1221 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1222 INTERNAL_CATCH_TYPE_GEN\ 1223 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1224 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1225 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1226 template<typename...Types> \ 1227 struct TestNameClass{\ 1230 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1231 using expander = int[];\ 1232 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... }; \ 1235 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1236 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1241 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1242 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1244 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1245 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1246 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__ ) 1248 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1249 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__ ) ) 1252 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1253 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1254 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__ ) 1256 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1257 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__ ) ) 1260 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ 1261 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1262 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1263 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1264 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1265 template<typename TestType> \ 1266 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1270 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\ 1271 INTERNAL_CATCH_TYPE_GEN \ 1272 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1273 template<typename...Types>\ 1274 struct TestNameClass{\ 1277 using expander = int[];\ 1278 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1279 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1280 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1281 (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++, 0)... }; \ 1284 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1285 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;\ 1292 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1293 template<typename TestType> \ 1294 void TestName<TestType>::test() 1296 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1297 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1298 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__ ) 1300 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1301 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__ ) ) 1304 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1305 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1306 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__ ) 1308 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1309 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__ ) ) 1312 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ 1313 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1314 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1315 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1316 template<typename TestType> \ 1317 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1321 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1322 INTERNAL_CATCH_TYPE_GEN\ 1323 template<typename...Types>\ 1324 struct TestNameClass{\ 1327 using expander = int[];\ 1328 (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++, 0)... }; \ 1331 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1332 using TestInit = typename convert<TestNameClass, TmplList>::type;\ 1338 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1339 template<typename TestType> \ 1340 void TestName<TestType>::test() 1342 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ 1343 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 ) 1365 ExpressionFailed = FailureBit | 1,
1366 ExplicitFailure = FailureBit | 2,
1368 Exception = 0x100 | FailureBit,
1370 ThrewException = Exception | 1,
1371 DidntThrowException = Exception | 2,
1373 FatalErrorCondition = 0x200 | FailureBit
1384 ContinueOnFailure = 0x02,
1421 #include <type_traits> 1431 std::ostream&
cout();
1432 std::ostream&
cerr();
1433 std::ostream&
clog();
1439 virtual std::ostream&
stream()
const = 0;
1451 auto str() const ->
std::
string;
1453 template<typename
T>
1458 auto get() -> std::ostream& {
return *m_oss; }
1485 template<
typename E>
1487 static_assert(
sizeof(
int) >=
sizeof(E),
"Cannot serialize enum to int");
1488 std::vector<int> intValues;
1489 intValues.reserve( values.size() );
1490 for(
auto enumValue : values )
1491 intValues.push_back( static_cast<int>( enumValue ) );
1492 return registerEnum( enumName, allEnums, intValues );
1500 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1501 #include <string_view> 1507 #import <Foundation/Foundation.h> 1509 #ifdef __has_feature 1510 #define CATCH_ARC_ENABLED __has_feature(objc_arc) 1512 #define CATCH_ARC_ENABLED 0 1515 void arcSafeRelease( NSObject*
obj );
1516 id performOptionalSelector(
id obj,
SEL sel );
1518 #if !CATCH_ARC_ENABLED 1519 inline void arcSafeRelease( NSObject* obj ) {
1522 inline id performOptionalSelector(
id obj,
SEL sel ) {
1523 if( [obj respondsToSelector: sel] )
1524 return [obj performSelector: sel];
1527 #define CATCH_UNSAFE_UNRETAINED 1528 #define CATCH_ARC_STRONG 1530 inline void arcSafeRelease( NSObject* ){}
1531 inline id performOptionalSelector(
id obj,
SEL sel ) {
1533 #pragma clang diagnostic push 1534 #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 1536 if( [obj respondsToSelector: sel] )
1537 return [obj performSelector: sel];
1539 #pragma clang diagnostic pop 1543 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained 1544 #define CATCH_ARC_STRONG __strong 1551 #pragma warning(push) 1552 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless 1562 template<
typename T>
1567 template<
typename T>
1569 template<
typename Stream,
typename U>
1570 static auto test(
int)
1571 -> decltype(std::declval<Stream&>() << std::declval<U>(),
std::true_type());
1573 template<
typename,
typename>
1574 static auto test(...)->std::false_type;
1580 template<
typename E>
1583 template<
typename T>
1584 typename std::enable_if<
1589 template<
typename T>
1590 typename std::enable_if<
1596 template<
typename T>
1597 typename std::enable_if<
1603 #if defined(_MANAGED) 1604 template<
typename T>
1609 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1610 cli::pin_ptr<System::Byte>
p = &bytes[0];
1611 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1618 template <
typename T,
typename =
void>
1620 template <
typename Fake = T>
1627 rss.operator<<(
value);
1631 template <
typename Fake = T>
1635 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) 1638 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1647 template <
typename T>
1652 template<
typename E>
1657 #if defined(_MANAGED) 1658 template <
typename T>
1673 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1689 #ifdef CATCH_CONFIG_WCHAR 1695 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1733 #if defined(CATCH_CONFIG_CPP17_BYTE) 1738 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 1799 template <
typename T>
1801 template <
typename U>
1811 template <
typename R,
typename C>
1822 #if defined(_MANAGED) 1823 template <
typename T>
1826 return ::Catch::Detail::clrReferenceToString(ref);
1832 template<
typename InputIterator>
1836 if (first != last) {
1838 for (++first; first != last; ++
first)
1876 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) 1877 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1878 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1879 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1880 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 1881 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1885 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) 1888 template<
typename T1,
typename T2>
1901 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1903 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) 1906 template<
typename T>
1910 if (optional.has_value()) {
1919 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1922 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) 1931 struct TupleElementPrinter {
1932 static void print(
const Tuple& tuple, std::ostream& os) {
1933 os << (N ?
", " :
" ")
1943 struct TupleElementPrinter<Tuple, N, false> {
1944 static void print(
const Tuple&, std::ostream&) {}
1949 template<
typename ...Types>
1954 Detail::TupleElementPrinter<std::tuple<Types...>>
::print(tuple, rss.
get());
1960 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1962 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) 1972 template<
typename... Elements>
1975 if (variant.valueless_by_exception()) {
1976 return "{valueless variant}";
1979 [](
const auto&
value) {
1988 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 2000 template <
typename T>
2007 #if defined(_MANAGED) // Managed types are never ranges 2008 template <
typename T>
2010 static const bool value =
false;
2014 template<
typename Range>
2020 template<
typename Allocator>
2036 template<
typename R>
2037 struct StringMaker<
R, typename
std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>
::type> {
2043 template <
typename T,
int SZ>
2053 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 2060 template <
class Ratio>
2061 struct ratio_string {
2065 template <
class Ratio>
2069 << Ratio::den <<
']';
2073 struct ratio_string<std::atto> {
2077 struct ratio_string<std::femto> {
2081 struct ratio_string<std::pico> {
2085 struct ratio_string<std::nano> {
2089 struct ratio_string<std::micro> {
2093 struct ratio_string<std::milli> {
2099 template<
typename Value,
typename Ratio>
2100 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2103 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2107 template<
typename Value>
2108 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2111 rss << duration.count() <<
" s";
2115 template<
typename Value>
2116 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2119 rss << duration.count() <<
" m";
2123 template<
typename Value>
2124 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2127 rss << duration.count() <<
" h";
2135 template<
typename Clock,
typename Duration>
2136 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2137 static std::string convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2142 template<
typename Duration>
2143 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2144 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2145 auto converted = std::chrono::system_clock::to_time_t(time_point);
2148 std::tm timeInfo = {};
2149 gmtime_s(&timeInfo, &converted);
2151 std::tm* timeInfo = std::gmtime(&converted);
2154 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2156 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2159 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2161 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2167 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 2169 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ 2171 template<> struct StringMaker<enumName> { \ 2172 static std::string convert( enumName value ) { \ 2173 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ 2174 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \ 2179 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) 2182 #pragma warning(pop) 2189 #pragma warning(push) 2190 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch 2191 #pragma warning(disable:4018) // more "signed/unsigned mismatch" 2192 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) 2193 #pragma warning(disable:4180) // qualifier applied to function type has no meaning 2194 #pragma warning(disable:4800) // Forcing result to true or false 2202 virtual void streamReconstructedExpression( std::ostream &os )
const = 0;
2205 : m_isBinaryExpression( isBinaryExpression ),
2220 template<
typename LhsT,
typename RhsT>
2239 template<
typename T>
2242 "chained comparisons are not supported inside assertions, " 2243 "wrap the expression inside parentheses, or decompose it");
2246 template<
typename T>
2249 "chained comparisons are not supported inside assertions, " 2250 "wrap the expression inside parentheses, or decompose it");
2253 template<
typename T>
2256 "chained comparisons are not supported inside assertions, " 2257 "wrap the expression inside parentheses, or decompose it");
2260 template<
typename T>
2263 "chained comparisons are not supported inside assertions, " 2264 "wrap the expression inside parentheses, or decompose it");
2267 template<
typename T>
2270 "chained comparisons are not supported inside assertions, " 2271 "wrap the expression inside parentheses, or decompose it");
2274 template<
typename T>
2277 "chained comparisons are not supported inside assertions, " 2278 "wrap the expression inside parentheses, or decompose it");
2281 template<
typename T>
2284 "chained comparisons are not supported inside assertions, " 2285 "wrap the expression inside parentheses, or decompose it");
2288 template<
typename T>
2291 "chained comparisons are not supported inside assertions, " 2292 "wrap the expression inside parentheses, or decompose it");
2296 template<
typename LhsT>
2312 template<
typename LhsT,
typename RhsT>
2314 template<
typename T>
2316 template<
typename T>
2318 template<
typename T>
2320 template<
typename T>
2323 template<
typename LhsT,
typename RhsT>
2325 template<
typename T>
2327 template<
typename T>
2329 template<
typename T>
2331 template<
typename T>
2334 template<
typename LhsT>
2340 template<
typename RhsT>
2342 return {
compareEqual( m_lhs, rhs ), m_lhs,
"==", rhs };
2345 return { m_lhs == rhs, m_lhs,
"==", rhs };
2348 template<
typename RhsT>
2353 return { m_lhs != rhs, m_lhs,
"!=", rhs };
2356 template<
typename RhsT>
2358 return {
static_cast<bool>(m_lhs > rhs), m_lhs,
">", rhs };
2360 template<
typename RhsT>
2362 return {
static_cast<bool>(m_lhs < rhs), m_lhs,
"<", rhs };
2364 template<
typename RhsT>
2366 return {
static_cast<bool>(m_lhs >= rhs), m_lhs,
">=", rhs };
2368 template<
typename RhsT>
2370 return {
static_cast<bool>(m_lhs <= rhs), m_lhs,
"<=", rhs };
2372 template <
typename RhsT>
2374 return {
static_cast<bool>(m_lhs | rhs), m_lhs,
"|", rhs };
2376 template <
typename RhsT>
2378 return {
static_cast<bool>(m_lhs & rhs), m_lhs,
"&", rhs };
2380 template <
typename RhsT>
2382 return {
static_cast<bool>(m_lhs ^ rhs), m_lhs,
"^", rhs };
2385 template<
typename RhsT>
2388 "operator&& is not supported inside assertions, " 2389 "wrap the expression inside parentheses, or decompose it");
2392 template<
typename RhsT>
2395 "operator|| is not supported inside assertions, " 2396 "wrap the expression inside parentheses, or decompose it");
2406 template<
typename T>
2412 template<
typename T>
2425 #pragma warning(pop) 2436 class AssertionResult;
2449 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2450 struct BenchmarkInfo;
2451 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2452 struct BenchmarkStats;
2453 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2459 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
2460 Counts& assertions ) = 0;
2462 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo ) = 0;
2466 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2468 virtual void benchmarkStarting( BenchmarkInfo
const&
info ) = 0;
2469 virtual void benchmarkEnded( BenchmarkStats<>
const& stats ) = 0;
2471 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2474 virtual void popScopedMessage(
MessageInfo const& message ) = 0;
2476 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder ) = 0;
2478 virtual void handleFatalErrorCondition(
StringRef message ) = 0;
2480 virtual void handleExpr
2484 virtual void handleMessage
2489 virtual void handleUnexpectedExceptionNotThrown
2492 virtual void handleUnexpectedInflightException
2496 virtual void handleIncomplete
2498 virtual void handleNonExpr
2503 virtual bool lastAssertionPassed() = 0;
2504 virtual void assertionPassed() = 0;
2507 virtual std::string getCurrentTestName()
const = 0;
2508 virtual const AssertionResult* getLastResult()
const = 0;
2509 virtual void exceptionEarlyReported() = 0;
2519 struct AssertionResultData;
2525 friend struct AssertionStats;
2526 friend class RunContext;
2535 explicit operator bool()
const;
2541 bool shouldDebugBreak =
false;
2542 bool shouldThrow =
false;
2548 bool m_completed =
false;
2558 if ( !m_completed ) {
2563 template<
typename T>
2571 void handleExceptionThrownAsExpected();
2572 void handleUnexpectedExceptionNotThrown();
2573 void handleExceptionNotThrownAsExpected();
2574 void handleThrowingCallSkipped();
2575 void handleUnexpectedInflightException();
2578 void setCompleted();
2581 auto allowThrows()
const -> bool;
2615 template<
typename T>
2629 template<
typename T>
2652 size_t m_captured = 0;
2659 template<
typename T>
2664 template<
typename T,
typename... Ts>
2667 captureValues( index+1, values... );
2674 #if !defined(CATCH_CONFIG_DISABLE) 2676 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) 2677 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ 2679 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" 2682 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 2687 #define INTERNAL_CATCH_TRY 2688 #define INTERNAL_CATCH_CATCH( capturer ) 2690 #else // CATCH_CONFIG_FAST_COMPILE 2692 #define INTERNAL_CATCH_TRY try 2693 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } 2697 #define INTERNAL_CATCH_REACT( handler ) handler.complete(); 2700 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ 2702 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ 2703 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2704 INTERNAL_CATCH_TRY { \ 2705 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2706 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 2707 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ 2708 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 2709 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 2710 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2711 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) 2714 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ 2715 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2716 if( Catch::getResultCapture().lastAssertionPassed() ) 2719 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ 2720 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2721 if( !Catch::getResultCapture().lastAssertionPassed() ) 2724 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ 2726 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2728 static_cast<void>(__VA_ARGS__); \ 2729 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ 2732 catchAssertionHandler.handleUnexpectedInflightException(); \ 2734 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2738 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ 2740 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ 2741 if( catchAssertionHandler.allowThrows() ) \ 2743 static_cast<void>(__VA_ARGS__); \ 2744 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2747 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2750 catchAssertionHandler.handleThrowingCallSkipped(); \ 2751 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2755 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ 2757 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ 2758 if( catchAssertionHandler.allowThrows() ) \ 2760 static_cast<void>(expr); \ 2761 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2763 catch( exceptionType const& ) { \ 2764 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2767 catchAssertionHandler.handleUnexpectedInflightException(); \ 2770 catchAssertionHandler.handleThrowingCallSkipped(); \ 2771 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2775 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ 2777 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ 2778 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ 2779 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2783 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ 2784 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ 2785 varName.captureValues( 0, __VA_ARGS__ ) 2788 #define INTERNAL_CATCH_INFO( macroName, log ) \ 2789 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); 2792 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ 2793 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) 2797 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ 2799 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 2800 if( catchAssertionHandler.allowThrows() ) \ 2802 static_cast<void>(__VA_ARGS__); \ 2803 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2806 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ 2809 catchAssertionHandler.handleThrowingCallSkipped(); \ 2810 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2813 #endif // CATCH_CONFIG_DISABLE 2830 std::size_t total()
const;
2831 bool allPassed()
const;
2834 std::size_t passed = 0;
2836 std::size_t failedButOk = 0;
2895 auto getElapsedNanoseconds() const ->
uint64_t;
2896 auto getElapsedMicroseconds() const ->
uint64_t;
2897 auto getElapsedMilliseconds() const ->
unsigned int;
2898 auto getElapsedSeconds() const ->
double;
2914 explicit operator bool()
const;
2927 #define INTERNAL_CATCH_SECTION( ... ) \ 2928 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2929 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2930 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ 2931 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2933 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ 2934 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2935 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2936 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ 2937 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2950 struct ITestCaseRegistry;
2951 struct IExceptionTranslatorRegistry;
2952 struct IExceptionTranslator;
2953 struct IReporterRegistry;
2954 struct IReporterFactory;
2955 struct ITagAliasRegistry;
2956 struct IMutableEnumValuesRegistry;
2958 class StartupExceptionRegistry;
2965 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2967 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2970 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
2977 virtual void registerTest(
TestCase const& testInfo ) = 0;
2980 virtual void registerStartupException() noexcept = 0;
2992 #if defined(CATCH_CONFIG_DISABLE) 2993 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ 2994 static std::string translatorName( signature ) 2997 #include <exception> 3009 virtual std::string translate( ExceptionTranslators::const_iterator
it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3019 template<
typename T>
3024 : m_translateFunction( translateFunction )
3027 std::string translate( ExceptionTranslators::const_iterator
it, ExceptionTranslators::const_iterator itEnd )
const override {
3028 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3033 std::rethrow_exception(std::current_exception());
3035 return (*it)->translate( it+1, itEnd );
3038 return m_translateFunction( ex );
3048 template<
typename T>
3057 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ 3058 static std::string translatorName( signature ); \ 3059 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 3060 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 3061 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ 3062 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 3063 static std::string translatorName( signature ) 3065 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 3070 #include <type_traits> 3077 bool equalityComparisonImpl(
double other)
const;
3080 void setMargin(
double margin);
3083 void setEpsilon(
double epsilon);
3107 auto lhs_v =
static_cast<double>(
lhs);
3128 return static_cast<double>(
lhs) < rhs.
m_value || lhs == rhs;
3133 return lhs.
m_value <
static_cast<double>(rhs) || lhs == rhs;
3138 return static_cast<double>(
lhs) > rhs.
m_value || lhs == rhs;
3143 return lhs.
m_value >
static_cast<double>(rhs) || lhs == rhs;
3148 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3149 setEpsilon(epsilonAsDouble);
3155 double marginAsDouble =
static_cast<double>(newMargin);
3156 setMargin(marginAsDouble);
3162 m_scale =
static_cast<double>(newScale);
3176 namespace literals {
3224 #ifndef CATCH_CONFIG_DISABLE_MATCHERS 3233 namespace Matchers {
3254 # pragma clang diagnostic push 3255 # pragma clang diagnostic ignored "-Wnon-virtual-dtor" 3258 template<
typename ObjectT>
3260 virtual bool match( ObjectT
const&
arg )
const = 0;
3263 #if defined(__OBJC__) 3268 virtual bool match( NSString*
arg )
const = 0;
3273 # pragma clang diagnostic pop 3276 template<
typename T>
3284 template<
typename ArgT>
3287 for(
auto matcher : m_matchers ) {
3288 if (!matcher->match(arg))
3295 description.reserve( 4 + m_matchers.size()*32 );
3296 description +=
"( ";
3298 for(
auto matcher : m_matchers ) {
3302 description +=
" and ";
3303 description += matcher->toString();
3305 description +=
" )";
3311 copy.m_matchers.push_back( &other );
3317 template<
typename ArgT>
3321 for(
auto matcher : m_matchers ) {
3322 if (matcher->match(arg))
3329 description.reserve( 4 + m_matchers.size()*32 );
3330 description +=
"( ";
3332 for(
auto matcher : m_matchers ) {
3336 description +=
" or ";
3337 description += matcher->toString();
3339 description +=
" )";
3345 copy.m_matchers.push_back( &other );
3352 template<
typename ArgT>
3358 return !m_underlyingMatcher.match( arg );
3362 return "not " + m_underlyingMatcher.toString();
3367 template<
typename T>
3371 template<
typename T>
3375 template<
typename T>
3384 using namespace Matchers;
3393 namespace Matchers {
3394 namespace Exception {
3404 bool match(std::exception
const& ex)
const override;
3420 namespace Matchers {
3422 namespace Floating {
3424 enum class FloatingPointKind :
uint8_t;
3428 bool match(
double const& matchee)
const override;
3437 bool match(
double const& matchee)
const override;
3453 bool match(
double const& matchee)
const override;
3480 #include <functional> 3484 namespace Matchers {
3491 template <
typename T>
3498 :m_predicate(
std::
move(elem)),
3503 return m_predicate(item);
3507 return m_description;
3517 template<
typename T>
3531 namespace Matchers {
3533 namespace StdString {
3572 bool match(
std::string const& matchee )
const override;
3597 #include <algorithm> 3600 namespace Matchers {
3603 template<
typename T,
typename Alloc>
3608 bool match(std::vector<T, Alloc>
const &
v)
const override {
3609 for (
auto const&
el : v) {
3610 if (
el == m_comparator) {
3624 template<
typename T,
typename AllocComp,
typename AllocMatch>
3627 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3629 bool match(std::vector<T, AllocMatch>
const &
v)
const override {
3631 if (m_comparator.size() > v.size())
3633 for (
auto const& comparator : m_comparator) {
3634 auto present =
false;
3635 for (
const auto&
el : v) {
3636 if (
el == comparator) {
3654 template<
typename T,
typename AllocComp,
typename AllocMatch>
3657 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3659 bool match(std::vector<T, AllocMatch>
const &
v)
const override {
3664 if (m_comparator.size() != v.size())
3666 for (std::size_t
i = 0;
i < v.size(); ++
i)
3667 if (m_comparator[
i] != v[
i])
3677 template<
typename T,
typename AllocComp,
typename AllocMatch>
3680 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3682 bool match(std::vector<T, AllocMatch>
const &
v)
const override {
3683 if (m_comparator.size() != v.size())
3685 for (std::size_t
i = 0;
i < v.size(); ++
i)
3686 if (m_comparator[
i] !=
approx(v[
i]))
3713 template<
typename T,
typename AllocComp,
typename AllocMatch>
3716 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3719 if (m_target.size() != vec.size()) {
3722 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3737 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3742 template<
typename T,
typename Alloc = std::allocator<T>>
3747 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3752 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3757 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3768 template<
typename ArgT,
typename MatcherT>
3777 m_matcher( matcher ),
3778 m_matcherString( matcherString )
3782 auto matcherAsString = m_matcher.toString();
3785 os << m_matcherString;
3787 os << matcherAsString;
3795 template<
typename ArgT,
typename MatcherT>
3803 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ 3805 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3806 INTERNAL_CATCH_TRY { \ 3807 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ 3808 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 3809 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3813 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ 3815 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3816 if( catchAssertionHandler.allowThrows() ) \ 3818 static_cast<void>(__VA_ARGS__ ); \ 3819 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 3821 catch( exceptionType const& ex ) { \ 3822 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ 3825 catchAssertionHandler.handleUnexpectedInflightException(); \ 3828 catchAssertionHandler.handleThrowingCallSkipped(); \ 3829 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3852 virtual bool next() = 0;
3860 virtual auto hasGenerator()
const ->
bool = 0;
3870 #include <exception> 3873 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3874 template <
typename Ex>
3879 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 3893 #define CATCH_MAKE_MSG(...) \ 3894 (Catch::ReusableStringStream() << __VA_ARGS__).str() 3896 #define CATCH_INTERNAL_ERROR(...) \ 3897 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) 3899 #define CATCH_ERROR(...) \ 3900 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3902 #define CATCH_RUNTIME_ERROR(...) \ 3903 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3905 #define CATCH_ENFORCE( condition, ... ) \ 3906 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) 3914 #include <exception> 3919 const char*
const m_msg =
"";
3926 const char* what()
const noexcept
override final;
3929 namespace Generators {
3933 template<
typename T,
typename... Args>
3935 return std::unique_ptr<T>(
new T(std::forward<Args>(
args)...));
3939 template<
typename T>
3947 virtual T const&
get()
const = 0;
3951 template<
typename T>
3957 T const&
get()
const override {
3965 template<
typename T>
3968 "FixedValuesGenerator does not support bools because of std::vector<bool>" 3969 "specialization, use SingleValue Generator instead.");
3975 T const&
get()
const override {
3976 return m_values[m_idx];
3980 return m_idx < m_values.size();
3984 template <
typename T>
3989 m_generator(
std::
move(generator))
3991 T const&
get()
const {
3992 return m_generator->get();
3995 return m_generator->next();
3999 template <
typename T>
4003 template <
typename T>
4008 template<
typename T>
4011 size_t m_current = 0;
4014 m_generators.emplace_back(
std::move(generator));
4017 m_generators.emplace_back(
value(std::forward<T>(
val)));
4019 template<
typename U>
4021 populate(
T(std::forward<U>(
val)));
4023 template<
typename U,
typename... Gs>
4024 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4025 populate(std::forward<U>(valueOrGenerator));
4026 populate(std::forward<Gs>(moreGenerators)...);
4030 template <
typename... Gs>
4032 m_generators.reserve(
sizeof...(Gs));
4033 populate(std::forward<Gs>(moreGenerators)...);
4036 T const&
get()
const override {
4037 return m_generators[m_current].get();
4041 if (m_current >= m_generators.size()) {
4044 const bool current_status = m_generators[m_current].next();
4045 if (!current_status) {
4048 return m_current < m_generators.size();
4052 template<
typename... Ts>
4054 return values<std::tuple<Ts...>>( tuples );
4058 template <
typename T>
4061 template<
typename T,
typename... Gs>
4065 template<
typename T>
4069 template<
typename T,
typename... Gs>
4073 template<
typename T,
typename U,
typename... Gs>
4080 template<
typename L>
4085 using UnderlyingType =
typename decltype(generatorExpression())::
type;
4093 return generator.
get();
4099 #define GENERATE( ... ) \ 4100 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4101 #define GENERATE_COPY( ... ) \ 4102 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4103 #define GENERATE_REF( ... ) \ 4104 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4110 namespace Generators {
4112 template <
typename T>
4115 size_t m_returned = 0;
4119 m_generator(
std::
move(generator)),
4122 assert(target != 0 &&
"Empty generators are not allowed");
4124 T
const&
get()
const override {
4125 return m_generator.
get();
4129 if (m_returned >= m_target) {
4137 m_returned = m_target;
4143 template <
typename T>
4148 template <
typename T,
typename Predicate>
4153 template <
typename P = Predicate>
4155 m_generator(
std::
move(generator)),
4158 if (!m_predicate(m_generator.
get())) {
4161 auto has_initial_value =
next();
4162 if (!has_initial_value) {
4168 T
const&
get()
const override {
4169 return m_generator.
get();
4177 while (!m_predicate(m_generator.
get()) && (success = m_generator.
next()) ==
true);
4182 template <
typename T,
typename Predicate>
4184 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred),
std::move(generator))));
4187 template <
typename T>
4190 "RepeatGenerator currently does not support bools" 4191 "because of std::vector<bool> specialization");
4195 size_t m_current_repeat = 0;
4196 size_t m_repeat_index = 0;
4199 m_generator(
std::
move(generator)),
4200 m_target_repeats(repeats)
4202 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4205 T
const&
get()
const override {
4206 if (m_current_repeat == 0) {
4207 m_returned.push_back(m_generator.
get());
4208 return m_returned.back();
4210 return m_returned[m_repeat_index];
4220 if (m_current_repeat == 0) {
4225 return m_current_repeat < m_target_repeats;
4230 if (m_repeat_index == m_returned.size()) {
4234 return m_current_repeat < m_target_repeats;
4238 template <
typename T>
4243 template <
typename T,
typename U,
typename Func>
4251 template <
typename F2 = Func>
4253 m_generator(
std::
move(generator)),
4255 m_cache(m_function(m_generator.
get()))
4258 T
const&
get()
const override {
4264 m_cache = m_function(m_generator.
get());
4270 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4273 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function),
std::move(generator))
4277 template <
typename T,
typename U,
typename Func>
4280 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function),
std::move(generator))
4284 template <
typename T>
4289 bool m_used_up =
false;
4292 m_chunk_size(size), m_generator(
std::
move(generator))
4294 m_chunk.reserve(m_chunk_size);
4295 if (m_chunk_size != 0) {
4296 m_chunk.push_back(m_generator.
get());
4297 for (
size_t i = 1;
i < m_chunk_size; ++
i) {
4298 if (!m_generator.
next()) {
4301 m_chunk.push_back(m_generator.
get());
4305 std::vector<T>
const&
get()
const override {
4310 for (
size_t idx = 0;
idx < m_chunk_size; ++
idx) {
4311 if (!m_generator.
next()) {
4314 m_chunk.push_back(m_generator.
get());
4320 template <
typename T>
4323 pf::make_unique<ChunkGenerator<T>>(
size,
std::move(generator))
4351 virtual IRunner* getRunner() = 0;
4352 virtual IConfigPtr const& getConfig()
const = 0;
4358 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4359 virtual void setRunner(
IRunner* runner ) = 0;
4366 static void createContext();
4396 template<
typename T>
4401 : nullableValue( new( storage ) T( _value ) )
4404 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4412 if( &_other !=
this ) {
4415 nullableValue =
new( storage )
T( *_other );
4421 nullableValue =
new( storage )
T( _value );
4427 nullableValue->~T();
4428 nullableValue =
nullptr;
4437 return nullableValue ? *nullableValue : defaultValue;
4440 bool some()
const {
return nullableValue !=
nullptr; }
4441 bool none()
const {
return nullableValue ==
nullptr; }
4443 bool operator !()
const {
return nullableValue ==
nullptr; }
4444 explicit operator bool()
const {
4450 alignas(
alignof(
T))
char storage[
sizeof(
T)];
4472 NoAssertions = 0x01,
4495 BeforeStartAndExit = BeforeStart | BeforeExit
4504 virtual bool allowThrows()
const = 0;
4505 virtual std::ostream&
stream()
const = 0;
4507 virtual bool includeSuccessfulResults()
const = 0;
4508 virtual bool shouldDebugBreak()
const = 0;
4509 virtual bool warnAboutMissingAssertions()
const = 0;
4510 virtual bool warnAboutNoTests()
const = 0;
4511 virtual int abortAfter()
const = 0;
4512 virtual bool showInvisibles()
const = 0;
4514 virtual TestSpec
const& testSpec()
const = 0;
4515 virtual bool hasTestFilters()
const = 0;
4516 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4518 virtual unsigned int rngSeed()
const = 0;
4520 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4521 virtual Verbosity verbosity()
const = 0;
4523 virtual bool benchmarkNoAnalysis()
const = 0;
4524 virtual int benchmarkSamples()
const = 0;
4525 virtual double benchmarkConfidenceInterval()
const = 0;
4526 virtual unsigned int benchmarkResamples()
const = 0;
4527 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4530 using IConfigPtr = std::shared_ptr<IConfig const>;
4562 void discard(uint64_t skip);
4587 namespace Generators {
4589 template <
typename Float>
4592 std::uniform_real_distribution<Float>
m_dist;
4599 static_cast<void>(
next());
4602 Float
const&
get()
const override {
4603 return m_current_number;
4606 m_current_number = m_dist(m_rng);
4611 template <
typename Integer>
4614 std::uniform_int_distribution<Integer>
m_dist;
4621 static_cast<void>(
next());
4624 Integer
const&
get()
const override {
4625 return m_current_number;
4628 m_current_number = m_dist(m_rng);
4635 template <
typename T>
4640 pf::make_unique<RandomIntegerGenerator<T>>(
a,
b)
4644 template <
typename T>
4649 pf::make_unique<RandomFloatingGenerator<T>>(
a,
b)
4653 template <
typename T>
4665 m_positive(m_step > T(0))
4667 assert(m_current != m_end &&
"Range start and end cannot be equal");
4668 assert(m_step !=
T(0) &&
"Step size cannot be zero");
4669 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4676 T
const&
get()
const override {
4681 m_current += m_step;
4682 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4686 template <
typename T>
4692 template <
typename T>
4698 template <
typename T>
4701 "IteratorGenerator currently does not support bools" 4702 "because of std::vector<bool> specialization");
4705 size_t m_current = 0;
4707 template <
typename InputIterator,
typename InputSentinel>
4709 if (m_elems.empty()) {
4714 T
const&
get()
const override {
4715 return m_elems[m_current];
4720 return m_current != m_elems.size();
4724 template <
typename InputIterator,
4725 typename InputSentinel,
4726 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4731 template <
typename Container,
4732 typename ResultType =
typename Container::value_type>
4751 #pragma clang diagnostic push 4752 #pragma clang diagnostic ignored "-Wpadded" 4763 ShouldFail = 1 << 2,
4766 NonPortable = 1 << 5,
4773 std::vector<std::string>
const&
_tags,
4776 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string>
tags );
4778 bool isHidden()
const;
4779 bool throws()
const;
4780 bool okToFail()
const;
4781 bool expectedToFail()
const;
4801 void invoke()
const;
4809 std::shared_ptr<ITestInvoker>
test;
4819 #pragma clang diagnostic pop 4829 virtual bool aborting()
const = 0;
4838 #import <objc/runtime.h> 4863 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4865 virtual void invoke()
const {
4866 id obj = [[m_cls alloc] init];
4868 performOptionalSelector( obj,
@selector(setUp) );
4869 performOptionalSelector( obj, m_sel );
4870 performOptionalSelector( obj,
@selector(tearDown) );
4872 arcSafeRelease( obj );
4875 virtual ~OcMethod() {}
4886 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4887 SEL sel = NSSelectorFromString( selStr );
4888 arcSafeRelease( selStr );
4889 id value = performOptionalSelector( cls, sel );
4891 return [(NSString*)value UTF8String];
4896 inline std::size_t registerTestMethods() {
4897 std::size_t noTestMethods = 0;
4898 int noClasses = objc_getClassList(
nullptr, 0 );
4900 Class*
classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4901 objc_getClassList( classes, noClasses );
4903 for(
int c = 0;
c < noClasses;
c++ ) {
4904 Class cls = classes[c];
4907 Method* methods = class_copyMethodList( cls, &count );
4908 for( u_int
m = 0;
m <
count ;
m++ ) {
4909 SEL selector = method_getName(methods[
m]);
4911 if(
startsWith( methodName,
"Catch_TestCase_" ) ) {
4912 std::string testCaseName = methodName.substr( 15 );
4913 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4914 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4915 const char* className = class_getName( cls );
4924 return noTestMethods;
4927 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 4929 namespace Matchers {
4931 namespace NSStringMatchers {
4933 struct StringHolder : MatcherBase<NSString*>{
4934 StringHolder( NSString* substr ) : m_substr( [substr
copy] ){}
4935 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4937 arcSafeRelease( m_substr );
4940 bool match( NSString*
str )
const override {
4944 NSString* CATCH_ARC_STRONG m_substr;
4947 struct Equals : StringHolder {
4948 Equals( NSString* substr ) : StringHolder( substr ){}
4950 bool match( NSString*
str )
const override {
4951 return (str != nil || m_substr == nil ) &&
4952 [str isEqualToString:m_substr];
4961 Contains( NSString* substr ) : StringHolder( substr ){}
4963 bool match( NSString*
str )
const override {
4964 return (str != nil || m_substr == nil ) &&
4965 [str rangeOfString:m_substr].location != NSNotFound;
4974 StartsWith( NSString* substr ) : StringHolder( substr ){}
4976 bool match( NSString*
str )
const override {
4977 return (str != nil || m_substr == nil ) &&
4978 [str rangeOfString:m_substr].location == 0;
4986 EndsWith( NSString* substr ) : StringHolder( substr ){}
4988 bool match( NSString*
str )
const override {
4989 return (str != nil || m_substr == nil ) &&
4990 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5015 using namespace Matchers;
5017 #endif // CATCH_CONFIG_DISABLE_MATCHERS 5022 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix 5023 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ 5024 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ 5028 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ 5032 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) 5034 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) 5040 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5052 #pragma clang diagnostic push 5053 #pragma clang diagnostic ignored "-Wpadded" 5059 #pragma clang diagnostic push 5060 #pragma clang diagnostic ignored "-Wpadded" 5067 class WildcardPattern {
5068 enum WildcardPosition {
5070 WildcardAtStart = 1,
5072 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5078 virtual ~WildcardPattern() =
default;
5084 WildcardPosition m_wildcard = NoWildcard;
5108 using PatternPtr = std::shared_ptr<Pattern>;
5110 class NamePattern :
public Pattern {
5115 WildcardPattern m_wildcardPattern;
5118 class TagPattern :
public Pattern {
5126 class ExcludedPattern :
public Pattern {
5128 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5131 PatternPtr m_underlyingPattern;
5135 std::vector<PatternPtr> m_patterns;
5142 struct FilterMatch {
5144 std::vector<TestCase const*>
tests;
5146 using Matches = std::vector<FilterMatch>;
5147 using vectorStrings = std::vector<std::string>;
5149 bool hasFilters()
const;
5151 Matches matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const&
config )
const;
5152 const vectorStrings & getInvalidArgs()
const;
5155 std::vector<Filter> m_filters;
5156 std::vector<std::string> m_invalidArgs;
5157 friend class TestSpecParser;
5162 #pragma clang diagnostic pop 5174 struct ITagAliasRegistry {
5175 virtual ~ITagAliasRegistry();
5180 static ITagAliasRegistry
const&
get();
5188 class TestSpecParser {
5189 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5191 Mode lastMode = None;
5192 bool m_exclusion =
false;
5193 std::size_t m_pos = 0;
5194 std::size_t m_realPatternPos = 0;
5198 std::vector<std::size_t> m_escapeChars;
5199 TestSpec::Filter m_currentFilter;
5200 TestSpec m_testSpec;
5201 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5204 TestSpecParser( ITagAliasRegistry
const& tagAliases );
5207 TestSpec testSpec();
5210 bool visitChar(
char c );
5212 bool processNoneChar(
char c );
5213 void processNameChar(
char c );
5214 bool processOtherChar(
char c );
5217 bool isControlChar(
char c )
const;
5218 void saveLastMode();
5219 void revertBackToLastMode();
5226 void addNamePattern();
5228 void addTagPattern();
5230 inline void addCharToPattern(
char c) {
5242 #pragma clang diagnostic pop 5252 #ifndef CATCH_CONFIG_CONSOLE_WIDTH 5253 #define CATCH_CONFIG_CONSOLE_WIDTH 80 5261 bool listTests =
false;
5262 bool listTags =
false;
5263 bool listReporters =
false;
5264 bool listTestNamesOnly =
false;
5266 bool showSuccessfulTests =
false;
5267 bool shouldDebugBreak =
false;
5268 bool noThrow =
false;
5269 bool showHelp =
false;
5270 bool showInvisibles =
false;
5271 bool filenamesAsTags =
false;
5272 bool libIdentify =
false;
5274 int abortAfter = -1;
5277 bool benchmarkNoAnalysis =
false;
5278 unsigned int benchmarkSamples = 100;
5279 double benchmarkConfidenceInterval = 0.95;
5280 unsigned int benchmarkResamples = 100000;
5281 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5293 #ifndef CATCH_CONFIG_DEFAULT_REPORTER 5294 #define CATCH_CONFIG_DEFAULT_REPORTER "console" 5296 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5297 #undef CATCH_CONFIG_DEFAULT_REPORTER 5299 std::vector<std::string> testsOrTags;
5300 std::vector<std::string> sectionsToRun;
5303 class Config :
public IConfig {
5307 Config( ConfigData
const&
data );
5308 virtual ~Config() =
default;
5312 bool listTests()
const;
5313 bool listTestNamesOnly()
const;
5314 bool listTags()
const;
5315 bool listReporters()
const;
5320 std::vector<std::string>
const& getTestsOrTags()
const override;
5321 std::vector<std::string>
const& getSectionsToRun()
const override;
5323 TestSpec
const& testSpec()
const override;
5324 bool hasTestFilters()
const override;
5326 bool showHelp()
const;
5329 bool allowThrows()
const override;
5330 std::ostream&
stream()
const override;
5332 bool includeSuccessfulResults()
const override;
5333 bool warnAboutMissingAssertions()
const override;
5334 bool warnAboutNoTests()
const override;
5337 unsigned int rngSeed()
const override;
5339 bool shouldDebugBreak()
const override;
5340 int abortAfter()
const override;
5341 bool showInvisibles()
const override;
5343 bool benchmarkNoAnalysis()
const override;
5344 int benchmarkSamples()
const override;
5345 double benchmarkConfidenceInterval()
const override;
5346 unsigned int benchmarkResamples()
const override;
5347 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5354 std::unique_ptr<IStream const> m_stream;
5355 TestSpec m_testSpec;
5356 bool m_hasTestFilters =
false;
5368 struct AssertionResultData
5370 AssertionResultData() =
delete;
5382 class AssertionResult {
5384 AssertionResult() =
delete;
5388 bool succeeded()
const;
5390 bool hasExpression()
const;
5391 bool hasMessage()
const;
5394 bool hasExpandedExpression()
const;
5402 AssertionResultData m_resultData;
5408 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5415 namespace Benchmark {
5416 template <
typename Duration>
5421 double confidence_interval;
5423 template <
typename Duration2>
5424 operator Estimate<Duration2>()
const {
5425 return {
point, lower_bound, upper_bound, confidence_interval };
5437 namespace Benchmark {
5438 struct OutlierClassification {
5439 int samples_seen = 0;
5443 int high_severe = 0;
5446 return low_severe + low_mild + high_mild + high_severe;
5453 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5460 #include <algorithm> 5464 struct ReporterConfig {
5465 explicit ReporterConfig(
IConfigPtr const& _fullConfig );
5467 ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream );
5469 std::ostream&
stream()
const;
5473 std::ostream* m_stream;
5477 struct ReporterPreferences {
5478 bool shouldRedirectStdOut =
false;
5479 bool shouldReportAllAssertions =
false;
5482 template<
typename T>
5484 LazyStat& operator=( T
const& _value ) {
5496 struct TestRunInfo {
5502 std::size_t _groupIndex,
5503 std::size_t _groupsCount );
5506 std::size_t groupIndex;
5507 std::size_t groupsCounts;
5510 struct AssertionStats {
5511 AssertionStats( AssertionResult
const& _assertionResult,
5512 std::vector<MessageInfo>
const& _infoMessages,
5515 AssertionStats( AssertionStats
const& ) =
default;
5516 AssertionStats( AssertionStats && ) =
default;
5517 AssertionStats& operator = ( AssertionStats
const& ) =
delete;
5518 AssertionStats& operator = ( AssertionStats && ) =
delete;
5519 virtual ~AssertionStats();
5521 AssertionResult assertionResult;
5522 std::vector<MessageInfo> infoMessages;
5526 struct SectionStats {
5528 Counts const& _assertions,
5529 double _durationInSeconds,
5530 bool _missingAssertions );
5531 SectionStats( SectionStats
const& ) =
default;
5532 SectionStats( SectionStats && ) =
default;
5533 SectionStats& operator = ( SectionStats
const& ) =
default;
5534 SectionStats& operator = ( SectionStats && ) =
default;
5535 virtual ~SectionStats();
5539 double durationInSeconds;
5540 bool missingAssertions;
5543 struct TestCaseStats {
5550 TestCaseStats( TestCaseStats
const& ) =
default;
5551 TestCaseStats( TestCaseStats && ) =
default;
5552 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5553 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5554 virtual ~TestCaseStats();
5563 struct TestGroupStats {
5564 TestGroupStats( GroupInfo
const& _groupInfo,
5567 TestGroupStats( GroupInfo
const& _groupInfo );
5569 TestGroupStats( TestGroupStats
const& ) =
default;
5570 TestGroupStats( TestGroupStats && ) =
default;
5571 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5572 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5573 virtual ~TestGroupStats();
5575 GroupInfo groupInfo;
5580 struct TestRunStats {
5581 TestRunStats( TestRunInfo
const& _runInfo,
5585 TestRunStats( TestRunStats
const& ) =
default;
5586 TestRunStats( TestRunStats && ) =
default;
5587 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5588 TestRunStats& operator = ( TestRunStats && ) =
default;
5589 virtual ~TestRunStats();
5591 TestRunInfo runInfo;
5596 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5597 struct BenchmarkInfo {
5599 double estimatedDuration;
5602 unsigned int resamples;
5603 double clockResolution;
5607 template <
class Duration>
5608 struct BenchmarkStats {
5611 std::vector<Duration>
samples;
5612 Benchmark::Estimate<Duration> mean;
5613 Benchmark::Estimate<Duration> standardDeviation;
5614 Benchmark::OutlierClassification outliers;
5615 double outlierVariance;
5617 template <
typename Duration2>
5618 operator BenchmarkStats<Duration2>()
const {
5619 std::vector<Duration2> samples2;
5620 samples2.reserve(samples.size());
5621 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
Duration d) {
return Duration2(
d); });
5632 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5634 struct IStreamingReporter {
5635 virtual ~IStreamingReporter() =
default;
5641 virtual ReporterPreferences getPreferences()
const = 0;
5643 virtual void noMatchingTestCases(
std::string const& spec ) = 0;
5645 virtual void reportInvalidArguments(
std::string const&) {}
5647 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5648 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5650 virtual void testCaseStarting(
TestCaseInfo const& testInfo ) = 0;
5651 virtual void sectionStarting(
SectionInfo const& sectionInfo ) = 0;
5653 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5654 virtual void benchmarkPreparing(
std::string const& ) {}
5655 virtual void benchmarkStarting( BenchmarkInfo
const& ) {}
5656 virtual void benchmarkEnded( BenchmarkStats<>
const& ) {}
5657 virtual void benchmarkFailed(
std::string const& ) {}
5658 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5660 virtual void assertionStarting(
AssertionInfo const& assertionInfo ) = 0;
5663 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5665 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5666 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5667 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5668 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5670 virtual void skipTest(
TestCaseInfo const& testInfo ) = 0;
5675 virtual bool isMulti()
const;
5677 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5679 struct IReporterFactory {
5680 virtual ~IReporterFactory();
5681 virtual IStreamingReporterPtr create( ReporterConfig
const&
config )
const = 0;
5686 struct IReporterRegistry {
5687 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5688 using Listeners = std::vector<IReporterFactoryPtr>;
5690 virtual ~IReporterRegistry();
5692 virtual FactoryMap
const& getFactories()
const = 0;
5693 virtual Listeners
const& getListeners()
const = 0;
5699 #include <algorithm> 5708 void prepareExpandedExpression(AssertionResult&
result);
5711 std::string getFormattedDuration(
double duration );
5713 std::string serializeFilters( std::vector<std::string>
const& container );
5715 template<
typename DerivedT>
5716 struct StreamingReporterBase : IStreamingReporter {
5718 StreamingReporterBase( ReporterConfig
const&
_config )
5719 : m_config( _config.fullConfig() ),
5720 stream( _config.stream() )
5722 m_reporterPrefs.shouldRedirectStdOut =
false;
5723 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5724 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5727 ReporterPreferences getPreferences()
const override {
5728 return m_reporterPrefs;
5731 static std::set<Verbosity> getSupportedVerbosities() {
5735 ~StreamingReporterBase()
override =
default;
5737 void noMatchingTestCases(
std::string const&)
override {}
5739 void reportInvalidArguments(
std::string const&)
override {}
5741 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5742 currentTestRunInfo = _testRunInfo;
5745 void testGroupStarting(GroupInfo
const& _groupInfo)
override {
5746 currentGroupInfo = _groupInfo;
5749 void testCaseStarting(
TestCaseInfo const& _testInfo)
override {
5750 currentTestCaseInfo = _testInfo;
5752 void sectionStarting(
SectionInfo const& _sectionInfo)
override {
5753 m_sectionStack.push_back(_sectionInfo);
5756 void sectionEnded(SectionStats
const& )
override {
5757 m_sectionStack.pop_back();
5759 void testCaseEnded(TestCaseStats
const& )
override {
5760 currentTestCaseInfo.reset();
5762 void testGroupEnded(TestGroupStats
const& )
override {
5763 currentGroupInfo.reset();
5765 void testRunEnded(TestRunStats
const& )
override {
5766 currentTestCaseInfo.reset();
5767 currentGroupInfo.reset();
5768 currentTestRunInfo.reset();
5779 LazyStat<TestRunInfo> currentTestRunInfo;
5780 LazyStat<GroupInfo> currentGroupInfo;
5781 LazyStat<TestCaseInfo> currentTestCaseInfo;
5783 std::vector<SectionInfo> m_sectionStack;
5784 ReporterPreferences m_reporterPrefs;
5787 template<
typename DerivedT>
5788 struct CumulativeReporterBase : IStreamingReporter {
5789 template<
typename T,
typename ChildNodeT>
5791 explicit Node( T
const& _value ) :
value( _value ) {}
5794 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5796 ChildNodes children;
5798 struct SectionNode {
5799 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5800 virtual ~SectionNode() =
default;
5802 bool operator == (SectionNode
const& other)
const {
5803 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5805 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5810 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5811 using Assertions = std::vector<AssertionStats>;
5812 ChildSections childSections;
5813 Assertions assertions;
5818 struct BySectionInfo {
5819 BySectionInfo(
SectionInfo const& other ) : m_other( other ) {}
5820 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
5821 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5822 return ((node->stats.sectionInfo.name == m_other.name) &&
5823 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5825 void operator=(BySectionInfo
const&) =
delete;
5831 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5832 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5833 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5835 CumulativeReporterBase( ReporterConfig
const&
_config )
5836 : m_config( _config.fullConfig() ),
5837 stream( _config.stream() )
5839 m_reporterPrefs.shouldRedirectStdOut =
false;
5840 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5841 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5843 ~CumulativeReporterBase()
override =
default;
5845 ReporterPreferences getPreferences()
const override {
5846 return m_reporterPrefs;
5849 static std::set<Verbosity> getSupportedVerbosities() {
5853 void testRunStarting( TestRunInfo
const& )
override {}
5854 void testGroupStarting( GroupInfo
const& )
override {}
5856 void testCaseStarting(
TestCaseInfo const& )
override {}
5858 void sectionStarting(
SectionInfo const& sectionInfo )
override {
5859 SectionStats incompleteStats( sectionInfo,
Counts(), 0,
false );
5860 std::shared_ptr<SectionNode> node;
5861 if( m_sectionStack.empty() ) {
5862 if( !m_rootSection )
5863 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5864 node = m_rootSection;
5867 SectionNode& parentNode = *m_sectionStack.back();
5869 std::find_if( parentNode.childSections.begin(),
5870 parentNode.childSections.end(),
5871 BySectionInfo( sectionInfo ) );
5872 if(
it == parentNode.childSections.end() ) {
5873 node = std::make_shared<SectionNode>( incompleteStats );
5874 parentNode.childSections.push_back( node );
5879 m_sectionStack.push_back( node );
5885 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5886 assert(!m_sectionStack.empty());
5892 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5893 SectionNode& sectionNode = *m_sectionStack.back();
5894 sectionNode.assertions.push_back(assertionStats);
5897 void sectionEnded(SectionStats
const& sectionStats)
override {
5898 assert(!m_sectionStack.empty());
5899 SectionNode& node = *m_sectionStack.back();
5900 node.stats = sectionStats;
5901 m_sectionStack.pop_back();
5903 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5904 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5905 assert(m_sectionStack.size() == 0);
5906 node->children.push_back(m_rootSection);
5907 m_testCases.push_back(node);
5908 m_rootSection.reset();
5910 assert(m_deepestSection);
5911 m_deepestSection->stdOut = testCaseStats.stdOut;
5912 m_deepestSection->stdErr = testCaseStats.stdErr;
5914 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5915 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5916 node->children.swap(m_testCases);
5917 m_testGroups.push_back(node);
5919 void testRunEnded(TestRunStats
const& testRunStats)
override {
5920 auto node = std::make_shared<TestRunNode>(testRunStats);
5921 node->children.swap(m_testGroups);
5922 m_testRuns.push_back(node);
5923 testRunEndedCumulative();
5925 virtual void testRunEndedCumulative() = 0;
5931 std::vector<AssertionStats> m_assertions;
5932 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5933 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5934 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5936 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5938 std::shared_ptr<SectionNode> m_rootSection;
5939 std::shared_ptr<SectionNode> m_deepestSection;
5940 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5941 ReporterPreferences m_reporterPrefs;
5945 char const* getLineOfChars() {
5946 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5948 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5949 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5954 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5955 TestEventListenerBase( ReporterConfig
const&
_config );
5957 static std::set<Verbosity> getSupportedVerbosities();
5960 bool assertionEnded(AssertionStats
const&)
override;
5984 BrightRed = Bright | Red,
5985 BrightGreen = Bright | Green,
5986 LightGrey = Bright | Grey,
5987 BrightWhite = Bright | White,
5988 BrightYellow = Bright | Yellow,
5991 FileName = LightGrey,
5992 Warning = BrightYellow,
5993 ResultError = BrightRed,
5994 ResultSuccess = BrightGreen,
5995 ResultExpectedFailure = Warning,
6000 OriginalExpression = Cyan,
6001 ReconstructedExpression = BrightYellow,
6003 SecondaryText = LightGrey,
6008 Colour( Code _colourCode );
6009 Colour( Colour&& other ) noexcept;
6010 Colour& operator=( Colour&& other ) noexcept;
6014 static void use( Code _colourCode );
6017 bool m_moved =
false;
6020 std::ostream&
operator << ( std::ostream& os, Colour
const& );
6030 template<
typename T>
6031 class ReporterRegistrar {
6033 class ReporterFactory :
public IReporterFactory {
6035 IStreamingReporterPtr create( ReporterConfig
const&
config )
const override {
6036 return std::unique_ptr<T>(
new T( config ) );
6040 return T::getDescription();
6051 template<
typename T>
6052 class ListenerRegistrar {
6054 class ListenerFactory :
public IReporterFactory {
6056 IStreamingReporterPtr create( ReporterConfig
const&
config )
const override {
6057 return std::unique_ptr<T>(
new T( config ) );
6066 ListenerRegistrar() {
6072 #if !defined(CATCH_CONFIG_DISABLE) 6074 #define CATCH_REGISTER_REPORTER( name, reporterType ) \ 6075 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6076 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6077 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ 6078 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6080 #define CATCH_REGISTER_LISTENER( listenerType ) \ 6081 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6082 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6083 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ 6084 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6085 #else // CATCH_CONFIG_DISABLE 6087 #define CATCH_REGISTER_REPORTER(name, reporterType) 6088 #define CATCH_REGISTER_LISTENER(listenerType) 6090 #endif // CATCH_CONFIG_DISABLE 6098 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6100 using StreamingReporterBase::StreamingReporterBase;
6102 ~CompactReporter()
override;
6106 ReporterPreferences getPreferences()
const override;
6108 void noMatchingTestCases(
std::string const& spec)
override;
6112 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6114 void sectionEnded(SectionStats
const& _sectionStats)
override;
6116 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6125 #if defined(_MSC_VER) 6126 #pragma warning(push) 6127 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 6134 struct SummaryColumn;
6137 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6138 std::unique_ptr<TablePrinter> m_tablePrinter;
6140 ConsoleReporter(ReporterConfig
const&
config);
6141 ~ConsoleReporter()
override;
6144 void noMatchingTestCases(
std::string const& spec)
override;
6150 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6152 void sectionStarting(
SectionInfo const& _sectionInfo)
override;
6153 void sectionEnded(SectionStats
const& _sectionStats)
override;
6155 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6157 void benchmarkStarting(BenchmarkInfo
const&
info)
override;
6158 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6160 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6162 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6163 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6164 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6165 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6170 void lazyPrintWithoutClosingBenchmarkTable();
6171 void lazyPrintRunInfo();
6172 void lazyPrintGroupInfo();
6173 void printTestCaseAndSectionHeader();
6180 void printHeaderString(
std::string const& _string, std::size_t indent = 0);
6182 void printTotals(
Totals const& totals);
6183 void printSummaryRow(
std::string const&
label, std::vector<SummaryColumn>
const& cols, std::size_t
row);
6185 void printTotalsDivider(
Totals const& totals);
6186 void printSummaryDivider();
6187 void printTestFilters();
6190 bool m_headerPrinted =
false;
6195 #if defined(_MSC_VER) 6196 #pragma warning(pop) 6207 enum class XmlFormatting {
6213 XmlFormatting
operator | (XmlFormatting
lhs, XmlFormatting rhs);
6214 XmlFormatting
operator & (XmlFormatting lhs, XmlFormatting rhs);
6218 enum ForWhat { ForTextNodes, ForAttributes };
6220 XmlEncode(
std::string const&
str, ForWhat forWhat = ForTextNodes );
6222 void encodeTo( std::ostream& os )
const;
6224 friend std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode );
6234 class ScopedElement {
6236 ScopedElement( XmlWriter* writer, XmlFormatting
fmt );
6238 ScopedElement( ScopedElement&& other ) noexcept;
6239 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6245 template<
typename T>
6247 m_writer->writeAttribute( name, attribute );
6252 mutable XmlWriter* m_writer =
nullptr;
6253 XmlFormatting m_fmt;
6259 XmlWriter( XmlWriter
const& ) =
delete;
6260 XmlWriter& operator=( XmlWriter
const& ) =
delete;
6270 XmlWriter& writeAttribute(
std::string const& name,
bool attribute );
6272 template<
typename T>
6273 XmlWriter& writeAttribute(
std::string const& name, T
const& attribute ) {
6276 return writeAttribute( name, rss.
str() );
6283 void writeStylesheetRef(
std::string const& url );
6285 XmlWriter& writeBlankLine();
6287 void ensureTagClosed();
6291 void applyFormatting(XmlFormatting
fmt);
6293 void writeDeclaration();
6295 void newlineIfNecessary();
6297 bool m_tagIsOpen =
false;
6298 bool m_needsNewline =
false;
6299 std::vector<std::string> m_tags;
6309 class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6311 JunitReporter(ReporterConfig
const&
_config);
6313 ~JunitReporter()
override;
6317 void noMatchingTestCases(
std::string const& )
override;
6319 void testRunStarting(TestRunInfo
const& runInfo)
override;
6321 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6323 void testCaseStarting(
TestCaseInfo const& testCaseInfo)
override;
6324 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6326 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6328 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6330 void testRunEndedCumulative()
override;
6332 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6334 void writeTestCase(TestCaseNode
const& testCaseNode);
6338 SectionNode
const& sectionNode);
6340 void writeAssertions(SectionNode
const& sectionNode);
6341 void writeAssertion(AssertionStats
const& stats);
6347 unsigned int unexpectedExceptions = 0;
6348 bool m_okToFail =
false;
6357 class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6359 XmlReporter(ReporterConfig
const&
_config);
6361 ~XmlReporter()
override;
6371 void noMatchingTestCases(
std::string const&
s)
override;
6373 void testRunStarting(TestRunInfo
const& testInfo)
override;
6375 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6377 void testCaseStarting(
TestCaseInfo const& testInfo)
override;
6379 void sectionStarting(
SectionInfo const& sectionInfo)
override;
6383 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6385 void sectionEnded(SectionStats
const& sectionStats)
override;
6387 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6389 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6391 void testRunEnded(TestRunStats
const& testRunStats)
override;
6393 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6395 void benchmarkStarting(BenchmarkInfo
const&)
override;
6396 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6397 void benchmarkFailed(
std::string const&)
override;
6398 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6401 Timer m_testCaseTimer;
6403 int m_sectionDepth = 0;
6413 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6438 namespace Benchmark {
6439 template <
typename Clock>
6440 using ClockDuration =
typename Clock::duration;
6441 template <
typename Clock>
6442 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6444 template <
typename Clock>
6445 using TimePoint =
typename Clock::time_point;
6447 using default_clock = std::chrono::steady_clock;
6449 template <
typename Clock>
6451 TimePoint<Clock> operator()()
const {
6456 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6466 #if defined(_MSC_VER) 6471 namespace Benchmark {
6472 #if defined(__GNUC__) || defined(__clang__) 6473 template <
typename T>
6474 inline void keep_memory(T*
p) {
6475 asm volatile(
"" : :
"g"(
p) :
"memory");
6477 inline void keep_memory() {
6478 asm volatile(
"" : : :
"memory");
6482 inline void optimizer_barrier() { keep_memory(); }
6484 #elif defined(_MSC_VER) 6486 #pragma optimize("", off) 6487 template <
typename T>
6488 inline void keep_memory(T* p) {
6490 *
reinterpret_cast<char volatile*
>(
p) = *reinterpret_cast<char const volatile*>(p);
6493 #pragma optimize("", on) 6496 inline void optimizer_barrier() {
6497 std::atomic_thread_fence(std::memory_order_seq_cst);
6503 template <
typename T>
6504 inline void deoptimize_value(T&&
x) {
6508 template <
typename Fn,
typename... Args>
6509 inline auto invoke_deoptimized(Fn&& fn, Args&&...
args) ->
typename std::enable_if<!std::is_same<
void, decltype(fn(
args...))>
::value>
::type {
6510 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(
args...)));
6513 template <
typename Fn,
typename... Args>
6514 inline auto invoke_deoptimized(Fn&& fn, Args&&...
args) ->
typename std::enable_if<std::is_same<
void, decltype(fn(
args...))>
::value>
::type {
6515 std::forward<Fn>(fn) (std::forward<Args...>(
args...));
6526 #include <type_traits> 6530 namespace Benchmark {
6532 template <
typename T>
6533 struct CompleteType {
using type =
T; };
6535 struct CompleteType<void> {
struct type {}; };
6537 template <
typename T>
6540 template <
typename Result>
6541 struct CompleteInvoker {
6542 template <
typename Fun,
typename... Args>
6543 static Result invoke(Fun&& fun, Args&&...
args) {
6544 return std::forward<Fun>(fun)(std::forward<Args>(
args)...);
6548 struct CompleteInvoker<void> {
6549 template <
typename Fun,
typename... Args>
6550 static CompleteType_t<void> invoke(Fun&& fun, Args&&...
args) {
6551 std::forward<Fun>(fun)(std::forward<Args>(
args)...);
6555 template <
typename Sig>
6559 template <
typename Fun,
typename... Args>
6560 CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&...
args) {
6561 return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(
args)...);
6564 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6567 template <
typename Fun>
6568 Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
6570 return Detail::complete_invoke(std::forward<Fun>(fun));
6581 namespace Benchmark {
6583 struct ChronometerConcept {
6584 virtual void start() = 0;
6585 virtual void finish() = 0;
6586 virtual ~ChronometerConcept() =
default;
6588 template <
typename Clock>
6589 struct ChronometerModel final :
public ChronometerConcept {
6593 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6595 TimePoint<Clock> started;
6596 TimePoint<Clock> finished;
6600 struct Chronometer {
6602 template <
typename Fun>
6605 int runs()
const {
return k; }
6607 Chronometer(Detail::ChronometerConcept& meter,
int k)
6612 template <
typename Fun>
6617 template <
typename Fun>
6619 Detail::optimizer_barrier();
6621 for (
int i = 0;
i < k; ++
i) invoke_deoptimized(fun,
i);
6623 Detail::optimizer_barrier();
6626 Detail::ChronometerConcept*
impl;
6639 namespace Benchmark {
6640 template <
typename Duration>
6641 struct EnvironmentEstimate {
6643 OutlierClassification outliers;
6645 template <
typename Duration2>
6646 operator EnvironmentEstimate<Duration2>()
const {
6647 return { mean, outliers };
6650 template <
typename Clock>
6651 struct Environment {
6652 using clock_type =
Clock;
6653 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6654 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6671 #include <type_traits> 6676 namespace Benchmark {
6678 template <
typename T>
6680 template <
typename T,
typename U>
6682 : std::is_same<Decay<T>, Decay<U>> {};
6691 struct BenchmarkFunction {
6694 virtual void call(Chronometer meter)
const = 0;
6695 virtual callable* clone()
const = 0;
6696 virtual ~callable() =
default;
6698 template <
typename Fun>
6699 struct model :
public callable {
6701 model(Fun
const& fun) : fun(fun) {}
6703 model<Fun>* clone()
const override {
return new model<Fun>(*this); }
6705 void call(Chronometer meter)
const override {
6718 struct do_nothing {
void operator()()
const {} };
6720 template <
typename T>
6721 BenchmarkFunction(model<T>*
c) :
f(c) {}
6725 :
f(
new model<do_nothing>{ {} }) {}
6727 template <
typename Fun,
6729 BenchmarkFunction(Fun&& fun)
6732 BenchmarkFunction(BenchmarkFunction&& that)
6735 BenchmarkFunction(BenchmarkFunction
const& that)
6736 :
f(that.f->clone()) {}
6738 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6743 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6744 f.reset(that.f->clone());
6748 void operator()(Chronometer meter)
const {
f->call(meter); }
6751 std::unique_ptr<callable>
f;
6763 #include <type_traits> 6767 namespace Benchmark {
6769 template <
typename Fun>
6771 void operator()(
int k)
const {
6772 for (
int i = 0;
i < k; ++
i) {
6778 template <
typename Fun>
6780 return { std::forward<Fun>(fun) };
6803 #include <type_traits> 6806 namespace Benchmark {
6807 template <
typename Duration,
typename Result>
6813 template <
typename Clock,
typename Sig>
6814 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
6822 namespace Benchmark {
6824 template <
typename Clock,
typename Fun,
typename... Args>
6827 auto&&
r = Detail::complete_invoke(fun, std::forward<Args>(
args)...);
6829 auto delta = end -
start;
6830 return { delta, std::forward<decltype(r)>(
r), 1 };
6838 #include <type_traits> 6841 namespace Benchmark {
6843 template <
typename Clock,
typename Fun>
6844 TimingOf<Clock, Fun(int)> measure_one(Fun&& fun,
int iters,
std::false_type) {
6845 return Detail::measure<Clock>(fun, iters);
6847 template <
typename Clock,
typename Fun>
6848 TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun,
int iters,
std::true_type) {
6849 Detail::ChronometerModel<Clock> meter;
6850 auto&&
result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6855 template <
typename Clock,
typename Fun>
6858 struct optimized_away_error : std::exception {
6859 const char* what()
const noexcept
override {
6860 return "could not measure benchmark, maybe it was optimized away";
6864 template <
typename Clock,
typename Fun>
6865 TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6867 while (iters < (1 << 30)) {
6870 if (Timing.elapsed >= how_long) {
6871 return { Timing.elapsed,
std::move(Timing.result), iters };
6875 throw optimized_away_error{};
6882 #include <algorithm> 6885 namespace Benchmark {
6886 template <
typename Duration>
6887 struct ExecutionPlan {
6888 int iterations_per_sample;
6890 Detail::BenchmarkFunction benchmark;
6892 int warmup_iterations;
6894 template <
typename Duration2>
6895 operator ExecutionPlan<Duration2>()
const {
6896 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6899 template <
typename Clock>
6900 std::vector<FloatDuration<Clock>>
run(
const IConfig &
cfg, Environment<FloatDuration<Clock>> env)
const {
6902 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
Detail::repeat(now<Clock>{}));
6904 std::vector<FloatDuration<Clock>>
times;
6906 std::generate_n(std::back_inserter(times), cfg.
benchmarkSamples(), [this, env] {
6907 Detail::ChronometerModel<Clock>
model;
6908 this->benchmark(Chronometer(model, iterations_per_sample));
6909 auto sample_time = model.elapsed() - env.clock_cost.mean;
6910 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6911 return sample_time / iterations_per_sample;
6930 #include <algorithm> 6931 #include <functional> 6942 namespace Benchmark {
6944 using sample = std::vector<double>;
6946 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator
first, std::vector<double>::iterator last);
6948 template <
typename Iterator>
6949 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6950 std::vector<double>
copy(first, last);
6952 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6953 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6955 auto los = q1 - (iqr * 3.);
6956 auto lom = q1 - (iqr * 1.5);
6957 auto him = q3 + (iqr * 1.5);
6958 auto his = q3 + (iqr * 3.);
6960 OutlierClassification o;
6961 for (; first != last; ++
first) {
6963 if (
t < los) ++o.low_severe;
6964 else if (
t < lom) ++o.low_mild;
6965 else if (
t > his) ++o.high_severe;
6966 else if (
t > him) ++o.high_mild;
6972 template <
typename Iterator>
6973 double mean(Iterator first, Iterator last) {
6975 double sum = std::accumulate(first, last, 0.);
6979 template <
typename URng,
typename Iterator,
typename Estimator>
6980 sample resample(URng&
rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
6982 std::uniform_int_distribution<decltype(n)>
dist(0,
n - 1);
6985 out.reserve(resamples);
6986 std::generate_n(std::back_inserter(out), resamples, [
n, first, &estimator, &dist, &rng] {
6987 std::vector<double> resampled;
6988 resampled.reserve(
n);
6989 std::generate_n(std::back_inserter(resampled),
n, [first, &dist, &rng] {
return first[dist(rng)]; });
6990 return estimator(resampled.begin(), resampled.end());
6996 template <
typename Estimator,
typename Iterator>
6997 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7003 for (
auto it = first;
it != last; ++
it) {
7004 std::iter_swap(
it, first);
7005 results.push_back(estimator(second, last));
7011 inline double normal_cdf(
double x) {
7012 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7015 double erfc_inv(
double x);
7017 double normal_quantile(
double p);
7019 template <
typename Iterator,
typename Estimator>
7020 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last,
sample const& resample, Estimator&& estimator) {
7021 auto n_samples = last -
first;
7023 double point = estimator(first, last);
7027 sample jack = jackknife(estimator, first, last);
7028 double jack_mean = mean(jack.begin(), jack.end());
7029 double sum_squares, sum_cubes;
7030 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> {
7031 auto d = jack_mean -
x;
7034 return { sqcb.first + d2, sqcb.second + d3 };
7037 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7038 int n =
static_cast<int>(resample.size());
7039 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) {
return x <
point; }) / (
double)
n;
7043 double bias = normal_quantile(prob_n);
7044 double z1 = normal_quantile((1. - confidence_level) / 2.);
7046 auto cumn = [n](
double x) ->
int {
7047 return std::lround(normal_cdf(x) * n); };
7048 auto a = [bias, accel](
double b) {
return bias +
b / (1. - accel *
b); };
7049 double b1 = bias + z1;
7050 double b2 = bias - z1;
7053 auto lo = std::max(cumn(a1), 0);
7054 auto hi =
std::min(cumn(a2), n - 1);
7056 return {
point, resample[lo], resample[hi], confidence_level };
7059 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7061 struct bootstrap_analysis {
7062 Estimate<double> mean;
7063 Estimate<double> standard_deviation;
7064 double outlier_variance;
7067 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7073 #include <algorithm> 7080 namespace Benchmark {
7082 template <
typename Clock>
7083 std::vector<double> resolution(
int k) {
7084 std::vector<TimePoint<Clock>>
times;
7085 times.reserve(k + 1);
7086 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7088 std::vector<double> deltas;
7091 std::back_inserter(deltas),
7092 [](TimePoint<Clock>
a, TimePoint<Clock>
b) {
return static_cast<double>((a -
b).
count()); });
7097 const auto warmup_iterations = 10000;
7098 const auto warmup_time = std::chrono::milliseconds(100);
7099 const auto minimum_ticks = 1000;
7100 const auto warmup_seed = 10000;
7101 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7102 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7103 const auto clock_cost_estimation_tick_limit = 100000;
7104 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7105 const auto clock_cost_estimation_iterations = 10000;
7107 template <
typename Clock>
7109 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7112 template <
typename Clock>
7113 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7114 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7117 FloatDuration<Clock>(mean(
r.begin(),
r.end())),
7118 classify_outliers(
r.begin(),
r.end()),
7121 template <
typename Clock>
7122 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7123 auto time_limit =
std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
7124 auto time_clock = [](
int k) {
7125 return Detail::measure<Clock>([k] {
7126 for (
int i = 0;
i < k; ++
i) {
7133 int iters = clock_cost_estimation_iterations;
7134 auto&&
r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7135 std::vector<double>
times;
7136 int nsamples =
static_cast<int>(std::ceil(time_limit /
r.elapsed));
7137 times.reserve(nsamples);
7138 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &
r] {
7139 return static_cast<double>((time_clock(
r.iterations) /
r.iterations).
count());
7142 FloatDuration<Clock>(mean(times.begin(), times.end())),
7143 classify_outliers(times.begin(), times.end()),
7147 template <
typename Clock>
7148 Environment<FloatDuration<Clock>> measure_environment() {
7149 static Environment<FloatDuration<Clock>>* env =
nullptr;
7154 auto iters = Detail::warmup<Clock>();
7155 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7156 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7158 env =
new Environment<FloatDuration<Clock>>{ resolution, cost };
7176 #include <algorithm> 7182 namespace Benchmark {
7183 template <
typename Duration>
7184 struct SampleAnalysis {
7185 std::vector<Duration>
samples;
7186 Estimate<Duration> mean;
7187 Estimate<Duration> standard_deviation;
7188 OutlierClassification outliers;
7189 double outlier_variance;
7191 template <
typename Duration2>
7192 operator SampleAnalysis<Duration2>()
const {
7193 std::vector<Duration2> samples2;
7194 samples2.reserve(samples.size());
7195 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
Duration d) {
return Duration2(
d); });
7209 #include <algorithm> 7214 namespace Benchmark {
7216 template <
typename Duration,
typename Iterator>
7217 SampleAnalysis<Duration> analyse(
const IConfig &
cfg, Environment<Duration>, Iterator
first, Iterator last) {
7220 samples.reserve(last - first);
7224 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7226 auto wrap_estimate = [](Estimate<double>
e) {
7227 return Estimate<Duration> {
7231 e.confidence_interval,
7234 std::vector<Duration> samples2;
7235 samples2.reserve(samples.size());
7236 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
double d) {
return Duration(d); });
7239 wrap_estimate(analysis.mean),
7240 wrap_estimate(analysis.standard_deviation),
7242 analysis.outlier_variance,
7245 std::vector<Duration>
samples;
7246 samples.reserve(last - first);
7250 for (
auto it = first;
it < last; ++
it, ++
i) {
7258 Estimate<Duration>{mean, mean, mean, 0.0},
7260 OutlierClassification{},
7270 #include <algorithm> 7271 #include <functional> 7277 namespace Benchmark {
7282 template <
class FUN>
7286 template <
typename Clock>
7287 ExecutionPlan<FloatDuration<Clock>> prepare(
const IConfig &
cfg, Environment<FloatDuration<Clock>> env)
const {
7288 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7289 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.
benchmarkWarmupTime()));
7290 auto&&
test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7291 int new_iters =
static_cast<int>(std::ceil(min_time *
test.iterations /
test.elapsed));
7295 template <
typename Clock = default_clock>
7299 auto env = Detail::measure_environment<Clock>();
7303 auto plan = user_code([&] {
7304 return prepare<Clock>(*
cfg, env);
7307 BenchmarkInfo
info {
7309 plan.estimated_duration.count(),
7310 plan.iterations_per_sample,
7311 cfg->benchmarkSamples(),
7312 cfg->benchmarkResamples(),
7313 env.clock_resolution.mean.count(),
7314 env.clock_cost.mean.count()
7319 auto samples = user_code([&] {
7320 return plan.template run<Clock>(*
cfg, env);
7323 auto analysis = Detail::analyse(*cfg, env,
samples.begin(),
samples.end());
7324 BenchmarkStats<FloatDuration<Clock>> stats{
info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7329 std::rethrow_exception(std::current_exception());
7334 template <
typename Fun,
7336 Benchmark & operator=(Fun
func) {
7337 fun = Detail::BenchmarkFunction(func);
7342 explicit operator bool() {
7347 Detail::BenchmarkFunction fun;
7353 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1 7354 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2 7356 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\ 7357 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ 7358 BenchmarkName = [&](int benchmarkIndex) 7360 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\ 7361 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ 7370 #include <type_traits> 7373 namespace Benchmark {
7375 template <
typename T,
bool Destruct>
7376 struct ObjectStorage
7380 ObjectStorage() :
data() {}
7382 ObjectStorage(
const ObjectStorage& other)
7384 new(&
data)
T(other.stored_object());
7387 ObjectStorage(ObjectStorage&& other)
7392 ~ObjectStorage() { destruct_on_exit<T>(); }
7394 template <
typename... Args>
7397 new (&
data)
T(std::forward<Args>(
args)...);
7400 template <
bool AllowManualDestruction = !Destruct>
7403 stored_object().~T();
7408 template <
typename U>
7411 template <
typename U>
7414 T& stored_object() {
7415 return *
static_cast<T*
>(
static_cast<void*
>(&
data));
7418 T
const& stored_object()
const {
7419 return *
static_cast<T*
>(
static_cast<void*
>(&
data));
7426 template <
typename T>
7427 using storage_for = Detail::ObjectStorage<T, true>;
7429 template <
typename T>
7430 using destructable_object = Detail::ObjectStorage<T, false>;
7438 #endif // ! CATCH_CONFIG_IMPL_ONLY 7444 #pragma clang diagnostic push 7445 #pragma clang diagnostic ignored "-Wweak-vtables" 7456 namespace TestCaseTracking {
7458 struct NameAndLocation {
7467 using ITrackerPtr = std::shared_ptr<ITracker>;
7470 virtual ~ITracker();
7473 virtual NameAndLocation
const& nameAndLocation()
const = 0;
7476 virtual bool isComplete()
const = 0;
7477 virtual bool isSuccessfullyCompleted()
const = 0;
7478 virtual bool isOpen()
const = 0;
7479 virtual bool hasChildren()
const = 0;
7481 virtual ITracker& parent() = 0;
7484 virtual void close() = 0;
7485 virtual void fail() = 0;
7486 virtual void markAsNeedingAnotherRun() = 0;
7488 virtual void addChild( ITrackerPtr
const& child ) = 0;
7489 virtual ITrackerPtr findChild( NameAndLocation
const& nameAndLocation ) = 0;
7490 virtual void openChild() = 0;
7493 virtual bool isSectionTracker()
const = 0;
7494 virtual bool isGeneratorTracker()
const = 0;
7497 class TrackerContext {
7505 ITrackerPtr m_rootTracker;
7506 ITracker* m_currentTracker =
nullptr;
7507 RunState m_runState = NotStarted;
7511 ITracker& startRun();
7515 void completeCycle();
7517 bool completedCycle()
const;
7518 ITracker& currentTracker();
7519 void setCurrentTracker( ITracker*
tracker );
7522 class TrackerBase :
public ITracker {
7529 CompletedSuccessfully,
7533 using Children = std::vector<ITrackerPtr>;
7534 NameAndLocation m_nameAndLocation;
7535 TrackerContext& m_ctx;
7537 Children m_children;
7538 CycleState m_runState = NotStarted;
7541 TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext&
ctx, ITracker* parent );
7543 NameAndLocation
const& nameAndLocation()
const override;
7544 bool isComplete()
const override;
7545 bool isSuccessfullyCompleted()
const override;
7546 bool isOpen()
const override;
7547 bool hasChildren()
const override;
7549 void addChild( ITrackerPtr
const& child )
override;
7551 ITrackerPtr findChild( NameAndLocation
const& nameAndLocation )
override;
7552 ITracker& parent()
override;
7554 void openChild()
override;
7556 bool isSectionTracker()
const override;
7557 bool isGeneratorTracker()
const override;
7561 void close()
override;
7562 void fail()
override;
7563 void markAsNeedingAnotherRun()
override;
7570 class SectionTracker :
public TrackerBase {
7571 std::vector<std::string> m_filters;
7574 SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext&
ctx, ITracker* parent );
7576 bool isSectionTracker()
const override;
7578 bool isComplete()
const override;
7580 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation );
7584 void addInitialFilters( std::vector<std::string>
const&
filters );
7585 void addNextFilters( std::vector<std::string>
const& filters );
7590 using TestCaseTracking::ITracker;
7591 using TestCaseTracking::TrackerContext;
7592 using TestCaseTracking::SectionTracker;
7602 struct LeakDetector {
7614 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 7619 #if defined(CATCH_CONFIG_USE_ASYNC) 7624 double erf_inv(
double x) {
7628 w = -
log((1.0 - x) * (1.0 + x));
7632 p = -3.6444120640178196996e-21;
7633 p = -1.685059138182016589e-19 + p *
w;
7634 p = 1.2858480715256400167e-18 + p *
w;
7635 p = 1.115787767802518096e-17 + p *
w;
7636 p = -1.333171662854620906e-16 + p *
w;
7637 p = 2.0972767875968561637e-17 + p *
w;
7638 p = 6.6376381343583238325e-15 + p *
w;
7639 p = -4.0545662729752068639e-14 + p *
w;
7640 p = -8.1519341976054721522e-14 + p *
w;
7641 p = 2.6335093153082322977e-12 + p *
w;
7642 p = -1.2975133253453532498e-11 + p *
w;
7643 p = -5.4154120542946279317e-11 + p *
w;
7644 p = 1.051212273321532285e-09 + p *
w;
7645 p = -4.1126339803469836976e-09 + p *
w;
7646 p = -2.9070369957882005086e-08 + p *
w;
7647 p = 4.2347877827932403518e-07 + p *
w;
7648 p = -1.3654692000834678645e-06 + p *
w;
7649 p = -1.3882523362786468719e-05 + p *
w;
7650 p = 0.0001867342080340571352 + p *
w;
7651 p = -0.00074070253416626697512 + p *
w;
7652 p = -0.0060336708714301490533 + p *
w;
7653 p = 0.24015818242558961693 + p *
w;
7654 p = 1.6536545626831027356 + p *
w;
7655 }
else if (w < 16.000000) {
7656 w = sqrt(w) - 3.250000;
7657 p = 2.2137376921775787049e-09;
7658 p = 9.0756561938885390979e-08 + p *
w;
7659 p = -2.7517406297064545428e-07 + p *
w;
7660 p = 1.8239629214389227755e-08 + p *
w;
7661 p = 1.5027403968909827627e-06 + p *
w;
7662 p = -4.013867526981545969e-06 + p *
w;
7663 p = 2.9234449089955446044e-06 + p *
w;
7664 p = 1.2475304481671778723e-05 + p *
w;
7665 p = -4.7318229009055733981e-05 + p *
w;
7666 p = 6.8284851459573175448e-05 + p *
w;
7667 p = 2.4031110387097893999e-05 + p *
w;
7668 p = -0.0003550375203628474796 + p *
w;
7669 p = 0.00095328937973738049703 + p *
w;
7670 p = -0.0016882755560235047313 + p *
w;
7671 p = 0.0024914420961078508066 + p *
w;
7672 p = -0.0037512085075692412107 + p *
w;
7673 p = 0.005370914553590063617 + p *
w;
7674 p = 1.0052589676941592334 + p *
w;
7675 p = 3.0838856104922207635 + p *
w;
7677 w = sqrt(w) - 5.000000;
7678 p = -2.7109920616438573243e-11;
7679 p = -2.5556418169965252055e-10 + p *
w;
7680 p = 1.5076572693500548083e-09 + p *
w;
7681 p = -3.7894654401267369937e-09 + p *
w;
7682 p = 7.6157012080783393804e-09 + p *
w;
7683 p = -1.4960026627149240478e-08 + p *
w;
7684 p = 2.9147953450901080826e-08 + p *
w;
7685 p = -6.7711997758452339498e-08 + p *
w;
7686 p = 2.2900482228026654717e-07 + p *
w;
7687 p = -9.9298272942317002539e-07 + p *
w;
7688 p = 4.5260625972231537039e-06 + p *
w;
7689 p = -1.9681778105531670567e-05 + p *
w;
7690 p = 7.5995277030017761139e-05 + p *
w;
7691 p = -0.00021503011930044477347 + p *
w;
7692 p = -0.00013871931833623122026 + p *
w;
7693 p = 1.0103004648645343977 + p *
w;
7694 p = 4.8499064014085844221 + p *
w;
7699 double standard_deviation(std::vector<double>::iterator
first, std::vector<double>::iterator last) {
7700 auto m = Catch::Benchmark::Detail::mean(first, last);
7701 double variance = std::accumulate(first, last, 0., [
m](
double a,
double b) {
7702 double diff = b -
m;
7703 return a + diff * diff;
7704 }) / (last - first);
7705 return std::sqrt(variance);
7711 namespace Benchmark {
7714 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator
first, std::vector<double>::iterator last) {
7716 double idx = (
count - 1) * k / static_cast<double>(q);
7717 int j =
static_cast<int>(
idx);
7719 std::nth_element(first, first + j, last);
7721 if (g == 0)
return xj;
7723 auto xj1 = *std::min_element(first + (j + 1), last);
7724 return xj + g * (xj1 - xj);
7727 double erfc_inv(
double x) {
7728 return erf_inv(1.0 - x);
7731 double normal_quantile(
double p) {
7732 static const double ROOT_TWO = std::sqrt(2.0);
7735 assert(p >= 0 && p <= 1);
7740 result = -erfc_inv(2.0 * p);
7747 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7748 double sb = stddev.point;
7749 double mn = mean.point /
n;
7750 double mg_min = mn / 2.;
7751 double sg =
std::min(mg_min / 4., sb / std::sqrt(n));
7752 double sg2 = sg * sg;
7753 double sb2 = sb * sb;
7755 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7759 double k0 = -n * nd;
7760 double k1 = sb2 - n * sg2 + nd;
7761 double det = k1 * k1 - 4 * sg2 * k0;
7762 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7765 auto var_out = [n, sb2, sg2](
double c) {
7767 return (nc / n) * (sb2 - nc * sg2);
7770 return std::min(var_out(1), var_out(
std::min(c_max(0.), c_max(mg_min)))) / sb2;
7773 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7776 static std::random_device entropy;
7779 auto n =
static_cast<int>(last -
first);
7781 auto mean = &Detail::mean<std::vector<double>::iterator>;
7782 auto stddev = &standard_deviation;
7784 #if defined(CATCH_CONFIG_USE_ASYNC) 7785 auto Estimate = [=](double(*
f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7786 auto seed = entropy();
7787 return std::async(std::launch::async, [=] {
7788 std::mt19937
rng(seed);
7789 auto resampled = resample(rng, n_resamples, first, last,
f);
7790 return bootstrap(confidence_level, first, last, resampled,
f);
7794 auto mean_future = Estimate(mean);
7795 auto stddev_future = Estimate(stddev);
7797 auto mean_estimate = mean_future.get();
7798 auto stddev_estimate = stddev_future.get();
7800 auto Estimate = [=](double(*
f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7801 auto seed = entropy();
7802 std::mt19937
rng(seed);
7803 auto resampled = resample(rng, n_resamples, first, last,
f);
7804 return bootstrap(confidence_level, first, last, resampled,
f);
7807 auto mean_estimate = Estimate(mean);
7808 auto stddev_estimate = Estimate(stddev);
7809 #endif // CATCH_USE_ASYNC 7811 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7813 return { mean_estimate, stddev_estimate, outlier_variance };
7819 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 7830 bool marginComparison(
double lhs,
double rhs,
double margin) {
7831 return (lhs + margin >= rhs) && (rhs + margin >=
lhs);
7840 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7852 temp.m_value = -temp.m_value;
7862 bool Approx::equalityComparisonImpl(
const double other)
const {
7865 return marginComparison(m_value, other, m_margin)
7866 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7869 void Approx::setMargin(
double newMargin) {
7871 "Invalid Approx::margin: " << newMargin <<
'.' 7872 <<
" Approx::Margin has to be non-negative.");
7873 m_margin = newMargin;
7876 void Approx::setEpsilon(
double newEpsilon) {
7878 "Invalid Approx::epsilon: " << newEpsilon <<
'.' 7879 <<
" Approx::epsilon has to be in [0, 1]");
7880 m_epsilon = newEpsilon;
7885 namespace literals {
7905 bool isDebuggerActive();
7908 #ifdef CATCH_PLATFORM_MAC 7910 #define CATCH_TRAP() __asm__("int $3\n" : : ) 7912 #elif defined(CATCH_PLATFORM_IPHONE) 7915 #if defined(__i386__) || defined(__x86_64__) 7916 #define CATCH_TRAP() __asm__("int $3") 7917 #elif defined(__aarch64__) 7918 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7919 #elif defined(__arm__) && !defined(__thumb__) 7920 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") 7921 #elif defined(__arm__) && defined(__thumb__) 7922 #define CATCH_TRAP() __asm__(".inst 0xde01") 7925 #elif defined(CATCH_PLATFORM_LINUX) 7929 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) 7930 #define CATCH_TRAP() asm volatile ("int $3") 7931 #else // Fall back to the generic way. 7934 #define CATCH_TRAP() raise(SIGTRAP) 7936 #elif defined(_MSC_VER) 7937 #define CATCH_TRAP() __debugbreak() 7938 #elif defined(__MINGW32__) 7939 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7940 #define CATCH_TRAP() DebugBreak() 7943 #ifndef CATCH_BREAK_INTO_DEBUGGER 7945 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() 7947 #define CATCH_BREAK_INTO_DEBUGGER() []{}() 7959 #if defined(CATCH_PLATFORM_WINDOWS) 7961 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) 7962 # define CATCH_DEFINED_NOMINMAX 7965 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) 7966 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN 7967 # define WIN32_LEAN_AND_MEAN 7973 #include <windows.h> 7976 #ifdef CATCH_DEFINED_NOMINMAX 7979 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN 7980 # undef WIN32_LEAN_AND_MEAN 7983 #endif // defined(CATCH_PLATFORM_WINDOWS) 7986 #if defined( CATCH_CONFIG_WINDOWS_SEH ) 7990 struct FatalConditionHandler {
7992 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
7993 FatalConditionHandler();
7994 static void reset();
7995 ~FatalConditionHandler();
7999 static ULONG guaranteeSize;
8000 static PVOID exceptionHandlerHandle;
8005 #elif defined ( CATCH_CONFIG_POSIX_SIGNALS ) 8011 struct FatalConditionHandler {
8014 static struct sigaction oldSigActions[];
8015 static stack_t oldSigStack;
8016 static char altStackMem[];
8018 static void handleSignal(
int sig );
8020 FatalConditionHandler();
8021 ~FatalConditionHandler();
8022 static void reset();
8030 struct FatalConditionHandler {
8049 RunContext( RunContext
const& ) =
delete;
8050 RunContext& operator =( RunContext
const& ) =
delete;
8052 explicit RunContext(
IConfigPtr const&
_config, IStreamingReporterPtr&& reporter );
8054 ~RunContext()
override;
8056 void testGroupStarting(
std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8057 void testGroupEnded(
std::string const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8062 IStreamingReporter& reporter()
const;
8076 void handleUnexpectedExceptionNotThrown
8079 void handleUnexpectedInflightException
8083 void handleIncomplete
8090 bool sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions )
override;
8093 void sectionEndedEarly(
SectionEndInfo const& endInfo )
override;
8097 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 8099 void benchmarkStarting( BenchmarkInfo
const& info )
override;
8100 void benchmarkEnded( BenchmarkStats<>
const& stats )
override;
8102 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 8104 void pushScopedMessage(
MessageInfo const& message )
override;
8105 void popScopedMessage(
MessageInfo const& message )
override;
8107 void emplaceUnscopedMessage(
MessageBuilder const& builder )
override;
8111 const AssertionResult* getLastResult()
const override;
8113 void exceptionEarlyReported()
override;
8115 void handleFatalErrorCondition(
StringRef message )
override;
8117 bool lastAssertionPassed()
override;
8119 void assertionPassed()
override;
8123 bool aborting()
const final;
8128 void invokeActiveTestCase();
8130 void resetAssertionInfo();
8131 bool testForMissingAssertions(
Counts& assertions );
8133 void assertionEnded( AssertionResult
const&
result );
8144 void handleUnfinishedSections();
8146 TestRunInfo m_runInfo;
8148 TestCase const* m_activeTestCase =
nullptr;
8149 ITracker* m_testCaseTracker =
nullptr;
8154 IStreamingReporterPtr m_reporter;
8155 std::vector<MessageInfo> m_messages;
8156 std::vector<ScopedMessage> m_messageScopes;
8158 std::vector<SectionEndInfo> m_unfinishedSections;
8159 std::vector<ITracker*> m_activeSections;
8160 TrackerContext m_trackerContext;
8161 bool m_lastAssertionPassed =
false;
8162 bool m_shouldReportUnexpected =
true;
8163 bool m_includeSuccessfulResults;
8181 : m_isNegated( isNegated )
8186 LazyExpression::operator bool()
const {
8187 return m_transientExpression !=
nullptr;
8201 os <<
"{** error - unchecked empty expression requested **}";
8211 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8216 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8219 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8228 if( m_reaction.shouldDebugBreak ) {
8234 CATCH_BREAK_INTO_DEBUGGER();
8236 if (m_reaction.shouldThrow) {
8237 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 8240 CATCH_ERROR(
"Test failure requires aborting test!" );
8253 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8256 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8260 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8264 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8279 lazyExpression(_lazyExpression),
8280 resultType(_resultType) {}
8282 std::string AssertionResultData::reconstructExpression()
const {
8284 if( reconstructedExpression.empty() ) {
8285 if( lazyExpression ) {
8287 rss << lazyExpression;
8288 reconstructedExpression = rss.
str();
8291 return reconstructedExpression;
8296 m_resultData( data )
8300 bool AssertionResult::succeeded()
const {
8310 return m_resultData.resultType;
8313 bool AssertionResult::hasExpression()
const {
8314 return !m_info.capturedExpression.empty();
8317 bool AssertionResult::hasMessage()
const {
8318 return !m_resultData.message.empty();
8321 std::string AssertionResult::getExpression()
const {
8323 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8327 expr += m_info.capturedExpression;
8334 std::string AssertionResult::getExpressionInMacro()
const {
8336 if( m_info.macroName.empty() )
8337 expr = static_cast<std::string>(m_info.capturedExpression);
8339 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8340 expr += m_info.macroName;
8342 expr += m_info.capturedExpression;
8348 bool AssertionResult::hasExpandedExpression()
const {
8349 return hasExpression() && getExpandedExpression() != getExpression();
8352 std::string AssertionResult::getExpandedExpression()
const {
8353 std::string expr = m_resultData.reconstructExpression();
8360 return m_resultData.message;
8363 return m_info.lineInfo;
8366 StringRef AssertionResult::getTestMacroName()
const {
8367 return m_info.macroName;
8396 #ifdef CLARA_CONFIG_CONSOLE_WIDTH 8397 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8398 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8400 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 8403 #pragma clang diagnostic push 8404 #pragma clang diagnostic ignored "-Wweak-vtables" 8405 #pragma clang diagnostic ignored "-Wexit-time-destructors" 8406 #pragma clang diagnostic ignored "-Wshadow" 8420 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8421 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 8424 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8425 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8428 #ifndef CLARA_CONFIG_OPTIONAL_TYPE 8429 #ifdef __has_include 8430 #if __has_include(<optional>) && __cplusplus >= 201703L 8432 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional 8454 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8455 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 8460 namespace TextFlow {
8462 inline auto isWhitespace(
char c) ->
bool {
8464 return chars.find(c) != std::string::npos;
8466 inline auto isBreakableBefore(
char c) ->
bool {
8468 return chars.find(c) != std::string::npos;
8470 inline auto isBreakableAfter(
char c) ->
bool {
8472 return chars.find(c) != std::string::npos;
8478 std::vector<std::string> m_strings;
8479 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8480 size_t m_indent = 0;
8481 size_t m_initialIndent = std::string::npos;
8488 size_t m_stringIndex = 0;
8493 bool m_suffix =
false;
8497 m_stringIndex(stringIndex) {}
8499 auto line()
const ->
std::string const& {
return m_column.m_strings[m_stringIndex]; }
8501 auto isBoundary(
size_t at)
const ->
bool {
8505 return at ==
line().size() ||
8506 (isWhitespace(
line()[at]) && !isWhitespace(
line()[at - 1])) ||
8507 isBreakableBefore(
line()[at]) ||
8508 isBreakableAfter(
line()[at - 1]);
8512 assert(m_stringIndex < m_column.m_strings.size());
8515 auto width = m_column.m_width - indent();
8517 if (
line()[m_pos] ==
'\n') {
8523 if (m_end < m_pos +
width) {
8524 m_len = m_end - m_pos;
8527 while (len > 0 && !isBoundary(m_pos + len))
8529 while (len > 0 && isWhitespace(
line()[m_pos + len - 1]))
8541 auto indent()
const ->
size_t {
8542 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8543 return initial == std::string::npos ? m_column.m_indent : initial;
8547 return std::string(indent(),
' ') + (m_suffix ? plain +
"-" : plain);
8551 using difference_type = std::ptrdiff_t;
8553 using pointer = value_type * ;
8555 using iterator_category = std::forward_iterator_tag;
8557 explicit iterator(
Column const& column) : m_column(column) {
8558 assert(m_column.m_width > m_column.m_indent);
8559 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8566 assert(m_stringIndex < m_column.m_strings.size());
8568 return addIndentAndSuffix(
line().substr(m_pos, m_len));
8576 while (m_pos <
line().
size() && isWhitespace(
line()[m_pos]))
8583 if (m_stringIndex < m_column.m_strings.size())
8588 iterator prev(*
this);
8593 auto operator ==(iterator
const& other)
const ->
bool {
8595 m_pos == other.m_pos &&
8596 m_stringIndex == other.m_stringIndex &&
8597 &m_column == &other.m_column;
8599 auto operator !=(iterator
const& other)
const ->
bool {
8603 using const_iterator = iterator;
8612 auto indent(
size_t newIndent) ->
Column& {
8613 m_indent = newIndent;
8616 auto initialIndent(
size_t newIndent) ->
Column& {
8617 m_initialIndent = newIndent;
8621 auto width()
const ->
size_t {
return m_width; }
8622 auto begin()
const -> iterator {
return iterator(*
this); }
8623 auto end()
const -> iterator {
return { *
this, m_strings.size() }; }
8627 for (
auto line : col) {
8640 std::ostringstream oss;
8646 class Spacer :
public Column {
8649 explicit Spacer(
size_t spaceWidth) :
Column(
"") {
8655 std::vector<Column> m_columns;
8663 std::vector<Column>
const& m_columns;
8664 std::vector<Column::iterator> m_iterators;
8665 size_t m_activeIterators;
8667 iterator(
Columns const& columns, EndTag)
8668 : m_columns(columns.m_columns),
8669 m_activeIterators(0) {
8670 m_iterators.reserve(m_columns.size());
8672 for (
auto const&
col : m_columns)
8673 m_iterators.push_back(
col.end());
8677 using difference_type = std::ptrdiff_t;
8679 using pointer = value_type * ;
8681 using iterator_category = std::forward_iterator_tag;
8683 explicit iterator(
Columns const& columns)
8684 : m_columns(columns.m_columns),
8685 m_activeIterators(m_columns.size()) {
8686 m_iterators.reserve(m_columns.size());
8688 for (
auto const&
col : m_columns)
8689 m_iterators.push_back(
col.begin());
8692 auto operator ==(iterator
const& other)
const ->
bool {
8693 return m_iterators == other.m_iterators;
8695 auto operator !=(iterator
const& other)
const ->
bool {
8696 return m_iterators != other.m_iterators;
8701 for (
size_t i = 0;
i < m_columns.size(); ++
i) {
8702 auto width = m_columns[i].width();
8703 if (m_iterators[
i] != m_columns[
i].
end()) {
8705 row += padding +
col;
8706 if (col.size() <
width)
8717 for (
size_t i = 0;
i < m_columns.size(); ++
i) {
8718 if (m_iterators[
i] != m_columns[
i].
end())
8724 iterator prev(*
this);
8729 using const_iterator = iterator;
8731 auto begin()
const -> iterator {
return iterator(*
this); }
8732 auto end()
const -> iterator {
return { *
this, iterator::EndTag() }; }
8735 m_columns.push_back(col);
8747 for (
auto line : cols) {
8758 std::ostringstream oss;
8782 #include <algorithm> 8784 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) 8785 #define CATCH_PLATFORM_WINDOWS 8788 namespace Catch {
namespace clara {
8792 template<
typename L>
8793 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8795 template<
typename ClassT,
typename ReturnT,
typename... Args>
8796 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8797 static const bool isValid =
false;
8800 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8801 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8802 static const bool isValid =
true;
8804 using ReturnType = ReturnT;
8813 std::vector<std::string> m_args;
8816 Args(
int argc,
char const*
const* argv )
8817 : m_exeName(argv[0]),
8818 m_args(argv + 1, argv + argc) {}
8820 Args( std::initializer_list<std::string>
args )
8821 : m_exeName( *args.begin() ),
8822 m_args( args.begin()+1, args.end() )
8832 enum class TokenType {
8840 inline auto isOptPrefix(
char c ) ->
bool {
8842 #ifdef CATCH_PLATFORM_WINDOWS 8850 using Iterator = std::vector<std::string>::const_iterator;
8853 std::vector<Token> m_tokenBuffer;
8856 m_tokenBuffer.resize( 0 );
8859 while( it != itEnd && it->empty() )
8864 if( isOptPrefix(
next[0] ) ) {
8865 auto delimiterPos =
next.find_first_of(
" :=" );
8866 if( delimiterPos != std::string::npos ) {
8867 m_tokenBuffer.push_back( { TokenType::Option,
next.substr( 0, delimiterPos ) } );
8868 m_tokenBuffer.push_back( { TokenType::Argument,
next.substr( delimiterPos + 1 ) } );
8870 if(
next[1] !=
'-' &&
next.size() > 2 ) {
8872 for(
size_t i = 1;
i <
next.size(); ++
i ) {
8874 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8877 m_tokenBuffer.push_back( { TokenType::Option,
next } );
8881 m_tokenBuffer.push_back( { TokenType::Argument,
next } );
8887 explicit TokenStream( Args
const &
args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8889 TokenStream( Iterator it, Iterator itEnd ) :
it( it ), itEnd( itEnd ) {
8893 explicit operator bool()
const {
8894 return !m_tokenBuffer.empty() || it != itEnd;
8897 auto count()
const ->
size_t {
return m_tokenBuffer.size() + (itEnd -
it); }
8900 assert( !m_tokenBuffer.empty() );
8901 return m_tokenBuffer.front();
8904 auto operator->()
const ->
Token const * {
8905 assert( !m_tokenBuffer.empty() );
8906 return &m_tokenBuffer.front();
8910 if( m_tokenBuffer.size() >= 2 ) {
8911 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8924 Ok, LogicError, RuntimeError
8928 ResultBase(
Type type ) : m_type( type ) {}
8929 virtual ~ResultBase() =
default;
8931 virtual void enforceOk()
const = 0;
8936 template<
typename T>
8937 class ResultValueBase :
public ResultBase {
8939 auto value()
const -> T
const & {
8945 ResultValueBase(
Type type ) : ResultBase( type ) {}
8947 ResultValueBase( ResultValueBase
const &other ) : ResultBase( other ) {
8948 if( m_type == ResultBase::Ok )
8949 new( &m_value )
T( other.m_value );
8952 ResultValueBase(
Type, T
const &
value ) : ResultBase( Ok ) {
8953 new( &m_value )
T( value );
8956 auto operator=( ResultValueBase
const &other ) -> ResultValueBase & {
8957 if( m_type == ResultBase::Ok )
8959 ResultBase::operator=(other);
8960 if( m_type == ResultBase::Ok )
8961 new( &m_value )
T( other.m_value );
8965 ~ResultValueBase()
override {
8976 class ResultValueBase<void> :
public ResultBase {
8978 using ResultBase::ResultBase;
8981 template<
typename T =
void>
8982 class BasicResult :
public ResultValueBase<
T> {
8984 template<
typename U>
8985 explicit BasicResult( BasicResult<U>
const &other )
8986 : ResultValueBase<T>( other.type() ),
8987 m_errorMessage( other.errorMessage() )
8992 template<
typename U>
8993 static auto ok( U
const &
value ) -> BasicResult {
return { ResultBase::Ok, value }; }
8994 static auto ok() -> BasicResult {
return { ResultBase::Ok }; }
8995 static auto logicError(
std::string const &
message ) -> BasicResult {
return { ResultBase::LogicError, message }; }
8996 static auto runtimeError(
std::string const &message ) -> BasicResult {
return { ResultBase::RuntimeError, message }; }
8998 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9000 auto errorMessage()
const ->
std::string {
return m_errorMessage; }
9003 void enforceOk()
const override {
9007 assert( m_type != ResultBase::LogicError );
9008 assert( m_type != ResultBase::RuntimeError );
9009 if( m_type != ResultBase::Ok )
9016 : ResultValueBase<T>(
type),
9017 m_errorMessage(message)
9019 assert( m_type != ResultBase::Ok );
9022 using ResultValueBase<T>::ResultValueBase;
9023 using ResultBase::m_type;
9026 enum class ParseResultType {
9027 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9033 ParseState( ParseResultType
type, TokenStream
const &remainingTokens )
9035 m_remainingTokens( remainingTokens )
9038 auto type()
const -> ParseResultType {
return m_type; }
9039 auto remainingTokens()
const -> TokenStream {
return m_remainingTokens; }
9042 ParseResultType m_type;
9043 TokenStream m_remainingTokens;
9046 using Result = BasicResult<void>;
9047 using ParserResult = BasicResult<ParseResultType>;
9048 using InternalParseResult = BasicResult<ParseState>;
9050 struct HelpColumns {
9055 template<
typename T>
9057 std::stringstream ss;
9061 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9063 return ParserResult::ok( ParseResultType::Matched );
9067 return ParserResult::ok( ParseResultType::Matched );
9069 inline auto convertInto(
std::string const &source,
bool &target ) -> ParserResult {
9071 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
char c ) {
return static_cast<char>( std::tolower(c) ); } );
9072 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9074 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9077 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9078 return ParserResult::ok( ParseResultType::Matched );
9080 #ifdef CLARA_CONFIG_OPTIONAL_TYPE 9081 template<
typename T>
9082 inline auto convertInto(
std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9084 auto result = convertInto( source, temp );
9089 #endif // CLARA_CONFIG_OPTIONAL_TYPE 9100 virtual ~BoundRef() =
default;
9101 virtual auto isContainer()
const ->
bool {
return false; }
9102 virtual auto isFlag()
const ->
bool {
return false; }
9104 struct BoundValueRefBase : BoundRef {
9105 virtual auto setValue(
std::string const &
arg ) -> ParserResult = 0;
9107 struct BoundFlagRefBase : BoundRef {
9108 virtual auto setFlag(
bool flag ) -> ParserResult = 0;
9109 virtual auto isFlag()
const ->
bool {
return true; }
9112 template<
typename T>
9113 struct BoundValueRef : BoundValueRefBase {
9116 explicit BoundValueRef( T &
ref ) : m_ref( ref ) {}
9118 auto setValue(
std::string const &
arg ) -> ParserResult
override {
9119 return convertInto( arg, m_ref );
9123 template<
typename T>
9124 struct BoundValueRef<std::vector<
T>> : BoundValueRefBase {
9125 std::vector<T> &m_ref;
9127 explicit BoundValueRef( std::vector<T> &
ref ) : m_ref( ref ) {}
9129 auto isContainer()
const ->
bool override {
return true; }
9131 auto setValue(
std::string const &
arg ) -> ParserResult
override {
9133 auto result = convertInto( arg, temp );
9135 m_ref.push_back( temp );
9140 struct BoundFlagRef : BoundFlagRefBase {
9143 explicit BoundFlagRef(
bool &
ref ) : m_ref( ref ) {}
9145 auto setFlag(
bool flag ) -> ParserResult
override {
9147 return ParserResult::ok( ParseResultType::Matched );
9151 template<
typename ReturnType>
9152 struct LambdaInvoker {
9155 template<
typename L,
typename ArgType>
9156 static auto invoke( L
const &lambda, ArgType
const &
arg ) -> ParserResult {
9157 return lambda( arg );
9162 struct LambdaInvoker<void> {
9163 template<
typename L,
typename ArgType>
9164 static auto invoke( L
const &lambda, ArgType
const &
arg ) -> ParserResult {
9166 return ParserResult::ok( ParseResultType::Matched );
9170 template<
typename ArgType,
typename L>
9171 inline auto invokeLambda( L
const &lambda,
std::string const &
arg ) -> ParserResult {
9173 auto result = convertInto( arg, temp );
9176 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9179 template<
typename L>
9180 struct BoundLambda : BoundValueRefBase {
9183 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9184 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9186 auto setValue(
std::string const &arg ) -> ParserResult
override {
9187 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9191 template<
typename L>
9192 struct BoundFlagLambda : BoundFlagRefBase {
9195 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9196 static_assert( std::is_same<
typename UnaryLambdaTraits<L>::ArgType,
bool>::
value,
"flags must be boolean" );
9198 explicit BoundFlagLambda( L
const &lambda ) : m_lambda( lambda ) {}
9200 auto setFlag(
bool flag ) -> ParserResult
override {
9201 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9205 enum class Optionality { Optional, Required };
9211 virtual ~ParserBase() =
default;
9212 virtual auto validate()
const -> Result {
return Result::ok(); }
9213 virtual auto parse(
std::string const& exeName, TokenStream
const &tokens)
const -> InternalParseResult = 0;
9214 virtual auto cardinality()
const ->
size_t {
return 1; }
9216 auto parse( Args
const &
args )
const -> InternalParseResult {
9217 return parse( args.exeName(), TokenStream( args ) );
9221 template<
typename DerivedT>
9222 class ComposableParserImpl :
public ParserBase {
9224 template<
typename T>
9225 auto operator|( T
const &other )
const -> Parser;
9227 template<
typename T>
9228 auto operator+( T
const &other )
const -> Parser;
9232 template<
typename DerivedT>
9233 class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9235 Optionality m_optionality = Optionality::Optional;
9236 std::shared_ptr<BoundRef> m_ref;
9240 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &
ref ) : m_ref( ref ) {}
9243 template<
typename T>
9245 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9249 template<
typename LambdaT>
9250 ParserRefImpl( LambdaT
const &ref,
std::string const &hint )
9251 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9255 auto operator()(
std::string const &description ) -> DerivedT & {
9256 m_description = description;
9257 return static_cast<DerivedT &
>( *this );
9260 auto optional() -> DerivedT & {
9261 m_optionality = Optionality::Optional;
9262 return static_cast<DerivedT &
>( *this );
9266 m_optionality = Optionality::Required;
9267 return static_cast<DerivedT &
>( *this );
9270 auto isOptional()
const ->
bool {
9271 return m_optionality == Optionality::Optional;
9274 auto cardinality()
const ->
size_t override {
9275 if( m_ref->isContainer() )
9281 auto hint()
const ->
std::string {
return m_hint; }
9284 class ExeName :
public ComposableParserImpl<ExeName> {
9285 std::shared_ptr<std::string> m_name;
9286 std::shared_ptr<BoundValueRefBase> m_ref;
9288 template<
typename LambdaT>
9289 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9290 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9294 ExeName() : m_name( std::make_shared<std::string>(
"<executable>" ) ) {}
9297 m_ref = std::make_shared<BoundValueRef<std::string>>(
ref );
9300 template<
typename LambdaT>
9301 explicit ExeName( LambdaT
const& lambda ) : ExeName() {
9302 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9306 auto parse(
std::string const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9307 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9311 auto set(
std::string const& newName ) -> ParserResult {
9313 auto lastSlash = newName.find_last_of(
"\\/" );
9314 auto filename = ( lastSlash == std::string::npos )
9316 : newName.substr( lastSlash+1 );
9320 return m_ref->setValue(
filename );
9322 return ParserResult::ok( ParseResultType::Matched );
9326 class Arg :
public ParserRefImpl<Arg> {
9328 using ParserRefImpl::ParserRefImpl;
9330 auto parse(
std::string const &, TokenStream
const &tokens )
const -> InternalParseResult
override {
9331 auto validationResult =
validate();
9332 if( !validationResult )
9333 return InternalParseResult( validationResult );
9335 auto remainingTokens = tokens;
9336 auto const &token = *remainingTokens;
9337 if( token.type != TokenType::Argument )
9338 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9340 assert( !m_ref->isFlag() );
9341 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9343 auto result = valueRef->setValue( remainingTokens->token );
9345 return InternalParseResult(
result );
9347 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9352 #ifdef CATCH_PLATFORM_WINDOWS 9353 if( optName[0] ==
'/' )
9354 return "-" + optName.substr( 1 );
9360 class Opt :
public ParserRefImpl<Opt> {
9362 std::vector<std::string> m_optNames;
9365 template<
typename LambdaT>
9366 explicit Opt( LambdaT
const &
ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9368 explicit Opt(
bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9370 template<
typename LambdaT>
9371 Opt( LambdaT
const &ref,
std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9373 template<
typename T>
9374 Opt( T &ref,
std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9376 auto operator[](
std::string const &optName ) -> Opt & {
9377 m_optNames.push_back( optName );
9381 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9382 std::ostringstream oss;
9384 for(
auto const &opt : m_optNames ) {
9391 if( !m_hint.empty() )
9392 oss <<
" <" << m_hint <<
">";
9393 return { { oss.str(), m_description } };
9396 auto isMatch(
std::string const &optToken )
const ->
bool {
9397 auto normalisedToken = normaliseOpt( optToken );
9398 for(
auto const &
name : m_optNames ) {
9399 if( normaliseOpt(
name ) == normalisedToken )
9407 auto parse(
std::string const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9408 auto validationResult =
validate();
9409 if( !validationResult )
9410 return InternalParseResult( validationResult );
9412 auto remainingTokens = tokens;
9413 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9414 auto const &token = *remainingTokens;
9415 if( isMatch(token.token ) ) {
9416 if( m_ref->isFlag() ) {
9417 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>( m_ref.get() );
9418 auto result = flagRef->setFlag(
true );
9420 return InternalParseResult(
result );
9421 if(
result.value() == ParseResultType::ShortCircuitAll )
9422 return InternalParseResult::ok( ParseState(
result.value(), remainingTokens ) );
9424 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9426 if( !remainingTokens )
9427 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9428 auto const &argToken = *remainingTokens;
9429 if( argToken.type != TokenType::Argument )
9430 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9431 auto result = valueRef->setValue( argToken.token );
9433 return InternalParseResult(
result );
9434 if(
result.value() == ParseResultType::ShortCircuitAll )
9435 return InternalParseResult::ok( ParseState(
result.value(), remainingTokens ) );
9437 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9440 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9443 auto validate()
const -> Result
override {
9444 if( m_optNames.empty() )
9445 return Result::logicError(
"No options supplied to Opt" );
9446 for(
auto const &
name : m_optNames ) {
9448 return Result::logicError(
"Option name cannot be empty" );
9449 #ifdef CATCH_PLATFORM_WINDOWS 9450 if(
name[0] !=
'-' &&
name[0] !=
'/' )
9451 return Result::logicError(
"Option name must begin with '-' or '/'" );
9453 if(
name[0] !=
'-' )
9454 return Result::logicError(
"Option name must begin with '-'" );
9462 Help(
bool &showHelpFlag )
9463 : Opt([&](
bool flag ) {
9464 showHelpFlag = flag;
9465 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9468 static_cast<Opt &
>( *this )
9469 (
"display usage information")
9470 [
"-?"][
"-h"][
"--help"]
9475 struct Parser : ParserBase {
9477 mutable ExeName m_exeName;
9478 std::vector<Opt> m_options;
9479 std::vector<Arg> m_args;
9481 auto operator|=( ExeName
const &exeName ) -> Parser & {
9482 m_exeName = exeName;
9486 auto operator|=( Arg
const &arg ) -> Parser & {
9487 m_args.push_back(arg);
9491 auto operator|=( Opt
const &opt ) -> Parser & {
9492 m_options.push_back(opt);
9496 auto operator|=( Parser
const &other ) -> Parser & {
9497 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9498 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9502 template<
typename T>
9503 auto operator|( T
const &other )
const -> Parser {
9504 return Parser( *
this ) |= other;
9508 template<
typename T>
9510 template<
typename T>
9513 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9514 std::vector<HelpColumns> cols;
9515 for (
auto const &o : m_options) {
9516 auto childCols = o.getHelpColumns();
9517 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9522 void writeToStream( std::ostream &os )
const {
9523 if (!m_exeName.name().empty()) {
9524 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9526 for(
auto const &arg : m_args ) {
9531 if( arg.isOptional() &&
required ) {
9535 os <<
"<" << arg.hint() <<
">";
9536 if( arg.cardinality() == 0 )
9541 if( !m_options.empty() )
9543 os <<
"\n\nwhere options are:" << std::endl;
9546 auto rows = getHelpColumns();
9547 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9548 size_t optWidth = 0;
9549 for(
auto const &cols : rows )
9550 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9552 optWidth = (
std::min)(optWidth, consoleWidth/2);
9554 for(
auto const &cols : rows ) {
9557 TextFlow::Spacer(4) +
9559 os <<
row << std::endl;
9563 friend auto operator<<( std::ostream &os, Parser
const &
parser ) -> std::ostream& {
9564 parser.writeToStream( os );
9568 auto validate()
const -> Result
override {
9569 for(
auto const &opt : m_options ) {
9570 auto result = opt.validate();
9574 for(
auto const &arg : m_args ) {
9575 auto result = arg.validate();
9579 return Result::ok();
9584 auto parse(
std::string const& exeName, TokenStream
const &tokens )
const -> InternalParseResult
override {
9587 ParserBase
const* parser =
nullptr;
9590 const size_t totalParsers = m_options.size() + m_args.size();
9591 assert( totalParsers < 512 );
9593 ParserInfo parseInfos[512];
9597 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9598 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9601 m_exeName.set( exeName );
9603 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9604 while(
result.value().remainingTokens() ) {
9605 bool tokenParsed =
false;
9607 for(
size_t i = 0;
i < totalParsers; ++
i ) {
9608 auto& parseInfo = parseInfos[i];
9609 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9610 result = parseInfo.parser->parse(exeName,
result.value().remainingTokens());
9613 if (
result.value().type() != ParseResultType::NoMatch) {
9621 if(
result.value().type() == ParseResultType::ShortCircuitAll )
9624 return InternalParseResult::runtimeError(
"Unrecognised token: " +
result.value().remainingTokens()->token );
9631 template<
typename DerivedT>
9632 template<
typename T>
9634 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9639 using detail::Parser;
9651 using detail::ExeName;
9657 using detail::ParseResultType;
9660 using detail::ParserResult;
9666 #pragma clang diagnostic pop 9670 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9671 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9672 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9678 clara::Parser makeCommandLineParser( ConfigData&
config );
9688 clara::Parser makeCommandLineParser( ConfigData&
config ) {
9690 using namespace clara;
9692 auto const setWarning = [&](
std::string const& warning ) {
9693 auto warningSet = [&]() {
9694 if( warning ==
"NoAssertions" )
9697 if ( warning ==
"NoTests" )
9704 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9705 config.warnings =
static_cast<WarnAbout::What>( config.warnings | warningSet );
9706 return ParserResult::ok( ParseResultType::Matched );
9711 return ParserResult::runtimeError(
"Unable to load input file: '" +
filename +
"'" );
9714 while( std::getline(
f, line ) ) {
9716 if( !line.empty() && !
startsWith( line,
'#' ) ) {
9718 line =
'"' + line +
'"';
9719 config.testsOrTags.push_back( line );
9720 config.testsOrTags.emplace_back(
"," );
9724 if(!config.testsOrTags.empty())
9725 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9727 return ParserResult::ok( ParseResultType::Matched );
9737 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" +
order +
"'" );
9738 return ParserResult::ok( ParseResultType::Matched );
9740 auto const setRngSeed = [&](
std::string const& seed ) {
9741 if( seed !=
"time" )
9742 return clara::detail::convertInto( seed, config.rngSeed );
9743 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9744 return ParserResult::ok( ParseResultType::Matched );
9746 auto const setColourUsage = [&](
std::string const& useColour ) {
9751 else if(
mode ==
"no" )
9753 else if(
mode ==
"auto" )
9756 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9757 return ParserResult::ok( ParseResultType::Matched );
9759 auto const setWaitForKeypress = [&](
std::string const& keypress ) {
9760 auto keypressLc =
toLower( keypress );
9761 if (keypressLc ==
"never")
9763 else if( keypressLc ==
"start" )
9765 else if( keypressLc ==
"exit" )
9767 else if( keypressLc ==
"both" )
9770 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9771 return ParserResult::ok( ParseResultType::Matched );
9773 auto const setVerbosity = [&](
std::string const& verbosity ) {
9774 auto lcVerbosity =
toLower( verbosity );
9775 if( lcVerbosity ==
"quiet" )
9777 else if( lcVerbosity ==
"normal" )
9779 else if( lcVerbosity ==
"high" )
9782 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9783 return ParserResult::ok( ParseResultType::Matched );
9785 auto const setReporter = [&](
std::string const& reporter ) {
9788 auto lcReporter =
toLower( reporter );
9789 auto result = factories.find( lcReporter );
9791 if( factories.end() !=
result )
9792 config.reporterName = lcReporter;
9794 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9795 return ParserResult::ok( ParseResultType::Matched );
9799 = ExeName( config.processName )
9800 | Help( config.showHelp )
9801 | Opt( config.listTests )
9802 ["-l"]["--list-tests"]
9803 (
"list all/matching test cases" )
9804 | Opt( config.listTags )
9805 ["-t"]["--list-tags"]
9806 (
"list all/matching tags" )
9807 | Opt( config.showSuccessfulTests )
9809 (
"include successful tests in output" )
9810 | Opt( config.shouldDebugBreak )
9812 (
"break into debugger on failure" )
9813 | Opt( config.noThrow )
9815 (
"skip exception tests" )
9816 | Opt( config.showInvisibles )
9817 ["-i"]["--invisibles"]
9818 (
"show invisibles (tabs, newlines)" )
9819 | Opt( config.outputFilename,
"filename" )
9821 (
"output filename" )
9822 | Opt( setReporter,
"name" )
9823 ["-r"]["--reporter"]
9824 (
"reporter to use (defaults to console)" )
9825 | Opt( config.name,
"name" )
9828 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9830 (
"abort at first failure" )
9831 | Opt( [&](
int x ){ config.abortAfter =
x; },
"no. failures" )
9833 (
"abort after x failures" )
9834 | Opt( setWarning,
"warning name" )
9836 (
"enable warnings" )
9838 [
"-d"][
"--durations"]
9839 (
"show test durations" )
9840 | Opt( loadTestNamesFromFile,
"filename" )
9841 ["-f"]["--input-file"]
9842 (
"load test names to run from a file" )
9843 | Opt( config.filenamesAsTags )
9844 ["-#"]["--filenames-as-tags"]
9845 (
"adds a tag for the filename" )
9846 | Opt( config.sectionsToRun,
"section name" )
9848 (
"specify section to run" )
9849 | Opt( setVerbosity,
"quiet|normal|high" )
9850 ["-v"]["--verbosity"]
9851 (
"set output verbosity" )
9852 | Opt( config.listTestNamesOnly )
9853 ["--list-test-names-only"]
9854 (
"list all/matching test cases names only" )
9855 | Opt( config.listReporters )
9856 ["--list-reporters"]
9857 (
"list all reporters" )
9858 | Opt( setTestOrder,
"decl|lex|rand" )
9860 (
"test case order (defaults to decl)" )
9861 | Opt( setRngSeed,
"'time'|number" )
9863 (
"set a specific seed for random numbers" )
9864 | Opt( setColourUsage,
"yes|no" )
9866 (
"should output be colourised" )
9867 | Opt( config.libIdentify )
9869 (
"report name and version according to libidentify standard" )
9870 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9871 ["--wait-for-keypress"]
9872 (
"waits for a keypress before exiting" )
9873 | Opt( config.benchmarkSamples,
"samples" )
9874 ["--benchmark-samples"]
9875 (
"number of samples to collect (default: 100)" )
9876 | Opt( config.benchmarkResamples,
"resamples" )
9877 ["--benchmark-resamples"]
9878 (
"number of resamples for the bootstrap (default: 100000)" )
9879 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9880 ["--benchmark-confidence-interval"]
9881 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9882 | Opt( config.benchmarkNoAnalysis )
9883 ["--benchmark-no-analysis"]
9884 (
"perform only measurements; do not perform any analysis" )
9885 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9886 ["--benchmark-warmup-time"]
9887 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9888 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9889 (
"which test or tests to use" );
9904 return line == other.
line && (file == other.
file || std::strcmp(file, other.
file) == 0);
9914 os << info.
file <<
'(' << info.
line <<
')';
9916 os << info.
file <<
':' << info.
line;
9934 Config::Config( ConfigData
const&
data )
9936 m_stream( openStream() )
9942 for (
auto& elem : m_data.testsOrTags) {
9945 for (
auto& elem : m_data.sectionsToRun) {
9950 if (!m_data.testsOrTags.empty()) {
9951 m_hasTestFilters =
true;
9952 for (
auto const& testOrTags : m_data.testsOrTags) {
9953 parser.parse(testOrTags);
9956 m_testSpec = parser.testSpec();
9960 return m_data.outputFilename ;
9963 bool Config::listTests()
const {
return m_data.listTests; }
9964 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
9965 bool Config::listTags()
const {
return m_data.listTags; }
9966 bool Config::listReporters()
const {
return m_data.listReporters; }
9968 std::string Config::getProcessName()
const {
return m_data.processName; }
9969 std::string const& Config::getReporterName()
const {
return m_data.reporterName; }
9971 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
9972 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
9974 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
9975 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
9977 bool Config::showHelp()
const {
return m_data.showHelp; }
9980 bool Config::allowThrows()
const {
return !m_data.noThrow; }
9981 std::ostream&
Config::stream()
const {
return m_stream->stream(); }
9983 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
9985 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings &
WarnAbout::NoTests); }
9990 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
9991 int Config::abortAfter()
const {
return m_data.abortAfter; }
9992 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
9993 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
9995 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
9996 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
9997 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
9998 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
9999 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10001 IStream const* Config::openStream() {
10009 #if defined(__clang__) 10010 # pragma clang diagnostic push 10011 # pragma clang diagnostic ignored "-Wexit-time-destructors" 10034 struct IColourImpl {
10035 virtual ~IColourImpl() =
default;
10036 virtual void use( Colour::Code _colourCode ) = 0;
10039 struct NoColourImpl : IColourImpl {
10040 void use( Colour::Code )
override {}
10042 static IColourImpl* instance() {
10043 static NoColourImpl s_instance;
10044 return &s_instance;
10051 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) 10052 # ifdef CATCH_PLATFORM_WINDOWS 10053 # define CATCH_CONFIG_COLOUR_WINDOWS 10055 # define CATCH_CONFIG_COLOUR_ANSI 10059 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) 10064 class Win32ColourImpl :
public IColourImpl {
10066 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10068 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10069 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10070 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10071 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10074 void use( Colour::Code _colourCode )
override {
10075 switch( _colourCode ) {
10076 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
10077 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10078 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
10079 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
10080 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
10081 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10082 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10083 case Colour::Grey:
return setTextAttribute( 0 );
10085 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
10086 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10087 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10088 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10089 case Colour::BrightYellow:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10099 void setTextAttribute( WORD _textAttribute ) {
10100 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10102 HANDLE stdoutHandle;
10103 WORD originalForegroundAttributes;
10104 WORD originalBackgroundAttributes;
10107 IColourImpl* platformColourInstance() {
10108 static Win32ColourImpl s_instance;
10112 ? config->useColour()
10118 : NoColourImpl::instance();
10124 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) 10126 #include <unistd.h> 10135 class PosixColourImpl :
public IColourImpl {
10137 void use( Colour::Code _colourCode )
override {
10138 switch( _colourCode ) {
10140 case Colour::White:
return setColour(
"[0m" );
10141 case Colour::Red:
return setColour(
"[0;31m" );
10142 case Colour::Green:
return setColour(
"[0;32m" );
10143 case Colour::Blue:
return setColour(
"[0;34m" );
10144 case Colour::Cyan:
return setColour(
"[0;36m" );
10145 case Colour::Yellow:
return setColour(
"[0;33m" );
10146 case Colour::Grey:
return setColour(
"[1;30m" );
10148 case Colour::LightGrey:
return setColour(
"[0;37m" );
10149 case Colour::BrightRed:
return setColour(
"[1;31m" );
10150 case Colour::BrightGreen:
return setColour(
"[1;32m" );
10151 case Colour::BrightWhite:
return setColour(
"[1;37m" );
10152 case Colour::BrightYellow:
return setColour(
"[1;33m" );
10158 static IColourImpl* instance() {
10159 static PosixColourImpl s_instance;
10160 return &s_instance;
10164 void setColour(
const char* _escapeCode ) {
10166 <<
'\033' << _escapeCode;
10170 bool useColourOnPlatform() {
10172 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10173 !isDebuggerActive() &&
10175 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) 10176 isatty(STDOUT_FILENO)
10182 IColourImpl* platformColourInstance() {
10186 ? config->useColour()
10189 colourMode = useColourOnPlatform()
10193 ? PosixColourImpl::instance()
10194 : NoColourImpl::instance();
10200 #else // not Windows or ANSI 10204 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
10208 #endif // Windows/ ANSI/ None 10212 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10213 Colour::Colour( Colour&& other ) noexcept {
10214 m_moved = other.m_moved;
10215 other.m_moved =
true;
10217 Colour& Colour::operator=( Colour&& other ) noexcept {
10218 m_moved = other.m_moved;
10219 other.m_moved =
true;
10223 Colour::~Colour(){
if( !m_moved ) use( None ); }
10225 void Colour::use( Code _colourCode ) {
10226 static IColourImpl*
impl = platformColourInstance();
10231 if (impl !=
nullptr) {
10232 impl->use( _colourCode );
10236 std::ostream&
operator << ( std::ostream& os, Colour
const& ) {
10242 #if defined(__clang__) 10243 # pragma clang diagnostic pop 10255 return m_resultCapture;
10257 IRunner* getRunner()
override {
10261 IConfigPtr const& getConfig()
const override {
10265 ~Context()
override;
10268 void setResultCapture(
IResultCapture* resultCapture )
override {
10269 m_resultCapture = resultCapture;
10271 void setRunner(
IRunner* runner )
override {
10290 currentContext =
new Context();
10295 IMutableContext::currentContext =
nullptr;
10299 Context::~Context() =
default;
10315 void writeToDebugConsole(
std::string const& text );
10319 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE) 10320 #include <android/log.h> 10323 void writeToDebugConsole(
std::string const& text ) {
10324 __android_log_write( ANDROID_LOG_DEBUG,
"Catch", text.c_str() );
10328 #elif defined(CATCH_PLATFORM_WINDOWS) 10331 void writeToDebugConsole(
std::string const& text ) {
10332 ::OutputDebugStringA( text.c_str() );
10339 void writeToDebugConsole(
std::string const& text ) {
10349 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10351 # include <cassert> 10352 # include <sys/types.h> 10353 # include <unistd.h> 10354 # include <cstddef> 10355 # include <ostream> 10357 #ifdef __apple_build_version__ 10360 # include <sys/sysctl.h> 10364 #ifdef __apple_build_version__ 10370 bool isDebuggerActive(){
10372 struct kinfo_proc info;
10378 info.kp_proc.p_flag = 0;
10384 mib[1] = KERN_PROC;
10385 mib[2] = KERN_PROC_PID;
10390 size =
sizeof(
info);
10391 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0 ) {
10392 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10398 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10401 bool isDebuggerActive() {
10408 #elif defined(CATCH_PLATFORM_LINUX) 10420 bool isDebuggerActive(){
10424 std::ifstream
in(
"/proc/self/status");
10426 static const int PREFIX_LEN = 11;
10427 if(
line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
10431 return line.length() > PREFIX_LEN &&
line[PREFIX_LEN] !=
'0';
10438 #elif defined(_MSC_VER) 10439 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10441 bool isDebuggerActive() {
10442 return IsDebuggerPresent() != 0;
10445 #elif defined(__MINGW32__) 10446 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10448 bool isDebuggerActive() {
10449 return IsDebuggerPresent() != 0;
10454 bool isDebuggerActive() {
return false; }
10465 if( lhs.size() + rhs.size() < 40 &&
10466 lhs.find(
'\n') == std::string::npos &&
10467 rhs.find(
'\n') == std::string::npos )
10468 os << lhs <<
" " << op <<
" " << rhs;
10470 os << lhs <<
"\n" << op <<
"\n" << rhs;
10476 #include <stdexcept> 10479 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) 10482 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n" 10483 <<
"The message was: " << e.what() <<
'\n';
10515 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const&
values );
10519 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10521 EnumInfo
const& registerEnum(
StringRef enumName,
StringRef allEnums, std::vector<int>
const& values)
override;
10546 size_t name_start = enumInstance.
size();
10547 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10550 return enumInstance.
substr(name_start, enumInstance.
size() - name_start);
10556 std::vector<StringRef> parsed;
10557 parsed.reserve( enumValues.size() );
10558 for(
auto const& enumValue : enumValues ) {
10559 parsed.push_back(
trim(extractInstanceName(enumValue)));
10564 EnumInfo::~EnumInfo() {}
10567 for(
auto const& valueToName : m_values ) {
10568 if( valueToName.first == value )
10569 return valueToName.second;
10571 return "{** unexpected enum value **}"_sr;
10574 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const&
values ) {
10575 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo );
10576 enumInfo->m_name = enumName;
10577 enumInfo->m_values.reserve( values.size() );
10579 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10580 assert( valueNames.size() == values.size() );
10582 for(
auto value : values )
10583 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10588 EnumInfo
const& EnumValuesRegistry::registerEnum(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const& values ) {
10589 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10590 return *m_enumInfos.back();
10602 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10603 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10618 ~ExceptionTranslatorRegistry();
10624 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10630 #import "Foundation/Foundation.h" 10635 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10638 void ExceptionTranslatorRegistry::registerTranslator(
const IExceptionTranslator* translator ) {
10639 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10642 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 10648 return tryTranslators();
10650 @catch (NSException *exception) {
10662 if (std::current_exception() ==
nullptr) {
10663 return "Non C++ exception. Possibly a CLR exception.";
10665 return tryTranslators();
10669 std::rethrow_exception(std::current_exception());
10671 catch( std::exception& ex ) {
10677 catch(
const char* msg ) {
10681 return "Unknown exception";
10685 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10686 if (m_translators.empty()) {
10687 std::rethrow_exception(std::current_exception());
10689 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10693 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 10695 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10698 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10699 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10707 #if defined(__GNUC__) 10708 # pragma GCC diagnostic push 10709 # pragma GCC diagnostic ignored "-Wmissing-field-initializers" 10712 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) 10716 void reportFatal(
char const *
const message ) {
10721 #endif // signals/SEH handling 10723 #if defined( CATCH_CONFIG_WINDOWS_SEH ) 10726 struct SignalDefs { DWORD
id;
const char*
name; };
10731 static SignalDefs signalDefs[] = {
10732 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10733 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10734 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10735 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10738 LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10739 for (
auto const& def : signalDefs) {
10740 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10741 reportFatal(def.name);
10746 return EXCEPTION_CONTINUE_SEARCH;
10749 FatalConditionHandler::FatalConditionHandler() {
10753 guaranteeSize = 32 * 1024;
10754 exceptionHandlerHandle =
nullptr;
10756 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10758 SetThreadStackGuarantee(&guaranteeSize);
10763 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
10764 SetThreadStackGuarantee(&guaranteeSize);
10765 exceptionHandlerHandle =
nullptr;
10770 FatalConditionHandler::~FatalConditionHandler() {
10774 bool FatalConditionHandler::isSet =
false;
10775 ULONG FatalConditionHandler::guaranteeSize = 0;
10776 PVOID FatalConditionHandler::exceptionHandlerHandle =
nullptr;
10780 #elif defined( CATCH_CONFIG_POSIX_SIGNALS ) 10784 struct SignalDefs {
10791 static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
10793 static SignalDefs signalDefs[] = {
10794 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10795 { SIGILL,
"SIGILL - Illegal instruction signal" },
10796 { SIGFPE,
"SIGFPE - Floating point error signal" },
10797 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10798 { SIGTERM,
"SIGTERM - Termination request signal" },
10799 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10802 void FatalConditionHandler::handleSignal(
int sig ) {
10803 char const *
name =
"<unknown signal>";
10804 for (
auto const& def : signalDefs) {
10805 if (sig == def.id) {
10815 FatalConditionHandler::FatalConditionHandler() {
10818 sigStack.ss_sp = altStackMem;
10819 sigStack.ss_size = sigStackSize;
10820 sigStack.ss_flags = 0;
10821 sigaltstack(&sigStack, &oldSigStack);
10822 struct sigaction sa = { };
10824 sa.sa_handler = handleSignal;
10825 sa.sa_flags = SA_ONSTACK;
10826 for (std::size_t
i = 0;
i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++
i) {
10827 sigaction(signalDefs[
i].
id, &sa, &oldSigActions[
i]);
10831 FatalConditionHandler::~FatalConditionHandler() {
10838 for( std::size_t
i = 0;
i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++
i ) {
10839 sigaction(signalDefs[
i].
id, &oldSigActions[
i],
nullptr);
10842 sigaltstack(&oldSigStack,
nullptr);
10847 bool FatalConditionHandler::isSet =
false;
10848 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
10849 stack_t FatalConditionHandler::oldSigStack = {};
10850 char FatalConditionHandler::altStackMem[sigStackSize] = {};
10860 #endif // signals/SEH handling 10862 #if defined(__GNUC__) 10863 # pragma GCC diagnostic pop 10879 namespace Generators {
10881 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10922 class ListeningReporter :
public IStreamingReporter {
10923 using Reporters = std::vector<IStreamingReporterPtr>;
10924 Reporters m_listeners;
10925 IStreamingReporterPtr m_reporter =
nullptr;
10926 ReporterPreferences m_preferences;
10929 ListeningReporter();
10931 void addListener( IStreamingReporterPtr&& listener );
10932 void addReporter( IStreamingReporterPtr&& reporter );
10936 ReporterPreferences getPreferences()
const override;
10938 void noMatchingTestCases(
std::string const& spec )
override;
10942 static std::set<Verbosity> getSupportedVerbosities();
10944 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 10946 void benchmarkStarting( BenchmarkInfo
const& benchmarkInfo )
override;
10947 void benchmarkEnded( BenchmarkStats<>
const& benchmarkStats )
override;
10948 void benchmarkFailed(
std::string const&)
override;
10949 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 10951 void testRunStarting( TestRunInfo
const& testRunInfo )
override;
10952 void testGroupStarting( GroupInfo
const& groupInfo )
override;
10953 void testCaseStarting(
TestCaseInfo const& testInfo )
override;
10954 void sectionStarting(
SectionInfo const& sectionInfo )
override;
10955 void assertionStarting(
AssertionInfo const& assertionInfo )
override;
10958 bool assertionEnded( AssertionStats
const& assertionStats )
override;
10959 void sectionEnded( SectionStats
const& sectionStats )
override;
10960 void testCaseEnded( TestCaseStats
const& testCaseStats )
override;
10961 void testGroupEnded( TestGroupStats
const& testGroupStats )
override;
10962 void testRunEnded( TestRunStats
const& testRunStats )
override;
10964 void skipTest(
TestCaseInfo const& testInfo )
override;
10965 bool isMulti()
const override;
10974 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig )
10975 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
10977 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream )
10978 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
10981 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
10986 std::size_t _groupIndex,
10987 std::size_t _groupsCount )
10989 groupIndex( _groupIndex ),
10990 groupsCounts( _groupsCount )
10993 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
10994 std::vector<MessageInfo>
const& _infoMessages,
10996 : assertionResult( _assertionResult ),
10997 infoMessages( _infoMessages ),
11000 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11002 if( assertionResult.hasMessage() ) {
11005 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11006 builder << assertionResult.getMessage();
11009 infoMessages.push_back( builder.m_info );
11013 AssertionStats::~AssertionStats() =
default;
11015 SectionStats::SectionStats(
SectionInfo const& _sectionInfo,
11016 Counts const& _assertions,
11017 double _durationInSeconds,
11018 bool _missingAssertions )
11019 : sectionInfo( _sectionInfo ),
11020 assertions( _assertions ),
11021 durationInSeconds( _durationInSeconds ),
11022 missingAssertions( _missingAssertions )
11025 SectionStats::~SectionStats() =
default;
11027 TestCaseStats::TestCaseStats(
TestCaseInfo const& _testInfo,
11032 : testInfo( _testInfo ),
11036 aborting( _aborting )
11039 TestCaseStats::~TestCaseStats() =
default;
11041 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11044 : groupInfo( _groupInfo ),
11046 aborting( _aborting )
11049 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11050 : groupInfo( _groupInfo ),
11054 TestGroupStats::~TestGroupStats() =
default;
11056 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11059 : runInfo( _runInfo ),
11061 aborting( _aborting )
11064 TestRunStats::~TestRunStats() =
default;
11066 void IStreamingReporter::fatalErrorEncountered(
StringRef ) {}
11067 bool IStreamingReporter::isMulti()
const {
return false; }
11069 IReporterFactory::~IReporterFactory() =
default;
11070 IReporterRegistry::~IReporterRegistry() =
default;
11089 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG 11090 #include <crtdbg.h> 11094 LeakDetector::LeakDetector() {
11095 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11096 flag |= _CRTDBG_LEAK_CHECK_DF;
11097 flag |= _CRTDBG_ALLOC_MEM_DF;
11098 _CrtSetDbgFlag(flag);
11099 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11100 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11102 _CrtSetBreakAlloc(-1);
11108 Catch::LeakDetector::LeakDetector() {}
11112 Catch::LeakDetector::~LeakDetector() {
11124 std::size_t listTests( Config
const&
config );
11126 std::size_t listTestsNamesOnly( Config
const& config );
11132 std::set<std::string> spellings;
11133 std::size_t
count = 0;
11136 std::size_t listTags( Config
const& config );
11138 std::size_t listReporters();
11148 using namespace clara::TextFlow;
11153 #include <algorithm> 11158 std::size_t listTests( Config
const&
config ) {
11159 TestSpec
const& testSpec = config.testSpec();
11160 if( config.hasTestFilters() )
11167 for(
auto const& testCaseInfo : matchedTestCases ) {
11168 Colour::Code colour = testCaseInfo.isHidden()
11169 ? Colour::SecondaryText
11171 Colour colourGuard( colour );
11173 Catch::cout() <<
Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11176 std::string description = testCaseInfo.description;
11177 if( description.empty() )
11178 description =
"(NO DESCRIPTION)";
11181 if( !testCaseInfo.tags.empty() )
11185 if( !config.hasTestFilters() )
11188 Catch::cout() <<
pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11189 return matchedTestCases.size();
11192 std::size_t listTestsNamesOnly( Config
const& config ) {
11193 TestSpec
const& testSpec = config.testSpec();
11194 std::size_t matchedTests = 0;
11196 for(
auto const& testCaseInfo : matchedTestCases ) {
11199 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11206 return matchedTests;
11209 void TagInfo::add(
std::string const& spelling ) {
11211 spellings.insert( spelling );
11216 for (
auto const& spelling : spellings) {
11218 size += spelling.size() + 2;
11222 for (
auto const& spelling : spellings) {
11230 std::size_t listTags( Config
const& config ) {
11231 TestSpec
const& testSpec = config.testSpec();
11232 if( config.hasTestFilters() )
11233 Catch::cout() <<
"Tags for matching test cases:\n";
11238 std::map<std::string, TagInfo> tagCounts;
11241 for(
auto const& testCase : matchedTestCases ) {
11242 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11244 auto countIt = tagCounts.find( lcaseTagName );
11245 if( countIt == tagCounts.end() )
11246 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11247 countIt->second.add( tagName );
11251 for(
auto const& tagCount : tagCounts ) {
11253 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11255 auto wrapper =
Column( tagCount.second.all() )
11256 .initialIndent( 0 )
11257 .indent(
str.size() )
11258 .
width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11262 return tagCounts.size();
11265 std::size_t listReporters() {
11268 std::size_t maxNameLen = 0;
11269 for(
auto const& factoryKvp : factories )
11270 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11272 for(
auto const& factoryKvp : factories ) {
11274 <<
Column( factoryKvp.first +
":" )
11276 .width( 5+maxNameLen )
11277 +
Column( factoryKvp.second->getDescription() )
11280 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11284 return factories.size();
11290 if( config->listTests() )
11291 listedCount = listedCount.
valueOr(0) + listTests( *config );
11292 if( config->listTestNamesOnly() )
11293 listedCount = listedCount.
valueOr(0) + listTestsNamesOnly( *config );
11294 if( config->listTags() )
11295 listedCount = listedCount.
valueOr(0) + listTags( *config );
11296 if( config->listReporters() )
11297 listedCount = listedCount.
valueOr(0) + listReporters();
11298 return listedCount;
11306 namespace Matchers {
11309 std::string MatcherUntypedBase::toString()
const {
11310 if( m_cachedToString.empty() )
11311 m_cachedToString = describe();
11312 return m_cachedToString;
11315 MatcherUntypedBase::~MatcherUntypedBase() =
default;
11320 using namespace Matchers;
11328 namespace Matchers {
11329 namespace Exception {
11331 bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11332 return ex.what() == m_message;
11335 std::string ExceptionMessageMatcher::describe()
const {
11336 return "exception message matches \"" + m_message +
"\"";
11353 bool isnan(
float f);
11354 bool isnan(
double d);
11363 template <
typename T>
11365 #if defined(CATCH_CONFIG_CPP11_TO_STRING) 11376 #include <algorithm> 11382 #include <type_traits> 11390 static_assert(
sizeof(
float) ==
sizeof(
int32_t),
"Important ULP matcher assumption violated");
11392 std::memcpy(&i, &f,
sizeof(f));
11397 static_assert(
sizeof(
double) ==
sizeof(
int64_t),
"Important ULP matcher assumption violated");
11399 std::memcpy(&i, &d,
sizeof(d));
11403 template <
typename FP>
11404 bool almostEqualUlps(FP
lhs, FP rhs, uint64_t maxUlpDiff) {
11407 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11414 if ((lc < 0) != (rc < 0)) {
11419 auto ulpDiff = std::abs(lc - rc);
11420 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11423 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11425 float nextafter(
float x,
float y) {
11426 return ::nextafterf(x, y);
11429 double nextafter(
double x,
double y) {
11430 return ::nextafter(x, y);
11433 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^ 11435 template <
typename FP>
11437 for (uint64_t
i = 0;
i < steps; ++
i) {
11438 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11439 start = Catch::nextafter(start, direction);
11441 start = std::nextafter(start, direction);
11449 bool marginComparison(
double lhs,
double rhs,
double margin) {
11450 return (lhs + margin >= rhs) && (rhs + margin >=
lhs);
11453 template <
typename FloatingPo
int>
11454 void write(std::ostream&
out, FloatingPoint
num) {
11455 out << std::scientific
11456 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11462 namespace Matchers {
11463 namespace Floating {
11465 enum class FloatingPointKind :
uint8_t {
11470 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11471 :m_target{ target }, m_margin{ margin } {
11472 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.' 11473 <<
" Margin has to be non-negative.");
11478 bool WithinAbsMatcher::match(
double const& matchee)
const {
11479 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11486 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11487 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11489 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11490 "Provided ULP is impossibly large for a float comparison.");
11493 #if defined(__clang__) 11494 #pragma clang diagnostic push 11496 #pragma clang diagnostic ignored "-Wunreachable-code" 11499 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11501 case FloatingPointKind::Float:
11502 return almostEqualUlps<float>(
static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11504 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11510 #if defined(__clang__) 11511 #pragma clang diagnostic pop 11514 std::string WithinUlpsMatcher::describe()
const {
11515 std::stringstream ret;
11517 ret <<
"is within " << m_ulps <<
" ULPs of ";
11519 if (m_type == FloatingPointKind::Float) {
11520 write(ret, static_cast<float>(m_target));
11523 write(ret, m_target);
11528 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11530 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11533 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11535 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11542 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11544 m_epsilon(epsilon){
11545 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11546 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
"); 11549 bool WithinRelMatcher::match(double const& matchee) const { 11550 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); 11551 return marginComparison(matchee, m_target, 11552 std::isinf(relMargin)? 0 : relMargin); 11555 std::string WithinRelMatcher::describe() const { 11556 Catch::ReusableStringStream sstr; 11557 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
"; 11561 }// namespace Floating 11563 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { 11564 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); 11567 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { 11568 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); 11571 Floating::WithinAbsMatcher WithinAbs(double target, double margin) { 11572 return Floating::WithinAbsMatcher(target, margin); 11575 Floating::WithinRelMatcher WithinRel(double target, double eps) { 11576 return Floating::WithinRelMatcher(target, eps); 11579 Floating::WithinRelMatcher WithinRel(double target) { 11580 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); 11583 Floating::WithinRelMatcher WithinRel(float target, float eps) { 11584 return Floating::WithinRelMatcher(target, eps); 11587 Floating::WithinRelMatcher WithinRel(float target) { 11588 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); 11591 } // namespace Matchers 11592 } // namespace Catch 11594 // end catch_matchers_floating.cpp 11595 // start catch_matchers_generic.cpp 11597 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { 11598 if (desc.empty()) { 11599 return "matches undescribed predicate
"; 11601 return "matches predicate: \
"" + desc +
'"';
11610 namespace Matchers {
11612 namespace StdString {
11615 : m_caseSensitivity( caseSensitivity ),
11616 m_str( adjustString( str ) )
11623 std::string CasedString::caseSensitivitySuffix()
const {
11625 ?
" (case insensitive)" 11629 StringMatcherBase::StringMatcherBase(
std::string const& operation, CasedString
const& comparator )
11630 : m_comparator( comparator ),
11631 m_operation( operation ) {
11634 std::string StringMatcherBase::describe()
const {
11636 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11637 m_comparator.caseSensitivitySuffix().size());
11638 description += m_operation;
11639 description +=
": \"";
11640 description += m_comparator.m_str;
11641 description +=
"\"";
11642 description += m_comparator.caseSensitivitySuffix();
11643 return description;
11646 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11649 return m_comparator.adjustString( source ) == m_comparator.m_str;
11652 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11654 bool ContainsMatcher::match(
std::string const& source )
const {
11655 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11658 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11660 bool StartsWithMatcher::match(
std::string const& source )
const {
11661 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11664 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11666 bool EndsWithMatcher::match(
std::string const& source )
const {
11667 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11672 bool RegexMatcher::match(
std::string const& matchee)
const {
11673 auto flags = std::regex::ECMAScript;
11674 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11675 flags |= std::regex::icase;
11678 return std::regex_match(matchee, reg);
11682 return "matches " +
::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)?
" case sensitively" :
" case insensitively");
11712 bool uncaught_exceptions();
11724 : macroName( _macroName ),
11725 lineInfo( _lineInfo ),
11727 sequence( ++globalCount )
11731 return sequence == other.
sequence;
11746 :m_info(macroName, lineInfo, type) {}
11751 : m_info( builder.
m_info ), m_moved()
11758 : m_info( old.m_info ), m_moved()
11760 old.m_moved =
true;
11764 if ( !uncaught_exceptions() && !m_moved ){
11770 auto trimmed = [&] (
size_t start,
size_t end) {
11771 while (names[start] ==
',' || isspace(names[start])) {
11774 while (names[end] ==
',' || isspace(names[end])) {
11777 return names.
substr(start, end - start + 1);
11779 auto skipq = [&] (
size_t start,
char quote) {
11780 for (
auto i = start + 1;
i < names.
size() ; ++
i) {
11781 if (names[
i] == quote)
11783 if (names[
i] ==
'\\')
11790 std::stack<char> openings;
11792 char c = names[pos];
11813 if (start !=
pos && openings.empty()) {
11814 m_messages.emplace_back(macroName, lineInfo, resultType);
11815 m_messages.back().message =
static_cast<std::string>(trimmed(start,
pos));
11816 m_messages.back().message +=
" := ";
11821 assert(openings.empty() &&
"Mismatched openings");
11822 m_messages.emplace_back(macroName, lineInfo, resultType);
11823 m_messages.back().message =
static_cast<std::string>(trimmed(start, names.
size() - 1));
11824 m_messages.back().message +=
" := ";
11827 if ( !uncaught_exceptions() ){
11828 assert( m_captured == m_messages.size() );
11829 for(
size_t i = 0;
i < m_captured; ++
i )
11830 m_resultCapture.popScopedMessage( m_messages[
i] );
11835 assert( index < m_messages.size() );
11836 m_messages[index].message +=
value;
11837 m_resultCapture.pushScopedMessage( m_messages[index] );
11846 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11847 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11855 class RedirectedStream {
11856 std::ostream& m_originalStream;
11857 std::ostream& m_redirectionStream;
11858 std::streambuf* m_prevBuf;
11861 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11862 ~RedirectedStream();
11865 class RedirectedStdOut {
11867 RedirectedStream m_cout;
11869 RedirectedStdOut();
11876 class RedirectedStdErr {
11878 RedirectedStream m_cerr;
11879 RedirectedStream m_clog;
11881 RedirectedStdErr();
11885 class RedirectedStreams {
11887 RedirectedStreams(RedirectedStreams
const&) =
delete;
11888 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
11889 RedirectedStreams(RedirectedStreams&&) =
delete;
11890 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
11893 ~RedirectedStreams();
11897 RedirectedStdOut m_redirectedStdOut;
11898 RedirectedStdErr m_redirectedStdErr;
11901 #if defined(CATCH_CONFIG_NEW_CAPTURE) 11909 TempFile(TempFile
const&) =
delete;
11910 TempFile& operator=(TempFile
const&) =
delete;
11911 TempFile(TempFile&&) =
delete;
11912 TempFile& operator=(TempFile&&) =
delete;
11917 std::FILE* getFile();
11921 std::FILE* m_file =
nullptr;
11922 #if defined(_MSC_VER) 11923 char m_buffer[L_tmpnam] = { 0 };
11927 class OutputRedirect {
11929 OutputRedirect(OutputRedirect
const&) =
delete;
11930 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
11931 OutputRedirect(OutputRedirect&&) =
delete;
11932 OutputRedirect& operator=(OutputRedirect&&) =
delete;
11938 int m_originalStdout = -1;
11939 int m_originalStderr = -1;
11940 TempFile m_stdoutFile;
11941 TempFile m_stderrFile;
11950 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11956 #include <stdexcept> 11958 #if defined(CATCH_CONFIG_NEW_CAPTURE) 11959 #if defined(_MSC_VER) 11963 #define fileno _fileno 11965 #include <unistd.h> 11971 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
11972 : m_originalStream( originalStream ),
11973 m_redirectionStream( redirectionStream ),
11974 m_prevBuf( m_originalStream.rdbuf() )
11976 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
11979 RedirectedStream::~RedirectedStream() {
11980 m_originalStream.rdbuf( m_prevBuf );
11983 RedirectedStdOut::RedirectedStdOut() : m_cout(
Catch::cout(), m_rss.get() ) {}
11986 RedirectedStdErr::RedirectedStdErr()
11993 : m_redirectedCout(redirectedCout),
11994 m_redirectedCerr(redirectedCerr)
11997 RedirectedStreams::~RedirectedStreams() {
11998 m_redirectedCout += m_redirectedStdOut.str();
11999 m_redirectedCerr += m_redirectedStdErr.str();
12002 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12004 #if defined(_MSC_VER) 12005 TempFile::TempFile() {
12006 if (tmpnam_s(m_buffer)) {
12009 if (fopen_s(&m_file, m_buffer,
"w")) {
12011 if (strerror_s(buffer, errno)) {
12014 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12018 TempFile::TempFile() {
12019 m_file = std::tmpfile();
12027 TempFile::~TempFile() {
12029 std::fclose(m_file);
12032 #if defined(_MSC_VER) 12033 std::remove(m_buffer);
12037 FILE* TempFile::getFile() {
12042 std::stringstream sstr;
12044 std::rewind(m_file);
12045 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12052 m_originalStdout(dup(1)),
12053 m_originalStderr(dup(2)),
12054 m_stdoutDest(stdout_dest),
12055 m_stderrDest(stderr_dest) {
12056 dup2(fileno(m_stdoutFile.getFile()), 1);
12057 dup2(fileno(m_stderrFile.getFile()), 2);
12060 OutputRedirect::~OutputRedirect() {
12069 dup2(m_originalStdout, 1);
12070 dup2(m_originalStderr, 2);
12072 m_stdoutDest += m_stdoutFile.getContents();
12073 m_stderrDest += m_stderrFile.getContents();
12076 #endif // CATCH_CONFIG_NEW_CAPTURE 12080 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12081 #if defined(_MSC_VER) 12094 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) 12095 bool isnan(
float f) {
12096 return std::isnan(f);
12098 bool isnan(
double d) {
12099 return std::isnan(d);
12103 bool isnan(
float f) {
12104 return std::_isnan(f);
12106 bool isnan(
double d) {
12107 return std::_isnan(d);
12119 #if defined(_MSC_VER) 12120 #pragma warning(push) 12121 #pragma warning(disable:4146) // we negate uint32 during the rotate 12127 return (val >> count) | (val << (-count &
mask));
12130 #if defined(_MSC_VER) 12131 #pragma warning(pop) 12150 for (uint64_t
s = 0;
s < skip; ++
s) {
12151 static_cast<void>((*this)());
12157 const uint32_t xorshifted =
static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12158 const auto output = rotate_right(xorshifted, m_state >> 59u);
12161 m_state = m_state * 6364136223846793005ULL + s_inc;
12181 #include <algorithm> 12189 std::vector<TestCase> sortTests(
IConfig const&
config, std::vector<TestCase>
const& unsortedTestCases );
12194 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12196 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
12201 virtual ~TestRegistry() =
default;
12203 virtual void registerTest(
TestCase const& testCase );
12205 std::vector<TestCase>
const& getAllTests()
const override;
12206 std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const override;
12209 std::vector<TestCase> m_functions;
12211 mutable std::vector<TestCase> m_sortedFunctions;
12212 std::size_t m_unnamedCount = 0;
12213 std::ios_base::Init m_ostreamInit;
12219 void(*m_testAsFunction)();
12221 TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept;
12223 void invoke()
const override;
12239 class ReporterRegistry :
public IReporterRegistry {
12243 ~ReporterRegistry()
override;
12250 FactoryMap
const& getFactories()
const override;
12251 Listeners
const& getListeners()
const override;
12254 FactoryMap m_factories;
12255 Listeners m_listeners;
12282 class TagAliasRegistry :
public ITagAliasRegistry {
12284 ~TagAliasRegistry()
override;
12290 std::map<std::string, TagAlias> m_registry;
12299 #include <exception> 12303 class StartupExceptionRegistry {
12305 void add(std::exception_ptr
const& exception) noexcept;
12306 std::vector<std::exception_ptr>
const& getExceptions()
const noexcept;
12308 std::vector<std::exception_ptr> m_exceptions;
12318 struct ISingleton {
12319 virtual ~ISingleton();
12322 void addSingleton( ISingleton* singleton );
12323 void cleanupSingletons();
12325 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12326 class Singleton : SingletonImplT,
public ISingleton {
12328 static auto getInternal() -> Singleton* {
12329 static Singleton* s_instance =
nullptr;
12330 if( !s_instance ) {
12331 s_instance =
new Singleton;
12332 addSingleton( s_instance );
12338 static auto get() -> InterfaceT
const& {
12339 return *getInternal();
12341 static auto getMutable() -> MutableInterfaceT& {
12342 return *getInternal();
12357 RegistryHub() =
default;
12358 IReporterRegistry
const& getReporterRegistry()
const override {
12359 return m_reporterRegistry;
12362 return m_testCaseRegistry;
12365 return m_exceptionTranslatorRegistry;
12367 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
12368 return m_tagAliasRegistry;
12370 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12371 return m_exceptionRegistry;
12376 m_reporterRegistry.registerReporter( name, factory );
12379 m_reporterRegistry.registerListener( factory );
12381 void registerTest(
TestCase const& testInfo )
override {
12382 m_testCaseRegistry.registerTest( testInfo );
12385 m_exceptionTranslatorRegistry.registerTranslator( translator );
12388 m_tagAliasRegistry.add( alias, tag, lineInfo );
12390 void registerStartupException() noexcept
override {
12391 m_exceptionRegistry.add(std::current_exception());
12394 return m_enumValuesRegistry;
12398 TestRegistry m_testCaseRegistry;
12399 ReporterRegistry m_reporterRegistry;
12400 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12401 TagAliasRegistry m_tagAliasRegistry;
12402 StartupExceptionRegistry m_exceptionRegistry;
12403 Detail::EnumValuesRegistry m_enumValuesRegistry;
12407 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12413 return RegistryHubSingleton::getMutable();
12416 cleanupSingletons();
12429 ReporterRegistry::~ReporterRegistry() =
default;
12432 auto it = m_factories.find( name );
12433 if(
it == m_factories.end() )
12435 return it->second->create( ReporterConfig( config ) );
12439 m_factories.emplace(name, factory);
12442 m_listeners.push_back( factory );
12445 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12446 return m_factories;
12448 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12449 return m_listeners;
12477 #include <algorithm> 12482 namespace Generators {
12486 GeneratorTracker( TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext&
ctx, ITracker* parent )
12487 : TrackerBase( nameAndLocation, ctx, parent )
12489 ~GeneratorTracker();
12491 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation
const& nameAndLocation ) {
12492 std::shared_ptr<GeneratorTracker>
tracker;
12494 ITracker& currentTracker = ctx.currentTracker();
12495 if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12497 assert( childTracker->isGeneratorTracker() );
12498 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12501 tracker = std::make_shared<GeneratorTracker>( nameAndLocation,
ctx, ¤tTracker );
12502 currentTracker.addChild( tracker );
12505 if( !ctx.completedCycle() && !tracker->isComplete() ) {
12513 bool isGeneratorTracker()
const override {
return true; }
12514 auto hasGenerator()
const ->
bool override {
12515 return !!m_generator;
12517 void close()
override {
12518 TrackerBase::close();
12520 if (m_runState == CompletedSuccessfully && m_generator->next()) {
12521 m_children.clear();
12522 m_runState = Executing;
12528 return m_generator;
12534 GeneratorTracker::~GeneratorTracker() {}
12537 RunContext::RunContext(
IConfigPtr const&
_config, IStreamingReporterPtr&& reporter)
12538 : m_runInfo(_config->name()),
12543 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12545 m_context.setRunner(
this);
12546 m_context.setConfig(m_config);
12547 m_context.setResultCapture(
this);
12548 m_reporter->testRunStarting(m_runInfo);
12551 RunContext::~RunContext() {
12552 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12555 void RunContext::testGroupStarting(
std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12556 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12559 void RunContext::testGroupEnded(
std::string const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12560 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12564 Totals prevTotals = m_totals;
12571 m_reporter->testCaseStarting(testInfo);
12573 m_activeTestCase = &testCase;
12575 ITracker& rootTracker = m_trackerContext.startRun();
12576 assert(rootTracker.isSectionTracker());
12577 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12579 m_trackerContext.startCycle();
12580 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12581 runCurrentTest(redirectedCout, redirectedCerr);
12582 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12590 m_totals.testCases += deltaTotals.
testCases;
12591 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12597 m_activeTestCase =
nullptr;
12598 m_testCaseTracker =
nullptr;
12600 return deltaTotals;
12607 IStreamingReporter& RunContext::reporter()
const {
12608 return *m_reporter;
12611 void RunContext::assertionEnded(AssertionResult
const &
result) {
12613 m_totals.assertions.passed++;
12614 m_lastAssertionPassed =
true;
12615 }
else if (!result.isOk()) {
12616 m_lastAssertionPassed =
false;
12617 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12618 m_totals.assertions.failedButOk++;
12620 m_totals.assertions.failed++;
12623 m_lastAssertionPassed =
true;
12628 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12631 m_messageScopes.clear();
12634 resetAssertionInfo();
12637 void RunContext::resetAssertionInfo() {
12638 m_lastAssertionInfo.macroName =
StringRef();
12639 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12642 bool RunContext::sectionStarted(
SectionInfo const & sectionInfo,
Counts & assertions) {
12643 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.
name, sectionInfo.
lineInfo));
12644 if (!sectionTracker.isOpen())
12646 m_activeSections.push_back(§ionTracker);
12648 m_lastAssertionInfo.lineInfo = sectionInfo.
lineInfo;
12650 m_reporter->sectionStarting(sectionInfo);
12652 assertions = m_totals.assertions;
12657 using namespace Generators;
12658 GeneratorTracker&
tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation(
"generator", lineInfo ) );
12659 assert( tracker.isOpen() );
12660 m_lastAssertionInfo.lineInfo = lineInfo;
12664 bool RunContext::testForMissingAssertions(
Counts& assertions) {
12665 if (assertions.
total() != 0)
12667 if (!m_config->warnAboutMissingAssertions())
12669 if (m_trackerContext.currentTracker().hasChildren())
12671 m_totals.assertions.failed++;
12678 bool missingAssertions = testForMissingAssertions(assertions);
12680 if (!m_activeSections.empty()) {
12681 m_activeSections.back()->close();
12682 m_activeSections.pop_back();
12686 m_messages.clear();
12687 m_messageScopes.clear();
12690 void RunContext::sectionEndedEarly(
SectionEndInfo const & endInfo) {
12691 if (m_unfinishedSections.empty())
12692 m_activeSections.back()->fail();
12694 m_activeSections.back()->close();
12695 m_activeSections.pop_back();
12697 m_unfinishedSections.push_back(endInfo);
12700 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 12702 m_reporter->benchmarkPreparing(name);
12704 void RunContext::benchmarkStarting( BenchmarkInfo
const&
info ) {
12705 m_reporter->benchmarkStarting( info );
12707 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12708 m_reporter->benchmarkEnded( stats );
12711 m_reporter->benchmarkFailed(error);
12713 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 12716 m_messages.push_back(message);
12719 void RunContext::popScopedMessage(
MessageInfo const & message) {
12720 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(),
message), m_messages.end());
12723 void RunContext::emplaceUnscopedMessage(
MessageBuilder const& builder ) {
12724 m_messageScopes.emplace_back( builder );
12727 std::string RunContext::getCurrentTestName()
const {
12728 return m_activeTestCase
12729 ? m_activeTestCase->getTestCaseInfo().name
12733 const AssertionResult * RunContext::getLastResult()
const {
12734 return &(*m_lastResult);
12737 void RunContext::exceptionEarlyReported() {
12738 m_shouldReportUnexpected =
false;
12741 void RunContext::handleFatalErrorCondition(
StringRef message ) {
12743 m_reporter->fatalErrorEncountered(message);
12749 AssertionResult
result(m_lastAssertionInfo, tempResult);
12751 assertionEnded(result);
12753 handleUnfinishedSections();
12756 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12757 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12761 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12762 m_reporter->sectionEnded(testCaseSectionStats);
12764 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12769 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12774 m_totals.testCases.failed++;
12776 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12779 bool RunContext::lastAssertionPassed() {
12780 return m_lastAssertionPassed;
12783 void RunContext::assertionPassed() {
12784 m_lastAssertionPassed =
true;
12785 ++m_totals.assertions.passed;
12786 resetAssertionInfo();
12787 m_messageScopes.clear();
12790 bool RunContext::aborting()
const {
12791 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12795 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12796 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12797 m_reporter->sectionStarting(testCaseSection);
12798 Counts prevAssertions = m_totals.assertions;
12799 double duration = 0;
12800 m_shouldReportUnexpected =
true;
12803 seedRng(*m_config);
12807 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12808 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 12809 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12812 invokeActiveTestCase();
12814 OutputRedirect
r(redirectedCout, redirectedCerr);
12816 invokeActiveTestCase();
12820 invokeActiveTestCase();
12828 if( m_shouldReportUnexpected ) {
12833 Counts assertions = m_totals.assertions - prevAssertions;
12834 bool missingAssertions = testForMissingAssertions(assertions);
12836 m_testCaseTracker->close();
12837 handleUnfinishedSections();
12838 m_messages.clear();
12839 m_messageScopes.clear();
12841 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
12842 m_reporter->sectionEnded(testCaseSectionStats);
12845 void RunContext::invokeActiveTestCase() {
12846 FatalConditionHandler fatalConditionHandler;
12847 m_activeTestCase->invoke();
12848 fatalConditionHandler.reset();
12851 void RunContext::handleUnfinishedSections() {
12854 for (
auto it = m_unfinishedSections.rbegin(),
12855 itEnd = m_unfinishedSections.rend();
12859 m_unfinishedSections.clear();
12862 void RunContext::handleExpr(
12867 m_reporter->assertionStarting( info );
12870 bool result = expr.
getResult() != negated;
12873 if (!m_includeSuccessfulResults) {
12882 populateReaction( reaction );
12885 void RunContext::reportExpr(
12891 m_lastAssertionInfo =
info;
12894 AssertionResult assertionResult{
info, data };
12895 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
12897 assertionEnded( assertionResult );
12900 void RunContext::handleMessage(
12906 m_reporter->assertionStarting( info );
12908 m_lastAssertionInfo =
info;
12912 AssertionResult assertionResult{ m_lastAssertionInfo, data };
12913 assertionEnded( assertionResult );
12914 if( !assertionResult.isOk() )
12915 populateReaction( reaction );
12917 void RunContext::handleUnexpectedExceptionNotThrown(
12924 void RunContext::handleUnexpectedInflightException(
12929 m_lastAssertionInfo =
info;
12933 AssertionResult assertionResult{
info, data };
12934 assertionEnded( assertionResult );
12935 populateReaction( reaction );
12943 void RunContext::handleIncomplete(
12946 m_lastAssertionInfo =
info;
12949 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
12950 AssertionResult assertionResult{
info, data };
12951 assertionEnded( assertionResult );
12953 void RunContext::handleNonExpr(
12958 m_lastAssertionInfo =
info;
12961 AssertionResult assertionResult{
info, data };
12962 assertionEnded( assertionResult );
12964 if( !assertionResult.isOk() )
12965 populateReaction( reaction );
12977 std::srand(config.
rngSeed());
12994 m_sectionIncluded(
getResultCapture().sectionStarted( m_info, m_assertions ) )
13000 if( m_sectionIncluded ) {
13001 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13002 if( uncaught_exceptions() )
13010 Section::operator bool()
const {
13011 return m_sectionIncluded;
13024 lineInfo( _lineInfo )
13041 ~Session()
override;
13043 void showHelp()
const;
13044 void libIdentify();
13046 int applyCommandLine(
int argc,
char const *
const * argv );
13047 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13048 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13051 void useConfigData( ConfigData
const& configData );
13053 template<
typename CharT>
13054 int run(
int argc, CharT
const *
const argv[]) {
13055 if (m_startupExceptions)
13057 int returnCode = applyCommandLine(argc, argv);
13058 if (returnCode == 0)
13059 returnCode =
run();
13065 clara::Parser
const& cli()
const;
13066 void cli( clara::Parser
const& newParser );
13067 ConfigData& configData();
13072 clara::Parser m_cli;
13073 ConfigData m_configData;
13074 std::shared_ptr<Config> m_config;
13075 bool m_startupExceptions =
false;
13089 Version( Version
const& ) =
delete;
13090 Version& operator=( Version
const& ) =
delete;
13091 Version(
unsigned int _majorVersion,
13092 unsigned int _minorVersion,
13093 unsigned int _patchNumber,
13094 char const *
const _branchName,
13095 unsigned int _buildNumber );
13097 unsigned int const majorVersion;
13098 unsigned int const minorVersion;
13099 unsigned int const patchNumber;
13102 char const *
const branchName;
13103 unsigned int const buildNumber;
13105 friend std::ostream&
operator << ( std::ostream& os, Version
const& version );
13108 Version
const& libraryVersion();
13115 #include <iterator> 13120 const int MaxExitCode = 255;
13124 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13129 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13131 return createReporter(config->getReporterName(),
config);
13139 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13140 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13142 for (
auto const& listener : listeners) {
13143 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13145 multi.addReporter(createReporter(config->getReporterName(),
config));
13151 explicit TestGroup(std::shared_ptr<Config>
const& config)
13153 , m_context{
config, makeReporter(config)}
13156 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13157 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13159 if (m_matches.empty() && invalidArgs.empty()) {
13160 for (
auto const&
test : allTestCases)
13161 if (!
test.isHidden())
13162 m_tests.emplace(&
test);
13164 for (
auto const& match : m_matches)
13165 m_tests.insert(match.tests.begin(), match.tests.end());
13170 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13172 m_context.testGroupStarting(m_config->name(), 1, 1);
13173 for (
auto const& testCase : m_tests) {
13174 if (!m_context.aborting())
13175 totals += m_context.runTest(*testCase);
13177 m_context.reporter().skipTest(*testCase);
13180 for (
auto const& match : m_matches) {
13181 if (match.tests.empty()) {
13182 m_context.reporter().noMatchingTestCases(match.name);
13187 if (!invalidArgs.empty()) {
13188 for (
auto const& invalidArg: invalidArgs)
13189 m_context.reporter().reportInvalidArguments(invalidArg);
13192 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13197 using Tests = std::set<TestCase const*>;
13199 std::shared_ptr<Config> m_config;
13200 RunContext m_context;
13207 for (
auto& testCase :
tests) {
13208 auto tags = testCase.tags;
13211 auto lastSlash = filename.find_last_of(
"\\/");
13212 if (lastSlash != std::string::npos) {
13213 filename.erase(0, lastSlash);
13217 auto lastDot = filename.find_last_of(
'.');
13218 if (lastDot != std::string::npos) {
13219 filename.erase(lastDot);
13223 setTags(testCase,
tags);
13229 Session::Session() {
13230 static bool alreadyInstantiated =
false;
13231 if( alreadyInstantiated ) {
13237 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13239 if ( !exceptions.empty() ) {
13243 m_startupExceptions =
true;
13244 Colour colourGuard( Colour::Red );
13245 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13247 for (
const auto& ex_ptr : exceptions ) {
13249 std::rethrow_exception(ex_ptr);
13250 }
catch ( std::exception
const& ex ) {
13257 alreadyInstantiated =
true;
13258 m_cli = makeCommandLineParser( m_configData );
13260 Session::~Session() {
13264 void Session::showHelp()
const {
13266 <<
"\nCatch v" << libraryVersion() <<
"\n" 13267 << m_cli << std::endl
13268 <<
"For more detailed usage please see the project docs\n" << std::endl;
13270 void Session::libIdentify() {
13272 <<
std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n" 13273 <<
std::left << std::setw(16) <<
"category: " <<
"testframework\n" 13274 <<
std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n" 13275 <<
std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13278 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13279 if( m_startupExceptions )
13282 auto result = m_cli.parse( clara::Args( argc, argv ) );
13287 << Colour( Colour::Red )
13288 <<
"\nError(s) in input:\n" 13291 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13292 return MaxExitCode;
13295 if( m_configData.showHelp )
13297 if( m_configData.libIdentify )
13303 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13304 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13306 char **utf8Argv =
new char *[ argc ];
13308 for (
int i = 0;
i < argc; ++
i ) {
13309 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[
i], -1,
nullptr, 0,
nullptr,
nullptr );
13311 utf8Argv[ i ] =
new char[ bufSize ];
13313 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13316 int returnCode = applyCommandLine( argc, utf8Argv );
13318 for (
int i = 0;
i < argc; ++
i )
13319 delete [] utf8Argv[
i ];
13321 delete [] utf8Argv;
13327 void Session::useConfigData( ConfigData
const& configData ) {
13328 m_configData = configData;
13334 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13335 static_cast<void>(std::getchar());
13337 int exitCode = runInternal();
13339 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13340 static_cast<void>(std::getchar());
13345 clara::Parser
const& Session::cli()
const {
13348 void Session::cli( clara::Parser
const& newParser ) {
13351 ConfigData& Session::configData() {
13352 return m_configData;
13356 m_config = std::make_shared<Config>( m_configData );
13360 int Session::runInternal() {
13361 if( m_startupExceptions )
13364 if (m_configData.showHelp || m_configData.libIdentify) {
13371 seedRng( *m_config );
13373 if( m_configData.filenamesAsTags )
13374 applyFilenamesAsTags( *m_config );
13378 return static_cast<int>( *listed );
13380 TestGroup
tests { m_config };
13381 auto const totals =
tests.execute();
13383 if( m_config->warnAboutNoTests() && totals.error == -1 )
13389 return (
std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13391 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13392 catch( std::exception& ex ) {
13394 return MaxExitCode;
13408 static auto getSingletons() -> std::vector<ISingleton*>*& {
13409 static std::vector<ISingleton*>* g_singletons =
nullptr;
13410 if( !g_singletons )
13411 g_singletons =
new std::vector<ISingleton*>();
13412 return g_singletons;
13416 ISingleton::~ISingleton() {}
13418 void addSingleton(ISingleton* singleton ) {
13419 getSingletons()->push_back( singleton );
13421 void cleanupSingletons() {
13422 auto& singletons = getSingletons();
13423 for(
auto singleton : *singletons )
13426 singletons =
nullptr;
13434 void StartupExceptionRegistry::add( std::exception_ptr
const& exception ) noexcept {
13436 m_exceptions.push_back(exception);
13443 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions()
const noexcept {
13444 return m_exceptions;
13452 #include <iostream> 13462 namespace Detail {
namespace {
13463 template<
typename WriterF, std::
size_t bufferSize=256>
13464 class StreamBufImpl :
public std::streambuf {
13465 char data[bufferSize];
13470 setp( data, data +
sizeof(data) );
13473 ~StreamBufImpl() noexcept {
13478 int overflow(
int c )
override {
13482 if( pbase() == epptr() )
13483 m_writer(
std::string( 1, static_cast<char>( c ) ) );
13485 sputc( static_cast<char>( c ) );
13490 int sync()
override {
13491 if( pbase() != pptr() ) {
13492 m_writer(
std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13493 setp( pbase(), epptr() );
13501 struct OutputDebugWriter {
13504 writeToDebugConsole( str );
13510 class FileStream :
public IStream {
13511 mutable std::ofstream m_ofs;
13514 m_ofs.open( filename.
c_str() );
13515 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13517 ~FileStream()
override =
default;
13519 std::ostream&
stream()
const override {
13526 class CoutStream :
public IStream {
13527 mutable std::ostream m_os;
13532 ~CoutStream()
override =
default;
13535 std::ostream&
stream()
const override {
return m_os; }
13540 class DebugOutStream :
public IStream {
13541 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13542 mutable std::ostream m_os;
13545 : m_streamBuf(
new StreamBufImpl<OutputDebugWriter>() ),
13546 m_os( m_streamBuf.get() )
13549 ~DebugOutStream()
override =
default;
13552 std::ostream&
stream()
const override {
return m_os; }
13560 if( filename.
empty() )
13561 return new Detail::CoutStream();
13562 else if( filename[0] ==
'%' ) {
13563 if( filename ==
"%debug" )
13564 return new Detail::DebugOutStream();
13566 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13569 return new Detail::FileStream( filename );
13573 struct StringStreams {
13574 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13575 std::vector<std::size_t> m_unused;
13576 std::ostringstream m_referenceStream;
13578 auto add() -> std::size_t {
13579 if( m_unused.empty() ) {
13580 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13581 return m_streams.size()-1;
13584 auto index = m_unused.back();
13585 m_unused.pop_back();
13590 void release( std::size_t
index ) {
13591 m_streams[index]->copyfmt( m_referenceStream );
13592 m_unused.push_back(index);
13597 : m_index( Singleton<StringStreams>::getMutable().add() ),
13598 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].
get() )
13602 static_cast<std::ostringstream*
>( m_oss )->
str(
"");
13604 Singleton<StringStreams>::getMutable().release( m_index );
13608 return static_cast<std::ostringstream*
>( m_oss )->
str();
13613 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions 13622 #include <algorithm> 13631 char toLowerCh(
char c) {
13632 return static_cast<char>( std::tolower( c ) );
13637 return s.size() >= prefix.size() &&
std::equal(prefix.begin(), prefix.end(), s.begin());
13640 return !s.empty() && s[0] == prefix;
13643 return s.size() >= suffix.size() &&
std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13646 return !s.empty() && s[s.size()-1] == suffix;
13649 return s.find( infix ) != std::string::npos;
13660 static char const* whitespaceChars =
"\n\r\t ";
13661 std::string::size_type
start = str.find_first_not_of( whitespaceChars );
13662 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13664 return start != std::string::npos ? str.substr( start, 1+end-start ) :
std::string();
13668 const auto is_ws = [](
char c) {
13669 return c ==
' ' ||
c ==
'\t' ||
c ==
'\n' ||
c ==
'\r';
13671 size_t real_begin = 0;
13672 while (real_begin < ref.
size() && is_ws(ref[real_begin])) { ++real_begin; }
13673 size_t real_end = ref.
size();
13674 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13676 return ref.
substr(real_begin, real_end - real_begin);
13680 bool replaced =
false;
13681 std::size_t
i = str.find( replaceThis );
13682 while( i != std::string::npos ) {
13684 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13685 if( i < str.size()-withThis.size() )
13686 i = str.find( replaceThis, i+withThis.size() );
13688 i = std::string::npos;
13694 std::vector<StringRef> subStrings;
13695 std::size_t
start = 0;
13697 if( str[
pos] == delimiter ) {
13698 if(
pos - start > 1 )
13699 subStrings.push_back( str.
substr( start,
pos-start ) );
13703 if( start < str.
size() )
13709 : m_count( count ),
13715 if( pluraliser.
m_count != 1 )
13724 #include <algorithm> 13731 :
StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13735 CATCH_ENFORCE(isNullTerminated(),
"Called StringRef::c_str() on a non-null-terminated instance");
13743 if (start < m_size) {
13750 return m_size == other.
m_size 13751 && (std::memcmp( m_start, other.
m_start, m_size ) == 0);
13755 return os.write(str.
data(), str.
size());
13759 lhs.append(rhs.
data(), rhs.
size());
13792 TagAliasRegistry::~TagAliasRegistry() {}
13795 auto it = m_registry.find( alias );
13796 if(
it != m_registry.end() )
13797 return &(
it->second);
13803 std::string expandedTestSpec = unexpandedTestSpec;
13804 for(
auto const& registryKvp : m_registry ) {
13805 std::size_t
pos = expandedTestSpec.find( registryKvp.first );
13806 if( pos != std::string::npos ) {
13807 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13808 registryKvp.second.tag +
13809 expandedTestSpec.substr( pos + registryKvp.first.size() );
13812 return expandedTestSpec;
13817 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
13819 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13820 "error: tag alias, '" << alias <<
"' already registered.\n" 13821 <<
"\tFirst seen at: " <<
find(alias)->lineInfo <<
"\n" 13822 <<
"\tRedefined at: " << lineInfo );
13825 ITagAliasRegistry::~ITagAliasRegistry() {}
13836 #include <exception> 13837 #include <algorithm> 13847 else if( tag ==
"!throws" )
13849 else if( tag ==
"!shouldfail" )
13851 else if( tag ==
"!mayfail" )
13853 else if( tag ==
"!nonportable" )
13855 else if( tag ==
"!benchmark" )
13861 return parseSpecialTag( tag ) ==
TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
13865 "Tag name: [" << tag <<
"] is not allowed.\n" 13866 <<
"Tag names starting with non alphanumeric characters are reserved\n" 13876 bool isHidden =
false;
13879 std::vector<std::string>
tags;
13881 bool inTag =
false;
13882 for (
char c : nameAndTags.
tags) {
13895 enforceNotReservedTag( tag, _lineInfo );
13900 if (
startsWith(tag,
'.') && tag.size() > 1) {
13903 tags.push_back( tag );
13913 tags.insert( tags.end(), {
".",
"!hide" } );
13916 TestCaseInfo info( static_cast<std::string>(nameAndTags.
name), _className, desc, tags, _lineInfo );
13920 void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string>
tags ) {
13922 tags.erase(std::unique(
begin(tags),
end(tags)),
end(tags));
13925 for(
auto const&
tag : tags ) {
13928 testCaseInfo.
lcaseTags.push_back( lcaseTag );
13936 std::vector<std::string>
const&
_tags,
13939 className( _className ),
13940 description( _description ),
13941 lineInfo( _lineInfo ),
13944 setTags( *
this, _tags );
13948 return ( properties & IsHidden ) != 0;
13951 return ( properties & Throws ) != 0;
13954 return ( properties & (ShouldFail | MayFail ) ) != 0;
13957 return ( properties & (ShouldFail ) ) != 0;
13963 std::size_t full_size = 2 * tags.size();
13964 for (
const auto&
tag : tags) {
13965 full_size +=
tag.size();
13967 ret.reserve(full_size);
13968 for (
const auto&
tag : tags) {
13969 ret.push_back(
'[');
13971 ret.push_back(
']');
13981 other.
name = _newName;
13990 return test.get() == other.
test.get() &&
14008 #include <algorithm> 14014 struct TestHasher {
14023 uint64_t operator()(
TestCase const&
t)
const {
14025 static constexpr uint64_t prime = 1099511628211;
14026 uint64_t hash = basis;
14027 for (
const char c : t.
name) {
14036 std::vector<TestCase> sortTests(
IConfig const&
config, std::vector<TestCase>
const& unsortedTestCases ) {
14043 std::vector<TestCase> sorted = unsortedTestCases;
14044 std::sort( sorted.begin(), sorted.end() );
14050 TestHasher
h(
rng() );
14052 using hashedTest = std::pair<uint64_t, TestCase const*>;
14053 std::vector<hashedTest> indexed_tests;
14054 indexed_tests.reserve( unsortedTestCases.size() );
14056 for (
auto const& testCase : unsortedTestCases) {
14057 indexed_tests.emplace_back(
h(testCase), &testCase);
14060 std::sort(indexed_tests.begin(), indexed_tests.end(),
14061 [](hashedTest
const&
lhs, hashedTest
const& rhs) {
14062 if (lhs.first == rhs.first) {
14063 return lhs.second->name < rhs.second->name;
14065 return lhs.first < rhs.first;
14068 std::vector<TestCase> sorted;
14069 sorted.reserve( indexed_tests.size() );
14071 for (
auto const& hashed : indexed_tests) {
14072 sorted.emplace_back(*hashed.second);
14078 return unsortedTestCases;
14086 return testSpec.matches( testCase ) &&
isThrowSafe( testCase, config );
14089 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14090 std::set<TestCase> seenFunctions;
14091 for(
auto const&
function : functions ) {
14092 auto prev = seenFunctions.insert(
function );
14094 "error: TEST_CASE( \"" <<
function.name <<
"\" ) already defined.\n" 14095 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n" 14096 <<
"\tRedefined at " <<
function.getTestCaseInfo().lineInfo );
14100 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config ) {
14101 std::vector<TestCase> filtered;
14102 filtered.reserve( testCases.size() );
14103 for (
auto const& testCase : testCases) {
14104 if ((!testSpec.hasFilters() && !testCase.
isHidden()) ||
14105 (testSpec.hasFilters() &&
matchTest(testCase, testSpec, config))) {
14106 filtered.push_back(testCase);
14115 void TestRegistry::registerTest(
TestCase const& testCase ) {
14117 if( name.empty() ) {
14119 rss <<
"Anonymous test case " << ++m_unnamedCount;
14120 return registerTest( testCase.
withName( rss.
str() ) );
14122 m_functions.push_back( testCase );
14125 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14126 return m_functions;
14128 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted(
IConfig const& config )
const {
14129 if( m_sortedFunctions.empty() )
14130 enforceNoDuplicateTestCases( m_functions );
14132 if( m_currentSortOrder != config.
runOrder() || m_sortedFunctions.empty() ) {
14133 m_sortedFunctions = sortTests( config, m_functions );
14134 m_currentSortOrder = config.
runOrder();
14136 return m_sortedFunctions;
14140 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14142 void TestInvokerAsFunction::invoke()
const {
14143 m_testAsFunction();
14147 std::string className(classOrQualifiedMethodName);
14150 std::size_t lastColons = className.rfind(
"::" );
14151 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14152 if( penultimateColons == std::string::npos )
14153 penultimateColons = 1;
14154 className = className.substr( penultimateColons, lastColons-penultimateColons );
14163 #include <algorithm> 14165 #include <stdexcept> 14169 #if defined(__clang__) 14170 # pragma clang diagnostic push 14171 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14175 namespace TestCaseTracking {
14182 ITracker::~ITracker() =
default;
14184 ITracker& TrackerContext::startRun() {
14185 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}",
CATCH_INTERNAL_LINEINFO ), *
this, nullptr );
14186 m_currentTracker =
nullptr;
14187 m_runState = Executing;
14188 return *m_rootTracker;
14191 void TrackerContext::endRun() {
14192 m_rootTracker.reset();
14193 m_currentTracker =
nullptr;
14194 m_runState = NotStarted;
14197 void TrackerContext::startCycle() {
14198 m_currentTracker = m_rootTracker.get();
14199 m_runState = Executing;
14201 void TrackerContext::completeCycle() {
14202 m_runState = CompletedCycle;
14205 bool TrackerContext::completedCycle()
const {
14206 return m_runState == CompletedCycle;
14208 ITracker& TrackerContext::currentTracker() {
14209 return *m_currentTracker;
14211 void TrackerContext::setCurrentTracker( ITracker*
tracker ) {
14212 m_currentTracker = tracker;
14215 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext&
ctx, ITracker* parent )
14216 : m_nameAndLocation( nameAndLocation ),
14221 NameAndLocation
const& TrackerBase::nameAndLocation()
const {
14222 return m_nameAndLocation;
14224 bool TrackerBase::isComplete()
const {
14225 return m_runState == CompletedSuccessfully || m_runState == Failed;
14227 bool TrackerBase::isSuccessfullyCompleted()
const {
14228 return m_runState == CompletedSuccessfully;
14231 return m_runState != NotStarted && !isComplete();
14233 bool TrackerBase::hasChildren()
const {
14234 return !m_children.empty();
14237 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14238 m_children.push_back( child );
14241 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14242 auto it = std::find_if( m_children.begin(), m_children.end(),
14243 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14245 tracker->nameAndLocation().location == nameAndLocation.location &&
14246 tracker->nameAndLocation().name == nameAndLocation.name;
14248 return(
it != m_children.end() )
14252 ITracker& TrackerBase::parent() {
14257 void TrackerBase::openChild() {
14258 if( m_runState != ExecutingChildren ) {
14259 m_runState = ExecutingChildren;
14261 m_parent->openChild();
14265 bool TrackerBase::isSectionTracker()
const {
return false; }
14266 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14268 void TrackerBase::open() {
14269 m_runState = Executing;
14272 m_parent->openChild();
14275 void TrackerBase::close() {
14278 while( &m_ctx.currentTracker() != this )
14279 m_ctx.currentTracker().close();
14281 switch( m_runState ) {
14282 case NeedsAnotherRun:
14286 m_runState = CompletedSuccessfully;
14288 case ExecutingChildren:
14289 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const&
t){
return t->isComplete(); }) )
14290 m_runState = CompletedSuccessfully;
14294 case CompletedSuccessfully:
14302 m_ctx.completeCycle();
14305 m_runState = Failed;
14307 m_parent->markAsNeedingAnotherRun();
14309 m_ctx.completeCycle();
14311 void TrackerBase::markAsNeedingAnotherRun() {
14312 m_runState = NeedsAnotherRun;
14317 m_ctx.setCurrentTracker( m_parent );
14319 void TrackerBase::moveToThis() {
14320 m_ctx.setCurrentTracker(
this );
14323 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14324 : TrackerBase( nameAndLocation, ctx, parent ),
14325 m_trimmed_name(
trim(nameAndLocation.name))
14328 while( !parent->isSectionTracker() )
14329 parent = &parent->parent();
14331 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14332 addNextFilters( parentSection.m_filters );
14336 bool SectionTracker::isComplete()
const {
14337 bool complete =
true;
14339 if ((m_filters.empty() || m_filters[0] ==
"")
14340 ||
std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14341 complete = TrackerBase::isComplete();
14346 bool SectionTracker::isSectionTracker()
const {
return true; }
14348 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14349 std::shared_ptr<SectionTracker>
section;
14351 ITracker& currentTracker = ctx.currentTracker();
14352 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14354 assert( childTracker->isSectionTracker() );
14355 section = std::static_pointer_cast<SectionTracker>( childTracker );
14358 section = std::make_shared<SectionTracker>( nameAndLocation,
ctx, ¤tTracker );
14359 currentTracker.addChild( section );
14361 if( !ctx.completedCycle() )
14362 section->tryOpen();
14366 void SectionTracker::tryOpen() {
14367 if( !isComplete() )
14371 void SectionTracker::addInitialFilters( std::vector<std::string>
const&
filters ) {
14372 if( !filters.empty() ) {
14373 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14374 m_filters.emplace_back(
"");
14375 m_filters.emplace_back(
"");
14376 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14379 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14380 if( filters.size() > 1 )
14381 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14386 using TestCaseTracking::ITracker;
14387 using TestCaseTracking::TrackerContext;
14388 using TestCaseTracking::SectionTracker;
14392 #if defined(__clang__) 14393 # pragma clang diagnostic pop 14401 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14412 extractClassName( classOrMethod ),
14426 #include <algorithm> 14437 TestSpec::Pattern::~Pattern() =
default;
14449 return m_wildcardPattern.matches( testCase.
name );
14463 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14464 :
Pattern( underlyingPattern->name() )
14465 , m_underlyingPattern( underlyingPattern )
14469 return !m_underlyingPattern->matches( testCase );
14473 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const&
p ){
return p->matches( testCase ); } );
14478 for(
auto const&
p : m_patterns )
14483 bool TestSpec::hasFilters()
const {
14484 return !m_filters.empty();
14488 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const&
f ){
return f.matches( testCase ); } );
14495 std::vector<TestCase const*> currentMatches;
14496 for(
auto const&
test : testCases )
14498 currentMatches.emplace_back( &
test );
14499 return FilterMatch{
filter.name(), currentMatches };
14504 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14505 return (m_invalidArgs);
14514 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14518 m_exclusion =
false;
14519 m_arg = m_tagAliases->expandAliases( arg );
14520 m_escapeChars.clear();
14521 m_substring.reserve(m_arg.size());
14522 m_patternName.reserve(m_arg.size());
14523 m_realPatternPos = 0;
14525 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14527 if( !visitChar( m_arg[m_pos] ) ){
14528 m_testSpec.m_invalidArgs.push_back(arg);
14534 TestSpec TestSpecParser::testSpec() {
14538 bool TestSpecParser::visitChar(
char c ) {
14539 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14541 addCharToPattern(c);
14543 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14549 if( processNoneChar( c ) )
14553 processNameChar( c );
14557 addCharToPattern(c);
14562 if( processOtherChar( c ) )
14568 if( !isControlChar( c ) ) {
14569 m_patternName +=
c;
14570 m_realPatternPos++;
14576 bool TestSpecParser::processNoneChar(
char c ) {
14581 m_exclusion =
true;
14584 startNewMode( Tag );
14587 startNewMode( QuotedName );
14590 startNewMode( Name );
14594 void TestSpecParser::processNameChar(
char c ) {
14596 if( m_substring ==
"exclude:" )
14597 m_exclusion =
true;
14600 startNewMode( Tag );
14603 bool TestSpecParser::processOtherChar(
char c ) {
14604 if( !isControlChar( c ) )
14610 void TestSpecParser::startNewMode(
Mode mode ) {
14613 void TestSpecParser::endMode() {
14617 return addNamePattern();
14619 return addTagPattern();
14621 revertBackToLastMode();
14625 return startNewMode( None );
14628 void TestSpecParser::escape() {
14630 m_mode = EscapedName;
14631 m_escapeChars.push_back(m_realPatternPos);
14633 bool TestSpecParser::isControlChar(
char c )
const {
14646 return c ==
'[' || c ==
']';
14650 void TestSpecParser::addFilter() {
14651 if( !m_currentFilter.m_patterns.empty() ) {
14652 m_testSpec.m_filters.push_back( m_currentFilter );
14653 m_currentFilter = TestSpec::Filter();
14657 void TestSpecParser::saveLastMode() {
14661 void TestSpecParser::revertBackToLastMode() {
14665 bool TestSpecParser::separate() {
14666 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14669 m_pos = m_arg.size();
14670 m_substring.clear();
14671 m_patternName.clear();
14672 m_realPatternPos = 0;
14680 std::string TestSpecParser::preprocessPattern() {
14682 for (std::size_t
i = 0;
i < m_escapeChars.size(); ++
i)
14683 token = token.substr(0, m_escapeChars[
i] -
i) + token.substr(m_escapeChars[
i] -
i + 1);
14684 m_escapeChars.clear();
14686 m_exclusion =
true;
14687 token = token.substr(8);
14690 m_patternName.clear();
14691 m_realPatternPos = 0;
14696 void TestSpecParser::addNamePattern() {
14697 auto token = preprocessPattern();
14699 if (!token.empty()) {
14700 TestSpec::PatternPtr
pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14702 pattern = std::make_shared<TestSpec::ExcludedPattern>(
pattern);
14703 m_currentFilter.m_patterns.push_back(pattern);
14705 m_substring.clear();
14706 m_exclusion =
false;
14710 void TestSpecParser::addTagPattern() {
14711 auto token = preprocessPattern();
14713 if (!token.empty()) {
14716 if (token.size() > 1 && token[0] ==
'.') {
14717 token.erase(token.begin());
14718 TestSpec::PatternPtr
pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14720 pattern = std::make_shared<TestSpec::ExcludedPattern>(
pattern);
14722 m_currentFilter.m_patterns.push_back(pattern);
14725 TestSpec::PatternPtr
pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14728 pattern = std::make_shared<TestSpec::ExcludedPattern>(
pattern);
14730 m_currentFilter.m_patterns.push_back(pattern);
14732 m_substring.clear();
14733 m_exclusion =
false;
14737 TestSpec parseTestSpec(
std::string const& arg ) {
14747 static const uint64_t nanosecondsInSecond = 1000000000;
14756 auto estimateClockResolution() -> uint64_t {
14768 }
while( ticks == baseTicks );
14770 auto delta = ticks - baseTicks;
14776 if (ticks > startTime + 3 * nanosecondsInSecond) {
14777 return sum / (
i + 1u );
14787 static auto s_resolution = estimateClockResolution();
14788 return s_resolution;
14798 return getElapsedNanoseconds()/1000;
14801 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14804 return getElapsedMicroseconds()/1000000.0;
14811 #if defined(__clang__) 14812 # pragma clang diagnostic push 14813 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14814 # pragma clang diagnostic ignored "-Wglobal-constructors" 14818 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 14819 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 14832 const int hexThreshold = 255;
14834 struct Endianness {
14835 enum Arch { Big, Little };
14837 static Arch which() {
14841 auto value = *
reinterpret_cast<char*
>(&
one);
14842 return value ? Little : Big;
14849 int i = 0, end =
static_cast<int>(
size ), inc = 1;
14850 if( Endianness::which() == Endianness::Little ) {
14855 unsigned char const *bytes =
static_cast<unsigned char const *
>(
object);
14857 rss <<
"0x" << std::setfill(
'0') << std::hex;
14858 for( ; i !=
end; i += inc )
14859 rss << std::setw(2) <<
static_cast<unsigned>(bytes[i]);
14864 template<
typename T>
14866 if (Catch::isnan(value)) {
14871 rss << std::setprecision( precision )
14875 std::size_t
i = d.find_last_not_of(
'0' );
14876 if( i != std::string::npos && i != d.size()-1 ) {
14879 d = d.substr( 0, i+1 );
14892 return '"' + str +
'"';
14896 for (
char c : str) {
14913 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 14923 return{
"{null string}" };
14930 return{
"{null string}" };
14934 #ifdef CATCH_CONFIG_WCHAR 14937 s.reserve(wstr.size());
14938 for (
auto c : wstr) {
14944 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 14954 return{
"{null string}" };
14961 return{
"{null string}" };
14966 #if defined(CATCH_CONFIG_CPP17_BYTE) 14971 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 14982 if (value > Detail::hexThreshold) {
14983 rss <<
" (0x" << std::hex << value <<
')';
14997 if (value > Detail::hexThreshold) {
14998 rss <<
" (0x" << std::hex << value <<
')';
15004 return b ?
"true" :
"false";
15008 if (value ==
'\r') {
15010 }
else if (value ==
'\f') {
15012 }
else if (value ==
'\n') {
15014 }
else if (value ==
'\t') {
15016 }
else if (
'\0' <= value && value <
' ') {
15019 char chstr[] =
"' '";
15038 return fpToString(value, precision) +
'f';
15044 return fpToString(value, precision);
15047 std::string ratio_string<std::atto>::symbol() {
return "a"; }
15048 std::string ratio_string<std::femto>::symbol() {
return "f"; }
15049 std::string ratio_string<std::pico>::symbol() {
return "p"; }
15050 std::string ratio_string<std::nano>::symbol() {
return "n"; }
15051 std::string ratio_string<std::micro>::symbol() {
return "u"; }
15052 std::string ratio_string<std::milli>::symbol() {
return "m"; }
15056 #if defined(__clang__) 15057 # pragma clang diagnostic pop 15081 return passed +
failed + failedButOk;
15084 return failed == 0 && failedButOk == 0;
15104 Totals diff = *
this - prevTotals;
15118 #include <exception> 15121 bool uncaught_exceptions() {
15122 #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15123 return std::uncaught_exceptions() > 0;
15125 return std::uncaught_exception();
15137 (
unsigned int _majorVersion,
15138 unsigned int _minorVersion,
15139 unsigned int _patchNumber,
15140 char const *
const _branchName,
15141 unsigned int _buildNumber )
15142 : majorVersion( _majorVersion ),
15143 minorVersion( _minorVersion ),
15144 patchNumber( _patchNumber ),
15145 branchName( _branchName ),
15146 buildNumber( _buildNumber )
15149 std::ostream&
operator << ( std::ostream& os, Version
const& version ) {
15150 os << version.majorVersion <<
'.' 15151 << version.minorVersion <<
'.' 15152 << version.patchNumber;
15154 if (version.branchName[0]) {
15155 os <<
'-' << version.branchName
15156 <<
'.' << version.buildNumber;
15161 Version
const& libraryVersion() {
15162 static Version version( 2, 12, 1,
"", 0 );
15174 : m_caseSensitivity( caseSensitivity ),
15175 m_pattern( normaliseString( pattern ) )
15178 m_pattern = m_pattern.substr( 1 );
15179 m_wildcard = WildcardAtStart;
15181 if(
endsWith( m_pattern,
'*' ) ) {
15182 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15183 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15188 switch( m_wildcard ) {
15190 return m_pattern == normaliseString( str );
15191 case WildcardAtStart:
15192 return endsWith( normaliseString( str ), m_pattern );
15193 case WildcardAtEnd:
15194 return startsWith( normaliseString( str ), m_pattern );
15195 case WildcardAtBothEnds:
15196 return contains( normaliseString( str ), m_pattern );
15210 #include <type_traits> 15216 size_t trailingBytes(
unsigned char c) {
15217 if ((c & 0xE0) == 0xC0) {
15220 if ((c & 0xF0) == 0xE0) {
15223 if ((c & 0xF8) == 0xF0) {
15229 uint32_t headerValue(
unsigned char c) {
15230 if ((c & 0xE0) == 0xC0) {
15233 if ((c & 0xF0) == 0xE0) {
15236 if ((c & 0xF8) == 0xF0) {
15242 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15243 std::ios_base::fmtflags
f(os.flags());
15245 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15246 <<
static_cast<int>(
c);
15250 bool shouldNewline(XmlFormatting
fmt) {
15254 bool shouldIndent(XmlFormatting fmt) {
15260 XmlFormatting
operator | (XmlFormatting
lhs, XmlFormatting rhs) {
15261 return static_cast<XmlFormatting
>(
15267 XmlFormatting
operator & (XmlFormatting lhs, XmlFormatting rhs) {
15268 return static_cast<XmlFormatting
>(
15276 m_forWhat( forWhat )
15279 void XmlEncode::encodeTo( std::ostream& os )
const {
15283 for( std::size_t
idx = 0;
idx < m_str.size(); ++
idx ) {
15284 unsigned char c = m_str[idx];
15286 case '<': os <<
"<";
break;
15287 case '&': os <<
"&";
break;
15291 if (
idx > 2 && m_str[
idx - 1] ==
']' && m_str[
idx - 2] ==
']')
15298 if (m_forWhat == ForAttributes)
15309 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15310 hexEscapeChar(os, c);
15328 hexEscapeChar(os, c);
15332 auto encBytes = trailingBytes(c);
15334 if (
idx + encBytes - 1 >= m_str.size()) {
15335 hexEscapeChar(os, c);
15343 for (std::size_t
n = 1;
n < encBytes; ++
n) {
15344 unsigned char nc = m_str[idx + n];
15345 valid &= ((nc & 0xC0) == 0x80);
15346 value = (value << 6) | (nc & 0x3F);
15357 (value >= 0x110000)
15359 hexEscapeChar(os, c);
15364 for (std::size_t
n = 0;
n < encBytes; ++
n) {
15365 os << m_str[idx + n];
15367 idx += encBytes - 1;
15373 std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15374 xmlEncode.encodeTo( os );
15378 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting
fmt )
15379 : m_writer( writer ),
15383 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15384 : m_writer( other.m_writer ),
15387 other.m_writer =
nullptr;
15388 other.m_fmt = XmlFormatting::None;
15390 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15392 m_writer->endElement();
15394 m_writer = other.m_writer;
15395 other.m_writer =
nullptr;
15396 m_fmt = other.m_fmt;
15397 other.m_fmt = XmlFormatting::None;
15401 XmlWriter::ScopedElement::~ScopedElement() {
15403 m_writer->endElement(m_fmt);
15407 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText(
std::string const& text, XmlFormatting fmt ) {
15408 m_writer->writeText( text, fmt );
15412 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15414 writeDeclaration();
15417 XmlWriter::~XmlWriter() {
15418 while (!m_tags.empty()) {
15421 newlineIfNecessary();
15424 XmlWriter& XmlWriter::startElement(
std::string const&
name, XmlFormatting fmt ) {
15426 newlineIfNecessary();
15427 if (shouldIndent(fmt)) {
15431 m_os <<
'<' <<
name;
15432 m_tags.push_back( name );
15433 m_tagIsOpen =
true;
15434 applyFormatting(fmt);
15438 XmlWriter::ScopedElement XmlWriter::scopedElement(
std::string const& name, XmlFormatting fmt ) {
15439 ScopedElement scoped(
this, fmt );
15440 startElement( name, fmt );
15444 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15445 m_indent = m_indent.substr(0, m_indent.size() - 2);
15447 if( m_tagIsOpen ) {
15449 m_tagIsOpen =
false;
15451 newlineIfNecessary();
15452 if (shouldIndent(fmt)) {
15455 m_os <<
"</" << m_tags.back() <<
">";
15457 m_os << std::flush;
15458 applyFormatting(fmt);
15464 if( !name.empty() && !attribute.empty() )
15465 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15469 XmlWriter& XmlWriter::writeAttribute(
std::string const& name,
bool attribute ) {
15470 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15474 XmlWriter& XmlWriter::writeText(
std::string const& text, XmlFormatting fmt) {
15475 if( !text.empty() ){
15476 bool tagWasOpen = m_tagIsOpen;
15478 if (tagWasOpen && shouldIndent(fmt)) {
15481 m_os << XmlEncode( text );
15482 applyFormatting(fmt);
15487 XmlWriter& XmlWriter::writeComment(
std::string const& text, XmlFormatting fmt) {
15489 if (shouldIndent(fmt)) {
15492 m_os <<
"<!--" << text <<
"-->";
15493 applyFormatting(fmt);
15497 void XmlWriter::writeStylesheetRef(
std::string const& url ) {
15498 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15501 XmlWriter& XmlWriter::writeBlankLine() {
15507 void XmlWriter::ensureTagClosed() {
15508 if( m_tagIsOpen ) {
15509 m_os << '>
' << std::flush; 15510 newlineIfNecessary(); 15511 m_tagIsOpen = false; 15515 void XmlWriter::applyFormatting(XmlFormatting fmt) { 15516 m_needsNewline = shouldNewline(fmt); 15519 void XmlWriter::writeDeclaration() { 15520 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; 15523 void XmlWriter::newlineIfNecessary() { 15524 if( m_needsNewline ) { 15526 m_needsNewline = false; 15530 // end catch_xmlwriter.cpp 15531 // start catch_reporter_bases.cpp 15540 void prepareExpandedExpression(AssertionResult& result) { 15541 result.getExpandedExpression(); 15544 // Because formatting using c++ streams is stateful, drop down to C is required 15545 // Alternatively we could use stringstream, but its performance is... not good. 15546 std::string getFormattedDuration( double duration ) { 15547 // Max exponent + 1 is required to represent the whole part 15548 // + 1 for decimal point 15549 // + 3 for the 3 decimal places 15550 // + 1 for null terminator 15551 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; 15552 char buffer[maxDoubleSize]; 15554 // Save previous errno, to prevent sprintf from overwriting it 15557 sprintf_s(buffer, "%.3f", duration); 15559 std::sprintf(buffer, "%.3f", duration); 15561 return std::string(buffer); 15564 std::string serializeFilters( std::vector<std::string> const& container ) { 15565 ReusableStringStream oss; 15567 for (auto&& filter : container) 15579 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) 15580 :StreamingReporterBase(_config) {} 15582 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() { 15583 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; 15586 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} 15588 bool TestEventListenerBase::assertionEnded(AssertionStats const &) { 15592 } // end namespace Catch 15593 // end catch_reporter_bases.cpp 15594 // start catch_reporter_compact.cpp 15598 #ifdef CATCH_PLATFORM_MAC 15599 const char* failedString() { return "FAILED"; } 15600 const char* passedString() { return "PASSED"; } 15602 const char* failedString() { return "failed"; } 15603 const char* passedString() { return "passed"; } 15606 // Colour::LightGrey 15607 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } 15609 std::string bothOrAll( std::size_t count ) { 15610 return count == 1 ? std::string() : 15611 count == 2 ? "both " : "all " ; 15614 } // anon namespace 15618 // Colour, message variants: 15619 // - white: No tests ran. 15620 // - red: Failed [both/all] N test cases, failed [both/all] M assertions. 15621 // - white: Passed [both/all] N test cases (no assertions). 15622 // - red: Failed N tests cases, failed M assertions. 15623 // - green: Passed [both/all] N tests cases with M assertions. 15624 void printTotals(std::ostream& out, const Totals& totals) { 15625 if (totals.testCases.total() == 0) { 15626 out << "No tests ran."; 15627 } else if (totals.testCases.failed == totals.testCases.total()) { 15628 Colour colour(Colour::ResultError); 15629 const std::string qualify_assertions_failed = 15630 totals.assertions.failed == totals.assertions.total() ? 15631 bothOrAll(totals.assertions.failed) : std::string(); 15633 "Failed " << bothOrAll(totals.testCases.failed) 15634 << pluralise(totals.testCases.failed, "test case") << ", " 15635 "failed " << qualify_assertions_failed << 15636 pluralise(totals.assertions.failed, "assertion") << '.
'; 15637 } else if (totals.assertions.total() == 0) { 15639 "Passed " << bothOrAll(totals.testCases.total()) 15640 << pluralise(totals.testCases.total(), "test case") 15641 << " (no assertions)."; 15642 } else if (totals.assertions.failed) { 15643 Colour colour(Colour::ResultError); 15645 "Failed " << pluralise(totals.testCases.failed, "test case") << ", " 15646 "failed " << pluralise(totals.assertions.failed, "assertion") << '.
'; 15648 Colour colour(Colour::ResultSuccess); 15650 "Passed " << bothOrAll(totals.testCases.passed) 15651 << pluralise(totals.testCases.passed, "test case") << 15652 " with " << pluralise(totals.assertions.passed, "assertion") << '.
'; 15656 // Implementation of CompactReporter formatting 15657 class AssertionPrinter { 15659 AssertionPrinter& operator= (AssertionPrinter const&) = delete; 15660 AssertionPrinter(AssertionPrinter const&) = delete; 15661 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) 15663 , result(_stats.assertionResult) 15664 , messages(_stats.infoMessages) 15665 , itMessage(_stats.infoMessages.begin()) 15666 , printInfoMessages(_printInfoMessages) {} 15671 itMessage = messages.begin(); 15673 switch (result.getResultType()) { 15674 case ResultWas::Ok: 15675 printResultType(Colour::ResultSuccess, passedString()); 15676 printOriginalExpression(); 15677 printReconstructedExpression(); 15678 if (!result.hasExpression()) 15679 printRemainingMessages(Colour::None); 15681 printRemainingMessages(); 15683 case ResultWas::ExpressionFailed: 15685 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); 15687 printResultType(Colour::Error, failedString()); 15688 printOriginalExpression(); 15689 printReconstructedExpression(); 15690 printRemainingMessages(); 15692 case ResultWas::ThrewException: 15693 printResultType(Colour::Error, failedString()); 15694 printIssue("unexpected exception with message:"); 15696 printExpressionWas(); 15697 printRemainingMessages(); 15699 case ResultWas::FatalErrorCondition: 15700 printResultType(Colour::Error, failedString()); 15701 printIssue("fatal error condition with message:"); 15703 printExpressionWas(); 15704 printRemainingMessages(); 15706 case ResultWas::DidntThrowException: 15707 printResultType(Colour::Error, failedString()); 15708 printIssue("expected exception, got none"); 15709 printExpressionWas(); 15710 printRemainingMessages(); 15712 case ResultWas::Info: 15713 printResultType(Colour::None, "info"); 15715 printRemainingMessages(); 15717 case ResultWas::Warning: 15718 printResultType(Colour::None, "warning"); 15720 printRemainingMessages(); 15722 case ResultWas::ExplicitFailure: 15723 printResultType(Colour::Error, failedString()); 15724 printIssue("explicitly"); 15725 printRemainingMessages(Colour::None); 15727 // These cases are here to prevent compiler warnings 15728 case ResultWas::Unknown: 15729 case ResultWas::FailureBit: 15730 case ResultWas::Exception: 15731 printResultType(Colour::Error, "** internal error **"); 15737 void printSourceInfo() const { 15738 Colour colourGuard(Colour::FileName); 15739 stream << result.getSourceInfo() << ':
'; 15742 void printResultType(Colour::Code colour, std::string const& passOrFail) const { 15743 if (!passOrFail.empty()) { 15745 Colour colourGuard(colour); 15746 stream << ' ' << passOrFail; 15752 void printIssue(std::string const& issue) const { 15753 stream << ' ' << issue; 15756 void printExpressionWas() { 15757 if (result.hasExpression()) { 15760 Colour colour(dimColour()); 15761 stream << " expression was:"; 15763 printOriginalExpression(); 15767 void printOriginalExpression() const { 15768 if (result.hasExpression()) { 15769 stream << ' ' << result.getExpression(); 15773 void printReconstructedExpression() const { 15774 if (result.hasExpandedExpression()) { 15776 Colour colour(dimColour()); 15777 stream << " for: "; 15779 stream << result.getExpandedExpression(); 15783 void printMessage() { 15784 if (itMessage != messages.end()) { 15785 stream << " '" << itMessage->message << '\''; 15790 void printRemainingMessages(Colour::Code colour = dimColour()) { 15791 if (itMessage == messages.end()) 15794 const auto itEnd = messages.cend(); 15795 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd)); 15798 Colour colourGuard(colour); 15799 stream << " with
" << pluralise(N, "message") << ':'; 15802 while (itMessage != itEnd) { 15803 // If this assertion is a warning ignore any INFO messages 15804 if (printInfoMessages || itMessage->type != ResultWas::Info) { 15806 if (itMessage != itEnd) { 15807 Colour colourGuard(dimColour()); 15817 std::ostream& stream; 15818 AssertionResult const& result; 15819 std::vector<MessageInfo> messages; 15820 std::vector<MessageInfo>::const_iterator itMessage; 15821 bool printInfoMessages; 15824 } // anon namespace 15826 std::string CompactReporter::getDescription() { 15827 return "Reports
test results on
a single
line, suitable
for IDEs
"; 15830 ReporterPreferences CompactReporter::getPreferences() const { 15831 return m_reporterPrefs; 15834 void CompactReporter::noMatchingTestCases( std::string const& spec ) { 15835 stream << "No
test cases matched
'" << spec << '\
'' << std::endl;
15838 void CompactReporter::assertionStarting(
AssertionInfo const& ) {}
15840 bool CompactReporter::assertionEnded( AssertionStats
const& _assertionStats ) {
15841 AssertionResult
const&
result = _assertionStats.assertionResult;
15843 bool printInfoMessages =
true;
15846 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
15849 printInfoMessages =
false;
15852 AssertionPrinter printer(
stream, _assertionStats, printInfoMessages );
15859 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
15861 stream << getFormattedDuration(_sectionStats.durationInSeconds) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
15865 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
15866 printTotals(
stream, _testRunStats.totals );
15867 stream <<
'\n' << std::endl;
15868 StreamingReporterBase::testRunEnded( _testRunStats );
15871 CompactReporter::~CompactReporter() {}
15873 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
15882 #if defined(_MSC_VER) 15883 #pragma warning(push) 15884 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 15888 #if defined(__clang__) 15889 # pragma clang diagnostic push 15891 # pragma clang diagnostic ignored "-Wunused-function" 15899 class ConsoleAssertionPrinter {
15901 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter
const&) =
delete;
15902 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
15903 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
15906 result(_stats.assertionResult),
15907 colour(Colour::None),
15909 messages(_stats.infoMessages),
15910 printInfoMessages(_printInfoMessages) {
15911 switch (
result.getResultType()) {
15913 colour = Colour::Success;
15914 passOrFail =
"PASSED";
15916 if (_stats.infoMessages.size() == 1)
15917 messageLabel =
"with message";
15918 if (_stats.infoMessages.size() > 1)
15919 messageLabel =
"with messages";
15923 colour = Colour::Success;
15924 passOrFail =
"FAILED - but was ok";
15926 colour = Colour::Error;
15927 passOrFail =
"FAILED";
15929 if (_stats.infoMessages.size() == 1)
15930 messageLabel =
"with message";
15931 if (_stats.infoMessages.size() > 1)
15932 messageLabel =
"with messages";
15935 colour = Colour::Error;
15936 passOrFail =
"FAILED";
15937 messageLabel =
"due to unexpected exception with ";
15938 if (_stats.infoMessages.size() == 1)
15939 messageLabel +=
"message";
15940 if (_stats.infoMessages.size() > 1)
15941 messageLabel +=
"messages";
15944 colour = Colour::Error;
15945 passOrFail =
"FAILED";
15946 messageLabel =
"due to a fatal error condition";
15949 colour = Colour::Error;
15950 passOrFail =
"FAILED";
15951 messageLabel =
"because no exception was thrown where one was expected";
15954 messageLabel =
"info";
15957 messageLabel =
"warning";
15960 passOrFail =
"FAILED";
15961 colour = Colour::Error;
15962 if (_stats.infoMessages.size() == 1)
15963 messageLabel =
"explicitly with message";
15964 if (_stats.infoMessages.size() > 1)
15965 messageLabel =
"explicitly with messages";
15971 passOrFail =
"** internal error **";
15972 colour = Colour::Error;
15977 void print()
const {
15979 if (stats.totals.assertions.total() > 0) {
15981 printOriginalExpression();
15982 printReconstructedExpression();
15990 void printResultType()
const {
15991 if (!passOrFail.empty()) {
15992 Colour colourGuard(colour);
15993 stream << passOrFail <<
":\n";
15996 void printOriginalExpression()
const {
15997 if (
result.hasExpression()) {
15998 Colour colourGuard(Colour::OriginalExpression);
16004 void printReconstructedExpression()
const {
16005 if (
result.hasExpandedExpression()) {
16006 stream <<
"with expansion:\n";
16007 Colour colourGuard(Colour::ReconstructedExpression);
16011 void printMessage()
const {
16012 if (!messageLabel.empty())
16013 stream << messageLabel <<
':' <<
'\n';
16014 for (
auto const& msg : messages) {
16020 void printSourceInfo()
const {
16021 Colour colourGuard(Colour::FileName);
16026 AssertionStats
const& stats;
16027 AssertionResult
const&
result;
16028 Colour::Code colour;
16032 std::vector<MessageInfo> messages;
16033 bool printInfoMessages;
16036 std::size_t makeRatio(std::size_t number, std::size_t total) {
16037 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16038 return (ratio == 0 && number > 0) ? 1 : ratio;
16041 std::size_t& findMax(std::size_t&
i, std::size_t&
j, std::size_t& k) {
16042 if (i > j && i > k)
16050 struct ColumnInfo {
16051 enum Justification { Left, Right };
16054 Justification justification;
16056 struct ColumnBreak {};
16057 struct RowBreak {};
16068 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16069 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16070 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16071 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16073 double m_inNanoseconds;
16077 explicit Duration(
double inNanoseconds, Unit
units = Unit::Auto)
16078 : m_inNanoseconds(inNanoseconds),
16080 if (m_units == Unit::Auto) {
16081 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16082 m_units = Unit::Nanoseconds;
16083 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16084 m_units = Unit::Microseconds;
16085 else if (m_inNanoseconds < s_nanosecondsInASecond)
16086 m_units = Unit::Milliseconds;
16087 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16088 m_units = Unit::Seconds;
16090 m_units = Unit::Minutes;
16095 auto value()
const ->
double {
16097 case Unit::Microseconds:
16098 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16099 case Unit::Milliseconds:
16100 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16101 case Unit::Seconds:
16102 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16103 case Unit::Minutes:
16104 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16106 return m_inNanoseconds;
16111 case Unit::Nanoseconds:
16113 case Unit::Microseconds:
16115 case Unit::Milliseconds:
16117 case Unit::Seconds:
16119 case Unit::Minutes:
16122 return "** internal error **";
16127 return os << duration.value() <<
' ' << duration.unitsAsString();
16132 class TablePrinter {
16133 std::ostream& m_os;
16134 std::vector<ColumnInfo> m_columnInfos;
16135 std::ostringstream m_oss;
16136 int m_currentColumn = -1;
16137 bool m_isOpen =
false;
16140 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16142 m_columnInfos(
std::move( columnInfos ) ) {}
16144 auto columnInfos()
const -> std::vector<ColumnInfo>
const& {
16145 return m_columnInfos;
16151 *
this << RowBreak();
16155 for (
auto const&
info : m_columnInfos) {
16156 headerCols +=
Column(
info.name).width(static_cast<std::size_t>(
info.width - 2));
16157 headerCols += spacer;
16159 m_os << headerCols <<
'\n';
16161 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16166 *
this << RowBreak();
16172 template<
typename T>
16178 friend TablePrinter&
operator << (TablePrinter& tp, ColumnBreak) {
16179 auto colStr = tp.m_oss.str();
16180 const auto strSize = colStr.size();
16183 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16184 tp.m_currentColumn = -1;
16187 tp.m_currentColumn++;
16189 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16190 auto padding = (strSize + 1 <
static_cast<std::size_t
>(colInfo.width))
16191 ?
std::string(colInfo.width - (strSize + 1),
' ')
16193 if (colInfo.justification == ColumnInfo::Left)
16194 tp.m_os << colStr << padding <<
' ';
16196 tp.m_os << padding << colStr <<
' ';
16200 friend TablePrinter&
operator << (TablePrinter& tp, RowBreak) {
16201 if (tp.m_currentColumn > 0) {
16203 tp.m_currentColumn = -1;
16209 ConsoleReporter::ConsoleReporter(ReporterConfig
const&
config)
16210 : StreamingReporterBase(config),
16211 m_tablePrinter(
new TablePrinter(config.stream(),
16212 [&config]() -> std::vector<ColumnInfo> {
16213 if (config.fullConfig()->benchmarkNoAnalysis())
16216 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16217 {
" samples", 14, ColumnInfo::Right },
16218 {
" iterations", 14, ColumnInfo::Right },
16219 {
" mean", 14, ColumnInfo::Right }
16225 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16226 {
"samples mean std dev", 14, ColumnInfo::Right },
16227 {
"iterations low mean low std dev", 14, ColumnInfo::Right },
16228 {
"estimated high mean high std dev", 14, ColumnInfo::Right }
16232 ConsoleReporter::~ConsoleReporter() =
default;
16235 return "Reports test results as plain lines of text";
16238 void ConsoleReporter::noMatchingTestCases(
std::string const& spec) {
16239 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16242 void ConsoleReporter::reportInvalidArguments(
std::string const&
arg){
16243 stream <<
"Invalid Filter: " << arg << std::endl;
16246 void ConsoleReporter::assertionStarting(
AssertionInfo const&) {}
16248 bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16249 AssertionResult
const&
result = _assertionStats.assertionResult;
16251 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16259 ConsoleAssertionPrinter printer(
stream, _assertionStats, includeResults);
16265 void ConsoleReporter::sectionStarting(
SectionInfo const& _sectionInfo) {
16266 m_tablePrinter->close();
16267 m_headerPrinted =
false;
16268 StreamingReporterBase::sectionStarting(_sectionInfo);
16270 void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16271 m_tablePrinter->close();
16272 if (_sectionStats.missingAssertions) {
16274 Colour colour(Colour::ResultError);
16275 if (m_sectionStack.size() > 1)
16276 stream <<
"\nNo assertions in section";
16278 stream <<
"\nNo assertions in test case";
16279 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16282 stream << getFormattedDuration(_sectionStats.durationInSeconds) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16284 if (m_headerPrinted) {
16285 m_headerPrinted =
false;
16287 StreamingReporterBase::sectionEnded(_sectionStats);
16290 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 16291 void ConsoleReporter::benchmarkPreparing(
std::string const& name) {
16292 lazyPrintWithoutClosingBenchmarkTable();
16294 auto nameCol =
Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16296 bool firstLine =
true;
16297 for (
auto line : nameCol) {
16299 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16303 (*m_tablePrinter) <<
line << ColumnBreak();
16307 void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const&
info) {
16308 (*m_tablePrinter) << info.samples << ColumnBreak()
16309 << info.iterations << ColumnBreak();
16310 if (!m_config->benchmarkNoAnalysis())
16311 (*m_tablePrinter) <<
Duration(info.estimatedDuration) << ColumnBreak();
16313 void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16314 if (m_config->benchmarkNoAnalysis())
16316 (*m_tablePrinter) <<
Duration(stats.mean.point.count()) << ColumnBreak();
16320 (*m_tablePrinter) << ColumnBreak()
16321 <<
Duration(stats.mean.point.count()) << ColumnBreak()
16322 <<
Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16323 <<
Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16324 <<
Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16325 <<
Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16326 <<
Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16331 Colour colour(Colour::Red);
16333 <<
"Benchmark failed (" << error <<
')' 16334 << ColumnBreak() << RowBreak();
16336 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 16338 void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16339 m_tablePrinter->close();
16340 StreamingReporterBase::testCaseEnded(_testCaseStats);
16341 m_headerPrinted =
false;
16343 void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16344 if (currentGroupInfo.used) {
16345 printSummaryDivider();
16346 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16347 printTotals(_testGroupStats.totals);
16348 stream <<
'\n' << std::endl;
16350 StreamingReporterBase::testGroupEnded(_testGroupStats);
16352 void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16353 printTotalsDivider(_testRunStats.totals);
16354 printTotals(_testRunStats.totals);
16356 StreamingReporterBase::testRunEnded(_testRunStats);
16358 void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16359 StreamingReporterBase::testRunStarting(_testInfo);
16360 printTestFilters();
16363 void ConsoleReporter::lazyPrint() {
16365 m_tablePrinter->close();
16366 lazyPrintWithoutClosingBenchmarkTable();
16369 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16371 if (!currentTestRunInfo.used)
16372 lazyPrintRunInfo();
16373 if (!currentGroupInfo.used)
16374 lazyPrintGroupInfo();
16376 if (!m_headerPrinted) {
16377 printTestCaseAndSectionHeader();
16378 m_headerPrinted =
true;
16381 void ConsoleReporter::lazyPrintRunInfo() {
16383 Colour colour(Colour::SecondaryText);
16384 stream << currentTestRunInfo->name
16385 <<
" is a Catch v" << libraryVersion() <<
" host application.\n" 16386 <<
"Run with -? for options\n\n";
16388 if (m_config->rngSeed() != 0)
16389 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16391 currentTestRunInfo.used =
true;
16393 void ConsoleReporter::lazyPrintGroupInfo() {
16394 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16395 printClosedHeader(
"Group: " + currentGroupInfo->name);
16396 currentGroupInfo.used =
true;
16399 void ConsoleReporter::printTestCaseAndSectionHeader() {
16400 assert(!m_sectionStack.empty());
16401 printOpenHeader(currentTestCaseInfo->name);
16403 if (m_sectionStack.size() > 1) {
16404 Colour colourGuard(Colour::Headers);
16407 it = m_sectionStack.begin() + 1,
16408 itEnd = m_sectionStack.end();
16409 for (;
it != itEnd; ++
it)
16410 printHeaderString(
it->name, 2);
16415 stream << getLineOfChars<
'-'>() <<
'\n';
16416 Colour colourGuard(Colour::FileName);
16417 stream << lineInfo <<
'\n';
16418 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16422 printOpenHeader(_name);
16423 stream << getLineOfChars<
'.'>() <<
'\n';
16425 void ConsoleReporter::printOpenHeader(
std::string const& _name) {
16426 stream << getLineOfChars<
'-'>() <<
'\n';
16428 Colour colourGuard(Colour::Headers);
16429 printHeaderString(_name);
16435 void ConsoleReporter::printHeaderString(
std::string const& _string, std::size_t indent) {
16436 std::size_t
i = _string.find(
": ");
16437 if (i != std::string::npos)
16441 stream <<
Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16444 struct SummaryColumn {
16446 SummaryColumn(
std::string _label, Colour::Code _colour )
16448 colour( _colour ) {}
16449 SummaryColumn addRow( std::size_t
count ) {
16453 for (
auto& oldRow : rows) {
16454 while (oldRow.size() < row.size())
16455 oldRow =
' ' + oldRow;
16456 while (oldRow.size() > row.size())
16459 rows.push_back(row);
16464 Colour::Code colour;
16465 std::vector<std::string> rows;
16469 void ConsoleReporter::printTotals(
Totals const& totals ) {
16471 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16473 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16480 std::vector<SummaryColumn> columns;
16481 columns.push_back(SummaryColumn(
"", Colour::None)
16484 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16487 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16490 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16494 printSummaryRow(
"test cases", columns, 0);
16495 printSummaryRow(
"assertions", columns, 1);
16498 void ConsoleReporter::printSummaryRow(
std::string const&
label, std::vector<SummaryColumn>
const& cols, std::size_t
row) {
16499 for (
auto col : cols) {
16501 if (
col.label.empty()) {
16502 stream << label <<
": ";
16506 stream << Colour(Colour::Warning) <<
"- none -";
16507 }
else if (value !=
"0") {
16508 stream << Colour(Colour::LightGrey) <<
" | ";
16510 << value <<
' ' <<
col.label;
16516 void ConsoleReporter::printTotalsDivider(
Totals const& totals) {
16521 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16522 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16523 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16524 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16527 stream << Colour(Colour::ResultExpectedFailure) <<
std::string(failedButOkRatio,
'=');
16533 stream << Colour(Colour::Warning) <<
std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16537 void ConsoleReporter::printSummaryDivider() {
16538 stream << getLineOfChars<
'-'>() <<
'\n';
16541 void ConsoleReporter::printTestFilters() {
16542 if (m_config->testSpec().hasFilters()) {
16543 Colour guard(Colour::BrightYellow);
16544 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16548 CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16552 #if defined(_MSC_VER) 16553 #pragma warning(pop) 16556 #if defined(__clang__) 16557 # pragma clang diagnostic pop 16565 #include <algorithm> 16574 std::time(&rawtime);
16575 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16578 std::tm timeInfo = {};
16579 gmtime_s(&timeInfo, &rawtime);
16582 timeInfo = std::gmtime(&rawtime);
16586 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16589 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16591 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16597 auto it = std::find_if(
begin(tags),
16600 if (
it != tags.end())
16601 return it->substr(1);
16606 JunitReporter::JunitReporter( ReporterConfig
const&
_config )
16607 : CumulativeReporterBase( _config ),
16608 xml( _config.stream() )
16610 m_reporterPrefs.shouldRedirectStdOut =
true;
16611 m_reporterPrefs.shouldReportAllAssertions =
true;
16614 JunitReporter::~JunitReporter() {}
16617 return "Reports test results in an XML format that looks like Ant's junitreport target";
16620 void JunitReporter::noMatchingTestCases(
std::string const& ) {}
16622 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16623 CumulativeReporterBase::testRunStarting( runInfo );
16624 xml.startElement(
"testsuites" );
16627 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16628 suiteTimer.start();
16629 stdOutForSuite.clear();
16630 stdErrForSuite.clear();
16631 unexpectedExceptions = 0;
16632 CumulativeReporterBase::testGroupStarting( groupInfo );
16635 void JunitReporter::testCaseStarting(
TestCaseInfo const& testCaseInfo ) {
16636 m_okToFail = testCaseInfo.
okToFail();
16639 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16641 unexpectedExceptions++;
16642 return CumulativeReporterBase::assertionEnded( assertionStats );
16645 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16646 stdOutForSuite += testCaseStats.stdOut;
16647 stdErrForSuite += testCaseStats.stdErr;
16648 CumulativeReporterBase::testCaseEnded( testCaseStats );
16651 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16652 double suiteTime = suiteTimer.getElapsedSeconds();
16653 CumulativeReporterBase::testGroupEnded( testGroupStats );
16654 writeGroup( *m_testGroups.back(), suiteTime );
16657 void JunitReporter::testRunEndedCumulative() {
16661 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16662 XmlWriter::ScopedElement
e = xml.scopedElement(
"testsuite" );
16664 TestGroupStats
const& stats = groupNode.value;
16665 xml.writeAttribute(
"name", stats.groupInfo.name );
16666 xml.writeAttribute(
"errors", unexpectedExceptions );
16667 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16668 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16669 xml.writeAttribute(
"hostname",
"tbd" );
16671 xml.writeAttribute(
"time",
"" );
16673 xml.writeAttribute(
"time", suiteTime );
16674 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16677 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16678 auto properties = xml.scopedElement(
"properties");
16679 if (m_config->hasTestFilters()) {
16680 xml.scopedElement(
"property")
16681 .writeAttribute(
"name",
"filters")
16682 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16684 if (m_config->rngSeed() != 0) {
16685 xml.scopedElement(
"property")
16686 .writeAttribute(
"name",
"random-seed")
16687 .writeAttribute(
"value", m_config->rngSeed());
16692 for(
auto const& child : groupNode.children )
16693 writeTestCase( *child );
16695 xml.scopedElement(
"system-out" ).writeText(
trim( stdOutForSuite ), XmlFormatting::Newline );
16696 xml.scopedElement(
"system-err" ).writeText(
trim( stdErrForSuite ), XmlFormatting::Newline );
16699 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16700 TestCaseStats
const& stats = testCaseNode.value;
16704 assert( testCaseNode.children.size() == 1 );
16705 SectionNode
const& rootSection = *testCaseNode.children.front();
16707 std::string className = stats.testInfo.className;
16709 if( className.empty() ) {
16710 className = fileNameTag(stats.testInfo.tags);
16711 if ( className.empty() )
16712 className =
"global";
16715 if ( !m_config->name().empty() )
16716 className = m_config->name() +
"." + className;
16718 writeSection( className,
"", rootSection );
16721 void JunitReporter::writeSection(
std::string const& className,
16723 SectionNode
const& sectionNode ) {
16725 if( !rootName.empty() )
16726 name = rootName +
'/' + name;
16728 if( !sectionNode.assertions.empty() ||
16729 !sectionNode.stdOut.empty() ||
16730 !sectionNode.stdErr.empty() ) {
16731 XmlWriter::ScopedElement
e = xml.scopedElement(
"testcase" );
16732 if( className.empty() ) {
16733 xml.writeAttribute(
"classname", name );
16734 xml.writeAttribute(
"name",
"root" );
16737 xml.writeAttribute(
"classname", className );
16738 xml.writeAttribute(
"name", name );
16742 writeAssertions( sectionNode );
16744 if( !sectionNode.stdOut.empty() )
16745 xml.scopedElement(
"system-out" ).writeText(
trim( sectionNode.stdOut ), XmlFormatting::Newline );
16746 if( !sectionNode.stdErr.empty() )
16747 xml.scopedElement(
"system-err" ).writeText(
trim( sectionNode.stdErr ), XmlFormatting::Newline );
16749 for(
auto const& childNode : sectionNode.childSections )
16750 if( className.empty() )
16751 writeSection( name,
"", *childNode );
16753 writeSection( className, name, *childNode );
16756 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
16757 for(
auto const&
assertion : sectionNode.assertions )
16761 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
16762 AssertionResult
const&
result = stats.assertionResult;
16763 if( !result.isOk() ) {
16765 switch( result.getResultType() ) {
16768 elementName =
"error";
16773 elementName =
"failure";
16783 elementName =
"internalError";
16787 XmlWriter::ScopedElement
e = xml.scopedElement( elementName );
16789 xml.writeAttribute(
"message", result.getExpression() );
16790 xml.writeAttribute(
"type", result.getTestMacroName() );
16793 if (stats.totals.assertions.total() > 0) {
16794 rss <<
"FAILED" <<
":\n";
16795 if (result.hasExpression()) {
16797 rss << result.getExpressionInMacro();
16800 if (result.hasExpandedExpression()) {
16801 rss <<
"with expansion:\n";
16802 rss <<
Column(result.getExpandedExpression()).indent(2) <<
'\n';
16808 if( !result.getMessage().empty() )
16809 rss << result.getMessage() <<
'\n';
16810 for(
auto const& msg : stats.infoMessages )
16812 rss << msg.message <<
'\n';
16814 rss <<
"at " << result.getSourceInfo();
16815 xml.writeText( rss.
str(), XmlFormatting::Newline );
16819 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
16829 ListeningReporter::ListeningReporter() {
16831 m_preferences.shouldReportAllAssertions =
true;
16834 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
16835 m_listeners.push_back(
std::move( listener ) );
16838 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
16839 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
16841 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
16844 ReporterPreferences ListeningReporter::getPreferences()
const {
16845 return m_preferences;
16848 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
16849 return std::set<Verbosity>{ };
16852 void ListeningReporter::noMatchingTestCases(
std::string const& spec ) {
16853 for (
auto const& listener : m_listeners ) {
16854 listener->noMatchingTestCases( spec );
16856 m_reporter->noMatchingTestCases( spec );
16859 void ListeningReporter::reportInvalidArguments(
std::string const&
arg){
16860 for (
auto const& listener : m_listeners ) {
16861 listener->reportInvalidArguments( arg );
16863 m_reporter->reportInvalidArguments( arg );
16866 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 16867 void ListeningReporter::benchmarkPreparing(
std::string const& name ) {
16868 for (
auto const& listener : m_listeners) {
16869 listener->benchmarkPreparing(name);
16871 m_reporter->benchmarkPreparing(name);
16873 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
16874 for (
auto const& listener : m_listeners ) {
16875 listener->benchmarkStarting( benchmarkInfo );
16877 m_reporter->benchmarkStarting( benchmarkInfo );
16879 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
16880 for (
auto const& listener : m_listeners ) {
16881 listener->benchmarkEnded( benchmarkStats );
16883 m_reporter->benchmarkEnded( benchmarkStats );
16887 for (
auto const& listener : m_listeners) {
16888 listener->benchmarkFailed(error);
16890 m_reporter->benchmarkFailed(error);
16892 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 16894 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
16895 for (
auto const& listener : m_listeners ) {
16896 listener->testRunStarting( testRunInfo );
16898 m_reporter->testRunStarting( testRunInfo );
16901 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16902 for (
auto const& listener : m_listeners ) {
16903 listener->testGroupStarting( groupInfo );
16905 m_reporter->testGroupStarting( groupInfo );
16908 void ListeningReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
16909 for (
auto const& listener : m_listeners ) {
16910 listener->testCaseStarting( testInfo );
16912 m_reporter->testCaseStarting( testInfo );
16915 void ListeningReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
16916 for (
auto const& listener : m_listeners ) {
16917 listener->sectionStarting( sectionInfo );
16919 m_reporter->sectionStarting( sectionInfo );
16922 void ListeningReporter::assertionStarting(
AssertionInfo const& assertionInfo ) {
16923 for (
auto const& listener : m_listeners ) {
16924 listener->assertionStarting( assertionInfo );
16926 m_reporter->assertionStarting( assertionInfo );
16930 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16931 for(
auto const& listener : m_listeners ) {
16932 static_cast<void>( listener->assertionEnded( assertionStats ) );
16934 return m_reporter->assertionEnded( assertionStats );
16937 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
16938 for (
auto const& listener : m_listeners ) {
16939 listener->sectionEnded( sectionStats );
16941 m_reporter->sectionEnded( sectionStats );
16944 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16945 for (
auto const& listener : m_listeners ) {
16946 listener->testCaseEnded( testCaseStats );
16948 m_reporter->testCaseEnded( testCaseStats );
16951 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16952 for (
auto const& listener : m_listeners ) {
16953 listener->testGroupEnded( testGroupStats );
16955 m_reporter->testGroupEnded( testGroupStats );
16958 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
16959 for (
auto const& listener : m_listeners ) {
16960 listener->testRunEnded( testRunStats );
16962 m_reporter->testRunEnded( testRunStats );
16965 void ListeningReporter::skipTest(
TestCaseInfo const& testInfo ) {
16966 for (
auto const& listener : m_listeners ) {
16967 listener->skipTest( testInfo );
16969 m_reporter->skipTest( testInfo );
16972 bool ListeningReporter::isMulti()
const {
16980 #if defined(_MSC_VER) 16981 #pragma warning(push) 16982 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 16988 XmlReporter::XmlReporter( ReporterConfig
const&
_config )
16989 : StreamingReporterBase( _config ),
16990 m_xml(_config.stream())
16992 m_reporterPrefs.shouldRedirectStdOut =
true;
16993 m_reporterPrefs.shouldReportAllAssertions =
true;
16996 XmlReporter::~XmlReporter() =
default;
16999 return "Reports test results as an XML document";
17002 std::string XmlReporter::getStylesheetRef()
const {
17006 void XmlReporter::writeSourceInfo(
SourceLineInfo const& sourceInfo ) {
17008 .writeAttribute(
"filename", sourceInfo.
file )
17009 .writeAttribute(
"line", sourceInfo.
line );
17012 void XmlReporter::noMatchingTestCases(
std::string const&
s ) {
17013 StreamingReporterBase::noMatchingTestCases( s );
17016 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17017 StreamingReporterBase::testRunStarting( testInfo );
17019 if( !stylesheetRef.empty() )
17020 m_xml.writeStylesheetRef( stylesheetRef );
17021 m_xml.startElement(
"Catch" );
17022 if( !m_config->name().empty() )
17023 m_xml.writeAttribute(
"name", m_config->name() );
17024 if (m_config->testSpec().hasFilters())
17025 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17026 if( m_config->rngSeed() != 0 )
17027 m_xml.scopedElement(
"Randomness" )
17028 .writeAttribute(
"seed", m_config->rngSeed() );
17031 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17032 StreamingReporterBase::testGroupStarting( groupInfo );
17033 m_xml.startElement(
"Group" )
17034 .writeAttribute(
"name", groupInfo.name );
17037 void XmlReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17038 StreamingReporterBase::testCaseStarting(testInfo);
17039 m_xml.startElement(
"TestCase" )
17040 .writeAttribute(
"name",
trim( testInfo.
name ) )
17041 .writeAttribute(
"description", testInfo.
description )
17044 writeSourceInfo( testInfo.
lineInfo );
17047 m_testCaseTimer.start();
17048 m_xml.ensureTagClosed();
17051 void XmlReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17052 StreamingReporterBase::sectionStarting( sectionInfo );
17053 if( m_sectionDepth++ > 0 ) {
17054 m_xml.startElement(
"Section" )
17055 .writeAttribute(
"name",
trim( sectionInfo.
name ) );
17056 writeSourceInfo( sectionInfo.
lineInfo );
17057 m_xml.ensureTagClosed();
17061 void XmlReporter::assertionStarting(
AssertionInfo const& ) { }
17063 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17065 AssertionResult
const&
result = assertionStats.assertionResult;
17067 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17071 for(
auto const& msg : assertionStats.infoMessages ) {
17073 m_xml.scopedElement(
"Info" )
17074 .writeText( msg.message );
17076 m_xml.scopedElement(
"Warning" )
17077 .writeText( msg.message );
17087 if( result.hasExpression() ) {
17088 m_xml.startElement(
"Expression" )
17089 .writeAttribute(
"success", result.succeeded() )
17090 .writeAttribute(
"type", result.getTestMacroName() );
17092 writeSourceInfo( result.getSourceInfo() );
17094 m_xml.scopedElement(
"Original" )
17095 .writeText( result.getExpression() );
17096 m_xml.scopedElement(
"Expanded" )
17097 .writeText( result.getExpandedExpression() );
17101 switch( result.getResultType() ) {
17103 m_xml.startElement(
"Exception" );
17104 writeSourceInfo( result.getSourceInfo() );
17105 m_xml.writeText( result.getMessage() );
17106 m_xml.endElement();
17109 m_xml.startElement(
"FatalErrorCondition" );
17110 writeSourceInfo( result.getSourceInfo() );
17111 m_xml.writeText( result.getMessage() );
17112 m_xml.endElement();
17115 m_xml.scopedElement(
"Info" )
17116 .writeText( result.getMessage() );
17122 m_xml.startElement(
"Failure" );
17123 writeSourceInfo( result.getSourceInfo() );
17124 m_xml.writeText( result.getMessage() );
17125 m_xml.endElement();
17131 if( result.hasExpression() )
17132 m_xml.endElement();
17137 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17138 StreamingReporterBase::sectionEnded( sectionStats );
17139 if( --m_sectionDepth > 0 ) {
17140 XmlWriter::ScopedElement
e = m_xml.scopedElement(
"OverallResults" );
17141 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17142 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17143 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17146 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17148 m_xml.endElement();
17152 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17153 StreamingReporterBase::testCaseEnded( testCaseStats );
17154 XmlWriter::ScopedElement
e = m_xml.scopedElement(
"OverallResult" );
17155 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17158 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17160 if( !testCaseStats.stdOut.empty() )
17161 m_xml.scopedElement(
"StdOut" ).writeText(
trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17162 if( !testCaseStats.stdErr.empty() )
17163 m_xml.scopedElement(
"StdErr" ).writeText(
trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17165 m_xml.endElement();
17168 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17169 StreamingReporterBase::testGroupEnded( testGroupStats );
17171 m_xml.scopedElement(
"OverallResults" )
17172 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17173 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17174 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17175 m_xml.endElement();
17178 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17179 StreamingReporterBase::testRunEnded( testRunStats );
17180 m_xml.scopedElement(
"OverallResults" )
17181 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17182 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17183 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17184 m_xml.endElement();
17187 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17188 void XmlReporter::benchmarkPreparing(
std::string const& name) {
17189 m_xml.startElement(
"BenchmarkResults")
17190 .writeAttribute(
"name", name);
17193 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &
info) {
17194 m_xml.writeAttribute(
"samples", info.samples)
17195 .writeAttribute(
"resamples", info.resamples)
17196 .writeAttribute(
"iterations", info.iterations)
17197 .writeAttribute(
"clockResolution", info.clockResolution)
17198 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17199 .writeComment(
"All values in nano seconds");
17202 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17203 m_xml.startElement(
"mean")
17204 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17205 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17206 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17207 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17208 m_xml.endElement();
17209 m_xml.startElement(
"standardDeviation")
17210 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17211 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17212 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17213 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17214 m_xml.endElement();
17215 m_xml.startElement(
"outliers")
17216 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17217 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17218 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17219 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17220 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17221 m_xml.endElement();
17222 m_xml.endElement();
17226 m_xml.scopedElement(
"failed").
17227 writeAttribute(
"message", error);
17228 m_xml.endElement();
17230 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17232 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17236 #if defined(_MSC_VER) 17237 #pragma warning(pop) 17242 LeakDetector leakDetector;
17246 #pragma clang diagnostic pop 17252 #ifdef CATCH_CONFIG_MAIN 17257 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) 17259 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17262 int main (
int argc,
char * argv[]) {
17265 return Catch::Session().run( argc, argv );
17271 int main (
int argc,
char *
const argv[]) {
17272 #if !CATCH_ARC_ENABLED 17273 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17276 Catch::registerTestMethods();
17277 int result = Catch::Session().run( argc, (
char**)argv );
17279 #if !CATCH_ARC_ENABLED 17291 #if !defined(CATCH_CONFIG_IMPL_ONLY) 17293 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED 17294 # undef CLARA_CONFIG_MAIN 17297 #if !defined(CATCH_CONFIG_DISABLE) 17300 #ifdef CATCH_CONFIG_PREFIX_ALL 17302 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17303 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17305 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17306 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17307 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17308 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17309 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17310 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17311 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17313 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17314 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17315 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17316 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17317 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17319 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17320 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17321 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17322 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17323 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17324 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17325 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17327 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17328 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17330 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17331 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17333 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) 17334 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg ) 17335 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17336 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) 17338 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17339 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17340 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17341 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17342 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17343 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17344 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17345 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17346 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17348 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17350 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17351 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17352 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17353 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17354 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17355 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17356 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17357 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17358 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17360 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17361 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17362 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17363 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17364 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17365 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17366 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17367 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17370 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17371 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) 17372 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) 17374 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) 17375 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) 17379 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) 17380 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17381 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17382 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17383 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17384 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17385 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17386 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17388 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17389 #define CATCH_BENCHMARK(...) \ 17390 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__,,)) 17391 #define CATCH_BENCHMARK_ADVANCED(name) \ 17392 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) 17393 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17398 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17399 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17401 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17402 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17403 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17404 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17405 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17406 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17407 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17409 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17410 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17411 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17412 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17413 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17415 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17416 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17417 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17418 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17419 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17420 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17421 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17423 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17424 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17426 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17427 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17429 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) 17430 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) 17431 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17432 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) 17434 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17435 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17436 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17437 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17438 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17439 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17440 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17441 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17442 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17443 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17445 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17446 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17447 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17448 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17449 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17450 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17451 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17452 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17453 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17454 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) 17455 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17457 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17458 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17459 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17460 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17461 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17462 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17463 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17464 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17465 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) 17466 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17469 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17470 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) 17471 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) 17473 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) 17474 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) 17479 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) 17482 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) 17483 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17485 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17486 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17487 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17488 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17489 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17490 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17492 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17493 #define 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 BENCHMARK_ADVANCED(name) \ 17496 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) 17497 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17501 #else // CATCH_CONFIG_DISABLE 17505 #ifdef CATCH_CONFIG_PREFIX_ALL 17507 #define CATCH_REQUIRE( ... ) (void)(0) 17508 #define CATCH_REQUIRE_FALSE( ... ) (void)(0) 17510 #define CATCH_REQUIRE_THROWS( ... ) (void)(0) 17511 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17512 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17513 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17514 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17515 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17516 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) 17518 #define CATCH_CHECK( ... ) (void)(0) 17519 #define CATCH_CHECK_FALSE( ... ) (void)(0) 17520 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) 17521 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17522 #define CATCH_CHECK_NOFAIL( ... ) (void)(0) 17524 #define CATCH_CHECK_THROWS( ... ) (void)(0) 17525 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17526 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17527 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17528 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17529 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17530 #define CATCH_CHECK_NOTHROW( ... ) (void)(0) 17532 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17533 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0) 17535 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) 17536 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17538 #define CATCH_INFO( msg ) (void)(0) 17539 #define CATCH_UNSCOPED_INFO( msg ) (void)(0) 17540 #define CATCH_WARN( msg ) (void)(0) 17541 #define CATCH_CAPTURE( msg ) (void)(0) 17543 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17544 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17545 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) 17546 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) 17547 #define CATCH_SECTION( ... ) 17548 #define CATCH_DYNAMIC_SECTION( ... ) 17549 #define CATCH_FAIL( ... ) (void)(0) 17550 #define CATCH_FAIL_CHECK( ... ) (void)(0) 17551 #define CATCH_SUCCEED( ... ) (void)(0) 17553 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17555 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17556 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17557 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17558 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17559 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17560 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17561 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17562 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17563 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17565 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17566 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17567 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17568 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17569 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17570 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17571 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17572 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17576 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17577 #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 ) 17578 #define CATCH_GIVEN( desc ) 17579 #define CATCH_AND_GIVEN( desc ) 17580 #define CATCH_WHEN( desc ) 17581 #define CATCH_AND_WHEN( desc ) 17582 #define CATCH_THEN( desc ) 17583 #define CATCH_AND_THEN( desc ) 17585 #define CATCH_STATIC_REQUIRE( ... ) (void)(0) 17586 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) 17591 #define REQUIRE( ... ) (void)(0) 17592 #define REQUIRE_FALSE( ... ) (void)(0) 17594 #define REQUIRE_THROWS( ... ) (void)(0) 17595 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17596 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17597 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17598 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17599 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17600 #define REQUIRE_NOTHROW( ... ) (void)(0) 17602 #define CHECK( ... ) (void)(0) 17603 #define CHECK_FALSE( ... ) (void)(0) 17604 #define CHECKED_IF( ... ) if (__VA_ARGS__) 17605 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17606 #define CHECK_NOFAIL( ... ) (void)(0) 17608 #define CHECK_THROWS( ... ) (void)(0) 17609 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17610 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17611 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17612 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17613 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17614 #define CHECK_NOTHROW( ... ) (void)(0) 17616 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17617 #define CHECK_THAT( arg, matcher ) (void)(0) 17619 #define REQUIRE_THAT( arg, matcher ) (void)(0) 17620 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17622 #define INFO( msg ) (void)(0) 17623 #define UNSCOPED_INFO( msg ) (void)(0) 17624 #define WARN( msg ) (void)(0) 17625 #define CAPTURE( msg ) (void)(0) 17627 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17628 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17629 #define METHOD_AS_TEST_CASE( method, ... ) 17630 #define REGISTER_TEST_CASE( Function, ... ) (void)(0) 17631 #define SECTION( ... ) 17632 #define DYNAMIC_SECTION( ... ) 17633 #define FAIL( ... ) (void)(0) 17634 #define FAIL_CHECK( ... ) (void)(0) 17635 #define SUCCEED( ... ) (void)(0) 17636 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17638 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17639 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17640 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17641 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17642 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17643 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17644 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17645 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17646 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17648 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17649 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17650 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17651 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17652 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17653 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17654 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17655 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17658 #define STATIC_REQUIRE( ... ) (void)(0) 17659 #define STATIC_REQUIRE_FALSE( ... ) (void)(0) 17663 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 17666 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) 17667 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) 17669 #define GIVEN( desc ) 17670 #define AND_GIVEN( desc ) 17671 #define WHEN( desc ) 17672 #define AND_WHEN( desc ) 17673 #define THEN( desc ) 17674 #define AND_THEN( desc ) 17680 #endif // ! CATCH_CONFIG_IMPL_ONLY 17686 # ifdef __ICC // icpc defines the __clang__ macro 17687 # pragma warning(pop) 17689 # pragma clang diagnostic pop 17691 #elif defined __GNUC__ 17692 # pragma GCC diagnostic pop 17697 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define CATCH_INTERNAL_ERROR(...)
static std::string convert(T const (&arr)[SZ])
virtual T const & get() const =0
const char * const_iterator
virtual void setGenerator(Generators::GeneratorBasePtr &&generator)=0
GLenum GLuint GLenum GLsizei const GLchar * message
virtual ~IGeneratorTracker()
void handleExpression(ITransientExpression const &expr)
bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config)
GeneratorWrapper< T > values(std::initializer_list< T > values)
auto getResult() const -> bool
Totals & operator+=(Totals const &other)
ChunkGenerator(size_t size, GeneratorWrapper< T > generator)
Option(Option const &_other)
std::vector< MatcherBase< ArgT > const * > m_matchers
GLboolean GLboolean GLboolean b
std::unique_ptr< T > make_unique(Args &&...args)
std::string rawMemoryToString(const T &object)
std::unique_ptr< GeneratorUntypedBase > GeneratorBasePtr
FixedValuesGenerator(std::initializer_list< T > values)
CaseSensitive::Choice m_caseSensitivity
bool isFalseTest(int flags)
IteratorGenerator(InputIterator first, InputSentinel last)
ExceptionTranslatorRegistrar(std::string(*translateFunction)(T &))
GLenum GLsizei const void * pointer
TestCase(ITestInvoker *testCase, TestCaseInfo &&info)
boost_foreach_argument_dependent_lookup_hack tag
std::string m_description
GLenum GLenum GLsizei void * row
const char * what() const noexceptoverridefinal
bool operator<(TestCase const &other) const
EqualsMatcher(std::vector< T, AllocComp > const &comparator)
static std::enable_if<!::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
typedef void(APIENTRY *GLDEBUGPROC)(GLenum source
virtual void registerTest(TestCase const &testInfo)=0
GLuint const GLchar * name
Option & operator=(Option const &_other)
std::string toString() const
void toLowerInPlace(std::string &s)
auto substr(size_type start, size_type length) const noexcept-> StringRef
virtual StartupExceptionRegistry const & getStartupExceptionRegistry() const =0
GLdouble GLdouble GLint GLint order
static void moveToParent(BtCursor *pCur)
std::shared_ptr< ITestInvoker > test
void handleMessage(ResultWas::OfType resultType, StringRef const &message)
void handleExceptionNotThrownAsExpected()
LazyExpression(bool isNegated)
auto c_str() const -> char const *
ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs)
TestCase makeTestCase(ITestInvoker *testCase, std::string const &className, NameAndTags const &nameAndTags, SourceLineInfo const &lineInfo)
bool operator==(const plane &lhs, const plane &rhs)
void throw_runtime_error(std::string const &msg)
bool operator!=(failed, failed)
std::ostream & operator<<(std::ostream &os, SourceLineInfo const &info)
virtual void registerTagAlias(std::string const &alias, std::string const &tag, SourceLineInfo const &lineInfo)=0
GeneratorWrapper< std::tuple< Ts... > > table(std::initializer_list< std::tuple< typename std::decay< Ts >::type... >> tuples)
virtual auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker &=0
bool contains(std::string const &s, std::string const &infix)
Exception::ExceptionMessageMatcher Message(std::string const &message)
bool match(T const &item) const override
CaseSensitive::Choice m_caseSensitivity
void validate(std::vector< std::vector< rs2::stream_profile >> frames, std::vector< std::vector< double >> timestamps, device_profiles requests, int actual_fps)
PredicateMatcher(std::function< bool(T const &)> const &elem, std::string const &descr)
auto makeUnaryExpr() const -> UnaryExpr< LhsT >
std::string describe() const override
bool expectedToFail() const
std::vector< StringRef > splitStringRef(StringRef str, char delimiter)
GeneratorWrapper< T > m_generator
virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory)=0
virtual IConfigPtr const & getConfig() const =0
auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool
std::vector< std::pair< int, StringRef > > m_values
constexpr auto isNullTerminated() const noexcept-> bool
auto getCurrentNanosecondsSinceEpoch() -> uint64_t
T const & operator+(T const &value, StreamEndStop)
auto getEstimatedClockResolution() -> uint64_t
std::string describe() const override
integral_constant< bool, false > false_type
#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
SpecialProperties properties
bool match(ArgT const &arg) const override
T valueOr(T const &defaultValue) const
GeneratorWrapper(std::unique_ptr< IGenerator< T >> generator)
GeneratorWrapper< U > m_generator
Detail::EnumInfo const & registerEnum(StringRef enumName, StringRef allEnums, std::initializer_list< E > values)
::sensor_msgs::Range_< std::allocator< void > > Range
TestInvokerAsMethod(void(C::*testAsMethod)()) noexcept
SourceLineInfo(char const *_file, std::size_t _line) noexcept
virtual void popScopedMessage(MessageInfo const &message)=0
IResultCapture & getResultCapture()
std::string tagsAsString() const
bool operator&&(d400_caps l, d400_caps r)
ImVec4 operator*(const ImVec4 &color, float t)
Approx & epsilon(T const &newEpsilon)
Capturer(StringRef macroName, SourceLineInfo const &lineInfo, ResultWas::OfType resultType, StringRef names)
T const & operator*() const
std::vector< std::string > lcaseTags
GeneratorWrapper< T > value(T &&value)
StdString::RegexMatcher Matches(std::string const ®ex, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::string describe() const override
GeneratorWrapper< std::vector< T > > chunk(size_t size, GeneratorWrapper< T > &&generator)
auto data() const noexcept-> char const *
virtual auto hasGenerator() const -> bool=0
SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name)
virtual RunTests::InWhatOrder runOrder() const =0
Easylogging++ entry namespace.
bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis)
GLenum GLenum GLsizei void GLsizei void * column
void convert(rs2_format source, std::string &target)
virtual std::vector< TestCase > const & getAllTestsSorted(IConfig const &config) const =0
std::string finalizeDescription(const std::string &desc)
bool operator==(SourceLineInfo const &other) const noexcept
Approx operator()(T const &value)
constexpr const_iterator end() const
virtual void handleFatalErrorCondition(StringRef message)=0
GLdouble GLdouble GLdouble w
GeneratorWrapper< T > m_generator
std::enable_if< std::is_floating_point< T >::value, GeneratorWrapper< T > >::type random(T a, T b)
GLsizei const GLchar *const * string
IMGUI_API void Indent(float indent_w=0.0f)
std::uniform_int_distribution< Integer > m_dist
virtual auto getGenerator() const -> Generators::GeneratorBasePtr const &=0
std::vector< std::unique_ptr< IExceptionTranslator const >> ExceptionTranslators
StringRef(std::string const &stdString) noexcept
std::vector< std::string > tags
std::array< point3d, 4 > object
GLfloat GLfloat GLfloat GLfloat h
static std::string convert(signed char const *str)
IMutableRegistryHub & getMutableRegistryHub()
Counts & operator+=(Counts const &other)
std::string(*)( exceptionTranslateFunction)
bool operator>(failed, failed)
#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
void formatReconstructedExpression(std::ostream &os, std::string const &lhs, StringRef op, std::string const &rhs)
bool empty() const noexcept
ITransientExpression(bool isBinaryExpression, bool result)
GeneratorWrapper< ResultType > from_range(Container const &cnt)
ScopedMessage(MessageBuilder const &builder)
std::string stringify(const T &e)
StdString::EqualsMatcher Equals(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
void sort(sort_type m_sort_type, const std::string &in, const std::string &out)
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
bool operator==(TestCase const &other) const
virtual ~IMutableEnumValuesRegistry()
static std::string convert(U *p)
virtual void registerStartupException() noexcept=0
std::vector< GeneratorWrapper< T > > m_generators
virtual void pushScopedMessage(MessageInfo const &message)=0
virtual ~ITestCaseRegistry()
ApproxMatcher(std::vector< T, AllocComp > const &comparator)
Vector::EqualsMatcher< T, AllocComp, AllocMatch > Equals(std::vector< T, AllocComp > const &comparator)
Vector::ContainsElementMatcher< T, Alloc > VectorContains(T const &comparator)
auto getElapsedSeconds() const -> double
GeneratorWrapper< T > filter(Predicate &&pred, GeneratorWrapper< T > &&generator)
rs2rosinternal::Time * timeStamp(M &m)
returns TimeStamp<M>::pointer(m);
ResultDisposition::Flags resultDisposition
std::vector< TestCase > const & getAllTestCasesSorted(IConfig const &config)
ExceptionTranslator(std::string(*translateFunction)(T &))
GLboolean GLboolean GLboolean GLboolean a
void streamReconstructedExpression(std::ostream &os) const override
bool shouldContinueOnFailure(int flags)
::std_msgs::Duration_< std::allocator< void > > Duration
auto str() const -> std::string
d400_caps & operator|=(d400_caps &lhs, d400_caps rhs)
std::string operator+() const
UnorderedEqualsMatcher(std::vector< T, AllocComp > const &target)
def info(name, value, persistent=False)
Generators(Gs &&...moreGenerators)
std::function< void(std::function< void()>)> invoker
bool isJustInfo(int flags)
GeneratorWrapper< T > m_generator
GeneratorException(const char *msg)
AutoReg(ITestInvoker *invoker, SourceLineInfo const &lineInfo, StringRef const &classOrMethod, NameAndTags const &nameAndTags) noexcept
constexpr const_iterator begin() const
static T parse(const mxArray *cell)
void captureValues(size_t index, T const &value, Ts const &...values)
static std::string convert(R const &range)
GeneratorWrapper< T > range(T const &start, T const &end)
std::vector< TestCase > filterTests(std::vector< TestCase > const &testCases, TestSpec const &testSpec, IConfig const &config)
bool match(std::vector< T, AllocMatch > const &v) const override
AssertionReaction m_reaction
Vector::ContainsMatcher< T, AllocComp, AllocMatch > Contains(std::vector< T, AllocComp > const &comparator)
std::uniform_real_distribution< Float > m_dist
AssertionInfo m_assertionInfo
ApproxMatcher & margin(T const &newMargin)
void handleUnexpectedInflightException()
Floating::WithinAbsMatcher WithinAbs(double target, double margin)
Approx & scale(T const &newScale)
void populate(GeneratorWrapper< T > &&generator)
Totals delta(Totals const &prevTotals) const
static std::string convert(R C::*p)
StringRef m_matcherString
BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
AssertionHandler(StringRef const ¯oName, SourceLineInfo const &lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition)
StringRef capturedExpression
bool shouldSuppressFailure(int flags)
GLenum GLint GLint * precision
std::shared_ptr< IReporterFactory > IReporterFactoryPtr
StdString::EndsWithMatcher EndsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::string describe() const override
auto makeGenerators(as< T >, U &&val, Gs &&...moreGenerators) -> Generators< T >
virtual ~IExceptionTranslatorRegistry()
ContainsMatcher(std::vector< T, AllocComp > const &comparator)
auto makeTestInvoker(void(*testAsFunction)()) noexcept-> ITestInvoker *
virtual bool allowThrows() const =0
bool isOk(ResultWas::OfType resultType)
virtual void registerTranslator(const IExceptionTranslator *translator)=0
bool match(std::vector< T, Alloc > const &v) const override
ReusableStringStream m_stream
virtual int benchmarkSamples() const =0
float3 operator-(const float3 &a, const float3 &b)
virtual ~ITransientExpression()
GeneratorWrapper< T > m_generator
bool operator<(SourceLineInfo const &other) const noexcept
void handleThrowingCallSkipped()
void handleExceptionThrownAsExpected()
std::unique_ptr< IGenerator< T > > m_generator
bool match(std::vector< T, AllocMatch > const &v) const override
virtual std::string translateActiveException() const =0
bool operator<(failed, failed)
Catch::SimplePcg32 & m_rng
void captureValues(size_t index, T const &value)
def run(include_folder_path, addon_folder_path)
std::string trim(std::string const &str)
Returns a new string without whitespace at the start/end.
bool endsWith(std::string const &s, std::string const &suffix)
#define CATCH_INTERNAL_LINEINFO
static std::string convert(char const *str)
std::vector< T, AllocComp > const & m_comparator
#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
void populate(U &&valueOrGenerator, Gs &&...moreGenerators)
std::vector< T > m_returned
static void abort(int status, const std::string &reason)
Aborts application due with user-defined status.
T && forward(typename::boost::move_detail::remove_reference< T >::type &t) BOOST_NOEXCEPT
SingleValueGenerator(T &&value)
unsigned __int64 uint64_t
std::string toLower(std::string const &s)
BOOST_DEDUCED_TYPENAME optional< T >::reference_const_type get(optional< T > const &opt)
bool match(std::vector< T, AllocMatch > const &vec) const override
bool isThrowSafe(TestCase const &testCase, IConfig const &config)
static std::string custom
IMGUI_API void Value(const char *prefix, bool b)
std::string translateActiveException()
constexpr auto empty() const noexcept-> bool
virtual ~IMutableContext()
virtual void streamReconstructedExpression(std::ostream &os) const =0
TestCase withName(std::string const &_newName) const
static std::string print(const transformation &tf)
std::vector< T, AllocComp > const & m_comparator
bool equalityComparisonImpl(double other) const
std::enable_if< !std::is_enum< T >::value &&!std::is_base_of< std::exception, T >::value, std::string >::type convertUnstreamable(T const &)
virtual ITestCaseRegistry const & getTestCaseRegistry() const =0
void handleExpr(ExprLhs< T > const &expr)
bool match(ArgT const &arg) const override
ContainsElementMatcher(T const &comparator)
void discard(uint64_t skip)
std::size_t total() const
IContext & getCurrentContext()
typename std::remove_reference< typename std::remove_cv< typename std::result_of< Func(U)>::type >::type >::type FunctionReturnType
void throw_logic_error(std::string const &msg)
bool match(ArgT const &arg) const override
auto operator+=(std::string &lhs, StringRef const &sr) -> std::string &
auto generate(SourceLineInfo const &lineInfo, L const &generatorExpression) -> decltype(std::declval< decltype(generatorExpression())>().get())
GeneratorWrapper< T > repeat(size_t repeats, GeneratorWrapper< T > &&generator)
RegistrarForTagAliases(char const *alias, char const *tag, SourceLineInfo const &lineInfo)
RangeGenerator(T const &start, T const &end, T const &step)
std::chrono::duration< uint64_t, std::nano > nanoseconds
virtual double benchmarkConfidenceInterval() const =0
static const textual_icon times
virtual ~IMutableRegistryHub()
MessageBuilder(StringRef const ¯oName, SourceLineInfo const &lineInfo, ResultWas::OfType type)
std::string describe() const override
IResultCapture & m_resultCapture
void throw_exception(std::exception const &e)
static unsigned int globalCount
ApproxMatcher & epsilon(T const &newEpsilon)
GLsizei const GLfloat * values
d400_caps operator&(const d400_caps lhs, const d400_caps rhs)
auto getElapsedNanoseconds() const -> uint64_t
virtual void registerListener(IReporterFactoryPtr const &factory)=0
boost::move_detail::add_rvalue_reference< T >::type declval()
void streamReconstructedExpression(std::ostream &os) const override
void next(auto_any_t cur, type2type< T, C > *)
std::string translate(ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd) const override
void seed(result_type seed_)
TestCaseInfo const & getTestCaseInfo() const
auto getElapsedMicroseconds() const -> uint64_t
MapGenerator(F2 &&function, GeneratorWrapper< U > &&generator)
const std::string unprintableString
constexpr auto size() const noexcept-> size_type
GLdouble GLdouble GLdouble q
void construct(Factory const &factory, void *address)
static std::enable_if<::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
#define CATCH_ENFORCE(condition,...)
virtual void handleIncomplete(AssertionInfo const &info)=0
std::string rangeToString(std::vector< bool, Allocator > const &v)
auto isBinaryExpression() const -> bool
ApproxMatcher & scale(T const &newScale)
virtual std::chrono::milliseconds benchmarkWarmupTime() const =0
MessageInfo(StringRef const &_macroName, SourceLineInfo const &_lineInfo, ResultWas::OfType _type)
std::string m_cachedToString
bool match(std::vector< T, AllocMatch > const &v) const override
Section(SectionInfo const &info)
void log(std::string message)
GLuint GLsizei const GLchar * label
virtual IReporterRegistry const & getReporterRegistry() const =0
bool operator>=(failed, failed)
std::vector< MatcherBase< ArgT > const * > m_matchers
virtual IResultCapture * getResultCapture()=0
auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker &
std::string describe() const override
auto operator==(StringRef const &other) const noexcept-> bool
FilterGenerator(P &&pred, GeneratorWrapper< T > &&generator)
virtual unsigned int rngSeed() const =0
const T * operator->() const
auto makeMatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString) -> MatchExpr< ArgT, MatcherT >
RandomIntegerGenerator(Integer a, Integer b)
typename::boost::move_detail::remove_reference< T >::type && move(T &&t) BOOST_NOEXCEPT
StdString::StartsWithMatcher StartsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::vector< T, AllocComp > const & m_target
std::enable_if< std::is_enum< T >::value, std::string >::type convertUnstreamable(T const &value)
Approx & margin(T const &newMargin)
std::string convertUnknownEnumToString(E e)
GLsizei GLsizei GLchar * source
bool operator==(MessageInfo const &other) const
ExceptionMessageMatcher(std::string const &message)
std::string describe() const override
RepeatGenerator(size_t repeats, GeneratorWrapper< T > &&generator)
std::function< bool(T const &)> m_predicate
bool operator<(MessageInfo const &other) const
virtual void sectionEnded(SectionEndInfo const &endInfo)=0
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff)
static void terminate(void)
void throw_domain_error(std::string const &msg)
void handleExceptionMatchExpr(AssertionHandler &handler, std::string const &str, StringRef const &matcherString)
Catch::SimplePcg32 & m_rng
Totals operator-(Totals const &other) const
MatcherBase< ArgT > const & m_underlyingMatcher
int main(int argv, const char **argc)
GLenum GLuint GLenum GLsizei length
#define CATCH_RUNTIME_ERROR(...)
static IMutableContext * currentContext
virtual IExceptionTranslatorRegistry const & getExceptionTranslatorRegistry() const =0
IMutableContext & getCurrentMutableContext()
Counts operator-(Counts const &other) const
void streamReconstructedExpression(std::ostream &os) const override
IRegistryHub const & getRegistryHub()
virtual ~IExceptionTranslator()
std::uint32_t result_type
GLuint GLenum GLenum transform
Generic::PredicateMatcher< T > Predicate(std::function< bool(T const &)> const &predicate, std::string const &description="")
::rosgraph_msgs::Clock_< std::allocator< void > > Clock
void handleUnexpectedExceptionNotThrown()
static const textual_icon measure
virtual bool benchmarkNoAnalysis() const =0
auto compareEqual(LhsT const &lhs, RhsT const &rhs) -> bool
void captureValue(size_t index, std::string const &value)
std::shared_ptr< IConfig const > IConfigPtr
MatchNotOf(MatcherBase< ArgT > const &underlyingMatcher)
virtual void sectionEndedEarly(SectionEndInfo const &endInfo)=0
ITransientExpression const * m_transientExpression
std::vector< T > m_values
std::string describe() const override
virtual ~IResultCapture()
std::string describe() const override
MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
RandomFloatingGenerator(Float a, Float b)
IMGUI_API void Columns(int count=1, const char *id=NULL, bool border=true)
virtual void setConfig(IConfigPtr const &config)=0
boost::iterators::detail::postfix_increment_result< I, V, R, TC >::type operator++(iterator_facade< I, V, TC, R, D > &i, int)
static void createContext()
virtual unsigned int benchmarkResamples() const =0
std::string rangeToString(Range const &range)
void invoke() const override
Vector::ApproxMatcher< T, AllocComp, AllocMatch > Approx(std::vector< T, AllocComp > const &comparator)
auto makeStream(StringRef const &filename) -> IStream const *
static std::string convert(unsigned char const *str)
integral_constant< bool, true > true_type
GeneratorWrapper< T > map(Func &&function, GeneratorWrapper< U > &&generator)
auto allowThrows() const -> bool
TestCaseInfo(std::string const &_name, std::string const &_className, std::string const &_description, std::vector< std::string > const &_tags, SourceLineInfo const &_lineInfo)
virtual ITagAliasRegistry const & getTagAliasRegistry() const =0
std::vector< T, AllocComp > const & m_comparator
constexpr StringRef() noexcept=default
#define CATCH_CATCH_ANON(type)
pluralise(std::size_t count, std::string const &label)
bool m_isBinaryExpression
void copy(void *dst, void const *src, size_t size)
auto get() -> std::ostream &
bool operator<=(failed, failed)
std::vector< MessageInfo > m_messages
GeneratorWrapper< T > take(size_t target, GeneratorWrapper< T > &&generator)
Vector::UnorderedEqualsMatcher< T, AllocComp, AllocMatch > UnorderedEquals(std::vector< T, AllocComp > const &target)
TakeGenerator(size_t target, GeneratorWrapper< T > &&generator)
bool startsWith(std::string const &s, std::string const &prefix)
Floating::WithinRelMatcher WithinRel(float target)
std::string to_string(T value)
RangeGenerator(T const &start, T const &end)
auto getElapsedMilliseconds() const -> unsigned int