11 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED 12 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED 16 #define CATCH_VERSION_MAJOR 2 17 #define CATCH_VERSION_MINOR 13 18 #define CATCH_VERSION_PATCH 7 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) 72 # include <TargetConditionals.h> 73 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ 74 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) 75 # define CATCH_PLATFORM_MAC 76 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) 77 # define CATCH_PLATFORM_IPHONE 80 #elif defined(linux) || defined(__linux) || defined(__linux__) 81 # define CATCH_PLATFORM_LINUX 83 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) 84 # define CATCH_PLATFORM_WINDOWS 90 # ifndef CLARA_CONFIG_MAIN 91 # define CLARA_CONFIG_MAIN_NOT_DEFINED 92 # define CLARA_CONFIG_MAIN 128 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) 129 # define CATCH_CPP14_OR_GREATER 132 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) 133 # define CATCH_CPP17_OR_GREATER 140 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) 141 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) 142 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) 144 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) 148 #if defined(__clang__) 150 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) 151 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) 164 # if !defined(__ibmxl__) && !defined(__CUDACC__) 165 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) 168 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 169 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ 170 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") 172 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 173 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) 175 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 176 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) 178 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 179 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) 181 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 182 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) 188 #if !defined(CATCH_PLATFORM_WINDOWS) 189 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS 194 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) 195 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS 199 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS 200 # define CATCH_CONFIG_COLOUR_NONE 205 #if defined(__ANDROID__) 206 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING 207 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE 212 #if defined(__MINGW32__) 213 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH 218 #if defined(__ORBIS__) 219 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE 231 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ 232 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) 234 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING 241 #if defined(_MSC_VER) 243 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) 244 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) 248 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) 249 # define CATCH_CONFIG_COLOUR_NONE 251 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH 257 # if !defined(__clang__) // Handle Clang masquerading for msvc 258 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) 259 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 260 # endif // MSVC_TRADITIONAL 265 #if defined(_REENTRANT) || defined(_MSC_VER) 267 # define CATCH_INTERNAL_CONFIG_USE_ASYNC 272 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) 273 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED 279 # define CATCH_INTERNAL_CONFIG_NO_WCHAR 284 #if defined(__BORLANDC__) 285 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN 295 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) 296 #define CATCH_INTERNAL_CONFIG_COUNTER 304 #if defined(UNDER_RTSS) || defined(RTX64_BUILD) 305 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH 306 #define CATCH_INTERNAL_CONFIG_NO_ASYNC 307 #define CATCH_CONFIG_COLOUR_NONE 310 #if !defined(_GLIBCXX_USE_C99_MATH_TR1) 311 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER 315 #if defined(__has_include) 317 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) 318 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW 322 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 323 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL 324 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 327 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 329 # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) 330 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE 332 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 335 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) 336 # if defined(__clang__) && (__clang_major__ < 8) 340 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) 341 # define CATCH_CONFIG_NO_CPP17_VARIANT 343 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT 344 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) 346 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT 347 # endif // defined(__clang__) && (__clang_major__ < 8) 348 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) 349 #endif // defined(__has_include) 351 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) 352 # define CATCH_CONFIG_COUNTER 354 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) 355 # define CATCH_CONFIG_WINDOWS_SEH 358 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) 359 # define CATCH_CONFIG_POSIX_SIGNALS 362 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) 363 # define CATCH_CONFIG_WCHAR 366 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) 367 # define CATCH_CONFIG_CPP11_TO_STRING 370 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) 371 # define CATCH_CONFIG_CPP17_OPTIONAL 374 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) 375 # define CATCH_CONFIG_CPP17_STRING_VIEW 378 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) 379 # define CATCH_CONFIG_CPP17_VARIANT 382 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) 383 # define CATCH_CONFIG_CPP17_BYTE 386 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 387 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE 390 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) 391 # define CATCH_CONFIG_NEW_CAPTURE 394 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 395 # define CATCH_CONFIG_DISABLE_EXCEPTIONS 398 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) 399 # define CATCH_CONFIG_POLYFILL_ISNAN 402 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) 403 # define CATCH_CONFIG_USE_ASYNC 406 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) 407 # define CATCH_CONFIG_ANDROID_LOGWRITE 410 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 411 # define CATCH_CONFIG_GLOBAL_NEXTAFTER 416 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) 417 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION 419 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) 420 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 422 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) 423 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS 425 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) 426 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS 428 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) 429 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS 431 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) 432 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS 437 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) 438 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) 441 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) 442 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 443 #elif defined(__clang__) && (__clang_major__ < 5) 444 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 447 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) 448 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 451 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 452 #define CATCH_TRY if ((true)) 453 #define CATCH_CATCH_ALL if ((false)) 454 #define CATCH_CATCH_ANON(type) if ((false)) 456 #define CATCH_TRY try 457 #define CATCH_CATCH_ALL catch (...) 458 #define CATCH_CATCH_ANON(type) catch (type) 461 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) 462 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 466 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line 467 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) 468 #ifdef CATCH_CONFIG_COUNTER 469 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) 471 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) 513 bool empty() const noexcept {
return file[0] ==
'\0'; }
541 #define CATCH_INTERNAL_LINEINFO \ 542 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) 553 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ 554 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 555 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 556 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ 557 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 571 virtual void invoke ()
const = 0;
580 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
581 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const = 0;
586 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
610 static constexpr
char const*
const s_empty =
"";
612 char const* m_start = s_empty;
616 constexpr
StringRef() noexcept = default;
618 StringRef(
char const* rawChars ) noexcept;
621 : m_start( rawChars ),
626 : m_start( stdString.c_str() ),
627 m_size( stdString.size() )
630 explicit operator std::string()
const {
631 return std::string(m_start, m_size);
635 auto operator == (
StringRef const& other )
const noexcept -> bool;
636 auto operator != (
StringRef const& other)
const noexcept ->
bool {
637 return !(*
this == other);
640 auto operator[] (
size_type index )
const noexcept ->
char {
641 assert(index < m_size);
642 return m_start[index];
646 constexpr
auto empty() const noexcept ->
bool {
655 auto c_str()
const ->
char const*;
664 auto data()
const noexcept ->
char const*;
667 return m_start[m_size] ==
'\0';
678 constexpr
auto operator "" _sr(
char const* rawChars, std::size_t size ) noexcept ->
StringRef {
683 constexpr
auto operator "" _catch_sr(
char const* rawChars, std::size_t size ) noexcept ->
Catch::StringRef {
691 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ 692 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) 693 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) 694 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) 695 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) 696 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) 698 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 699 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ 701 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) 702 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) 704 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) 707 #define CATCH_REC_END(...) 708 #define CATCH_REC_OUT 710 #define CATCH_EMPTY() 711 #define CATCH_DEFER(id) id CATCH_EMPTY() 713 #define CATCH_REC_GET_END2() 0, CATCH_REC_END 714 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 715 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 716 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT 717 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) 718 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) 720 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 721 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) 722 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 724 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) 725 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) 726 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) 731 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 733 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 735 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) 736 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ 737 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ 738 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF 739 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) 740 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 741 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ 742 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) 745 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) 746 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ 747 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) 750 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ 751 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) 753 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) 755 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 756 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) 757 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) 759 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())) 760 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) 763 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ 764 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) 766 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) 767 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) 768 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) 769 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) 770 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) 771 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) 772 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) 773 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) 774 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) 775 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) 776 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) 778 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N 780 #define INTERNAL_CATCH_TYPE_GEN\ 781 template<typename...> struct TypeList {};\ 782 template<typename...Ts>\ 783 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\ 784 template<template<typename...> class...> struct TemplateTypeList{};\ 785 template<template<typename...> class...Cs>\ 786 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\ 787 template<typename...>\ 789 template<typename...>\ 791 template<template<typename...> class, typename...>\ 793 template<template<typename...> class, typename>\ 796 template<typename T> \ 797 struct append<T> { using type = T; };\ 798 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\ 799 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\ 800 template< template<typename...> class L1, typename...E1, typename...Rest>\ 801 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\ 803 template< template<typename...> class Container, template<typename...> class List, typename...elems>\ 804 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\ 805 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\ 806 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\ 808 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\ 809 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\ 810 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\ 811 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; }; 813 #define INTERNAL_CATCH_NTTP_1(signature, ...)\ 814 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\ 815 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 816 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \ 817 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\ 818 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\ 819 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \ 821 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 822 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\ 823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\ 824 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\ 825 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\ 826 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; }; 828 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName) 829 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\ 830 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 831 static void TestName() 832 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\ 833 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 834 static void TestName() 836 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName) 837 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\ 838 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 839 static void TestName() 840 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\ 841 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 842 static void TestName() 844 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\ 845 template<typename Type>\ 846 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\ 848 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 851 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\ 852 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 853 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\ 855 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 858 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\ 859 template<typename Type>\ 860 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 862 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 865 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\ 866 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 867 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 869 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 872 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName) 873 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\ 874 template<typename TestType> \ 875 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ 879 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\ 880 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 881 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ 885 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName) 886 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\ 887 template<typename TestType> \ 888 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test() 889 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\ 890 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 891 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test() 893 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 894 #define INTERNAL_CATCH_NTTP_0 895 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0) 896 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__) 897 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__) 898 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__) 899 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__) 900 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__) 901 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__) 902 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__) 904 #define INTERNAL_CATCH_NTTP_0(signature) 905 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__)) 906 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)) 907 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)) 908 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)) 909 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)) 910 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)) 911 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)) 912 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)) 919 #include <type_traits> 927 template <
typename Fun,
typename... Args>
929 template <
typename...>
930 std::false_type
static test(...);
933 template <
typename T>
936 template <
typename Fun,
typename... Args>
937 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
939 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 942 template <
typename Func,
typename... U>
943 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
946 template <
typename Func,
typename... U>
947 using FunctionReturnType =
typename std::remove_reference<
typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
961 void (C::*m_testAsMethod)();
967 (obj.*m_testAsMethod)();
991 #if defined(CATCH_CONFIG_DISABLE) 992 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ 993 static void TestName() 994 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ 996 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1000 void TestName::test() 1001 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \ 1002 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1003 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1005 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1006 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1009 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1011 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1012 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1013 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) 1015 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1016 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) 1019 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1020 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1021 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) 1023 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1024 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) 1027 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1028 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1029 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) 1031 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1032 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) 1035 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1036 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1037 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) 1039 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1040 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) 1045 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ 1046 static void TestName(); \ 1047 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1048 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1049 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1050 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1051 static void TestName() 1052 #define INTERNAL_CATCH_TESTCASE( ... ) \ 1053 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) 1056 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ 1057 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1058 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1059 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1060 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1063 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ 1064 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1065 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1067 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1070 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \ 1072 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1073 void TestName::test() 1074 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ 1075 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) 1078 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ 1079 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1080 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1081 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \ 1082 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1085 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\ 1086 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1087 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1088 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1089 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1090 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1092 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1093 INTERNAL_CATCH_TYPE_GEN\ 1094 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1095 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1096 template<typename...Types> \ 1100 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1101 using expander = int[];\ 1102 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... }; \ 1105 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1106 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1111 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1112 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1114 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1115 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1116 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) 1118 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1119 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) 1122 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1123 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1124 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) 1126 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1127 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) 1130 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ 1131 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1132 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1133 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1134 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1135 template<typename TestType> static void TestFuncName(); \ 1137 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1138 INTERNAL_CATCH_TYPE_GEN \ 1139 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ 1140 template<typename... Types> \ 1142 void reg_tests() { \ 1144 using expander = int[]; \ 1145 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1146 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1147 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1148 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };\ 1151 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1152 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \ 1159 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1160 template<typename TestType> \ 1161 static void TestFuncName() 1163 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1164 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1165 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__) 1167 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1168 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) ) 1171 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1172 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1173 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__) 1175 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1176 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) 1179 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ 1180 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1181 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1182 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1183 template<typename TestType> static void TestFunc(); \ 1185 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1186 INTERNAL_CATCH_TYPE_GEN\ 1187 template<typename... Types> \ 1189 void reg_tests() { \ 1191 using expander = int[]; \ 1192 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };\ 1195 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1196 using TestInit = typename convert<TestName, TmplList>::type; \ 1202 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1203 template<typename TestType> \ 1204 static void TestFunc() 1206 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ 1207 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList ) 1209 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1210 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1211 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1212 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1213 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1215 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1216 INTERNAL_CATCH_TYPE_GEN\ 1217 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1218 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1219 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1220 template<typename...Types> \ 1221 struct TestNameClass{\ 1224 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1225 using expander = int[];\ 1226 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... }; \ 1229 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1230 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1235 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1236 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1238 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1239 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1240 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) 1242 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1243 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) 1246 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1247 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1248 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) 1250 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1251 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) 1254 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ 1255 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1256 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1257 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1258 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1259 template<typename TestType> \ 1260 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1264 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\ 1265 INTERNAL_CATCH_TYPE_GEN \ 1266 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1267 template<typename...Types>\ 1268 struct TestNameClass{\ 1271 using expander = int[];\ 1272 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1273 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1274 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1275 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... }; \ 1278 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1279 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\ 1286 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1287 template<typename TestType> \ 1288 void TestName<TestType>::test() 1290 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1291 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1292 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ ) 1294 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1295 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) ) 1298 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1299 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1300 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ ) 1302 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1303 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) ) 1306 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ 1307 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1308 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1309 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1310 template<typename TestType> \ 1311 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1315 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1316 INTERNAL_CATCH_TYPE_GEN\ 1317 template<typename...Types>\ 1318 struct TestNameClass{\ 1321 using expander = int[];\ 1322 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... }; \ 1325 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1326 using TestInit = typename convert<TestNameClass, TmplList>::type;\ 1332 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1333 template<typename TestType> \ 1334 void TestName<TestType>::test() 1336 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ 1337 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList ) 1359 ExpressionFailed = FailureBit | 1,
1360 ExplicitFailure = FailureBit | 2,
1362 Exception = 0x100 | FailureBit,
1364 ThrewException = Exception | 1,
1365 DidntThrowException = Exception | 2,
1367 FatalErrorCondition = 0x200 | FailureBit
1378 ContinueOnFailure = 0x02,
1415 #include <type_traits> 1425 std::ostream&
cout();
1426 std::ostream&
cerr();
1427 std::ostream&
clog();
1433 virtual std::ostream& stream()
const = 0;
1445 auto str() const ->
std::
string;
1447 template<typename T>
1452 auto get() -> std::ostream& {
return *m_oss; }
1479 template<
typename E>
1481 static_assert(
sizeof(
int) >=
sizeof(E),
"Cannot serialize enum to int");
1482 std::vector<int> intValues;
1483 intValues.reserve( values.size() );
1484 for(
auto enumValue : values )
1485 intValues.push_back( static_cast<int>( enumValue ) );
1486 return registerEnum( enumName, allEnums, intValues );
1494 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1495 #include <string_view> 1501 #import <Foundation/Foundation.h> 1503 #ifdef __has_feature 1504 #define CATCH_ARC_ENABLED __has_feature(objc_arc) 1506 #define CATCH_ARC_ENABLED 0 1509 void arcSafeRelease( NSObject* obj );
1510 id performOptionalSelector(
id obj,
SEL sel );
1512 #if !CATCH_ARC_ENABLED 1513 inline void arcSafeRelease( NSObject* obj ) {
1516 inline id performOptionalSelector(
id obj,
SEL sel ) {
1517 if( [obj respondsToSelector: sel] )
1518 return [obj performSelector: sel];
1521 #define CATCH_UNSAFE_UNRETAINED 1522 #define CATCH_ARC_STRONG 1524 inline void arcSafeRelease( NSObject* ){}
1525 inline id performOptionalSelector(
id obj,
SEL sel ) {
1527 #pragma clang diagnostic push 1528 #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 1530 if( [obj respondsToSelector: sel] )
1531 return [obj performSelector: sel];
1533 #pragma clang diagnostic pop 1537 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained 1538 #define CATCH_ARC_STRONG __strong 1545 #pragma warning(push) 1546 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless 1556 template<
typename T>
1561 template<
typename T>
1563 template<
typename Stream,
typename U>
1564 static auto test(
int)
1565 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1567 template<
typename,
typename>
1568 static auto test(...)->std::false_type;
1571 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1574 template<
typename E>
1577 template<
typename T>
1578 typename std::enable_if<
1583 template<
typename T>
1584 typename std::enable_if<
1590 template<
typename T>
1591 typename std::enable_if<
1597 #if defined(_MANAGED) 1598 template<
typename T>
1600 std::string clrReferenceToString( T^ ref ) {
1602 return std::string(
"null");
1603 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1604 cli::pin_ptr<System::Byte> p = &bytes[0];
1605 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1612 template <
typename T,
typename =
void>
1614 template <
typename Fake = T>
1621 rss.operator<<(
value);
1625 template <
typename Fake = T>
1629 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) 1632 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1641 template <
typename T>
1643 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1646 template<
typename E>
1651 #if defined(_MANAGED) 1652 template <
typename T>
1654 return ::Catch::StringMaker<T^>::convert(e);
1664 static std::string convert(
const std::string& str);
1667 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1670 static std::string convert(std::string_view str);
1676 static std::string convert(
char const * str);
1680 static std::string convert(
char * str);
1683 #ifdef CATCH_CONFIG_WCHAR 1686 static std::string convert(
const std::wstring& wstr);
1689 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1692 static std::string convert(std::wstring_view str);
1698 static std::string convert(
wchar_t const * str);
1702 static std::string convert(
wchar_t * str);
1716 static std::string
convert(
signed char const* str) {
1722 static std::string
convert(
unsigned char const* str) {
1727 #if defined(CATCH_CONFIG_CPP17_BYTE) 1730 static std::string convert(std::byte value);
1732 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 1735 static std::string convert(
int value);
1739 static std::string convert(
long value);
1743 static std::string convert(
long long value);
1747 static std::string convert(
unsigned int value);
1751 static std::string convert(
unsigned long value);
1755 static std::string convert(
unsigned long long value);
1760 static std::string convert(
bool b);
1765 static std::string convert(
char c);
1769 static std::string convert(
signed char c);
1773 static std::string convert(
unsigned char c);
1778 static std::string convert(std::nullptr_t);
1783 static std::string convert(
float value);
1789 static std::string convert(
double value);
1793 template <
typename T>
1795 template <
typename U>
1805 template <
typename R,
typename C>
1816 #if defined(_MANAGED) 1817 template <
typename T>
1819 static std::string convert( T^ ref ) {
1820 return ::Catch::Detail::clrReferenceToString(ref);
1826 template<
typename InputIterator,
typename Sentinel = InputIterator>
1830 if (first != last) {
1832 for (++first; first != last; ++first)
1843 static std::string convert(NSString * nsstring) {
1846 return std::string(
"@") + [nsstring UTF8String];
1851 static std::string convert(NSObject* nsObject) {
1857 inline std::string
stringify( NSString* nsstring ) {
1870 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) 1871 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1872 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1873 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1874 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 1875 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1879 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) 1882 template<
typename T1,
typename T2>
1884 static std::string convert(
const std::pair<T1, T2>& pair) {
1895 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1897 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) 1900 template<
typename T>
1902 static std::string convert(
const std::optional<T>& optional) {
1904 if (optional.has_value()) {
1913 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1916 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) 1925 struct TupleElementPrinter {
1926 static void print(
const Tuple& tuple, std::ostream& os) {
1927 os << (N ?
", " :
" ")
1929 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1937 struct TupleElementPrinter<Tuple, N, false> {
1938 static void print(
const Tuple&, std::ostream&) {}
1943 template<
typename ...Types>
1945 static std::string convert(
const std::tuple<Types...>& tuple) {
1948 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.
get());
1954 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1956 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) 1961 static std::string convert(
const std::monostate&) {
1966 template<
typename... Elements>
1968 static std::string convert(
const std::variant<Elements...>& variant) {
1969 if (variant.valueless_by_exception()) {
1970 return "{valueless variant}";
1973 [](
const auto&
value) {
1982 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1990 template <
typename...>
1995 template <
typename T,
typename =
void>
1999 template <
typename T>
2004 template <
typename T>
2008 #if defined(_MANAGED) // Managed types are never ranges 2009 template <
typename T>
2011 static const bool value =
false;
2015 template<
typename Range>
2021 template<
typename Allocator>
2037 template<
typename R>
2044 template <
typename T,
int SZ>
2054 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 2061 template <
class Ratio>
2062 struct ratio_string {
2063 static std::string symbol();
2066 template <
class Ratio>
2067 std::string ratio_string<Ratio>::symbol() {
2069 rss <<
'[' << Ratio::num <<
'/' 2070 << Ratio::den <<
']';
2074 struct ratio_string<std::atto> {
2075 static std::string symbol();
2078 struct ratio_string<std::femto> {
2079 static std::string symbol();
2082 struct ratio_string<std::pico> {
2083 static std::string symbol();
2086 struct ratio_string<std::nano> {
2087 static std::string symbol();
2090 struct ratio_string<std::micro> {
2091 static std::string symbol();
2094 struct ratio_string<std::milli> {
2095 static std::string symbol();
2100 template<
typename Value,
typename Ratio>
2101 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2102 static std::string convert(std::chrono::duration<Value, Ratio>
const& duration) {
2104 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2108 template<
typename Value>
2109 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2110 static std::string convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2112 rss << duration.count() <<
" s";
2116 template<
typename Value>
2117 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2118 static std::string convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2120 rss << duration.count() <<
" m";
2124 template<
typename Value>
2125 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2126 static std::string convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2128 rss << duration.count() <<
" h";
2136 template<
typename Clock,
typename Duration>
2137 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2138 static std::string convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2143 template<
typename Duration>
2144 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2145 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2146 auto converted = std::chrono::system_clock::to_time_t(time_point);
2149 std::tm timeInfo = {};
2150 gmtime_s(&timeInfo, &converted);
2152 std::tm* timeInfo = std::gmtime(&converted);
2155 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2157 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2160 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2162 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2164 return std::string(timeStamp);
2168 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 2170 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ 2172 template<> struct StringMaker<enumName> { \ 2173 static std::string convert( enumName value ) { \ 2174 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ 2175 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \ 2180 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) 2183 #pragma warning(pop) 2190 #pragma warning(push) 2191 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch 2192 #pragma warning(disable:4018) // more "signed/unsigned mismatch" 2193 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) 2194 #pragma warning(disable:4180) // qualifier applied to function type has no meaning 2195 #pragma warning(disable:4800) // Forcing result to true or false 2203 virtual void streamReconstructedExpression( std::ostream &os )
const = 0;
2206 : m_isBinaryExpression( isBinaryExpression ),
2221 template<
typename LhsT,
typename RhsT>
2240 template<
typename T>
2243 "chained comparisons are not supported inside assertions, " 2244 "wrap the expression inside parentheses, or decompose it");
2247 template<
typename T>
2250 "chained comparisons are not supported inside assertions, " 2251 "wrap the expression inside parentheses, or decompose it");
2254 template<
typename T>
2257 "chained comparisons are not supported inside assertions, " 2258 "wrap the expression inside parentheses, or decompose it");
2261 template<
typename T>
2264 "chained comparisons are not supported inside assertions, " 2265 "wrap the expression inside parentheses, or decompose it");
2268 template<
typename T>
2271 "chained comparisons are not supported inside assertions, " 2272 "wrap the expression inside parentheses, or decompose it");
2275 template<
typename T>
2278 "chained comparisons are not supported inside assertions, " 2279 "wrap the expression inside parentheses, or decompose it");
2282 template<
typename T>
2285 "chained comparisons are not supported inside assertions, " 2286 "wrap the expression inside parentheses, or decompose it");
2289 template<
typename T>
2292 "chained comparisons are not supported inside assertions, " 2293 "wrap the expression inside parentheses, or decompose it");
2297 template<
typename LhsT>
2313 template<
typename LhsT,
typename RhsT>
2314 auto compareEqual( LhsT
const& lhs, RhsT
const& rhs ) ->
bool {
return static_cast<bool>(lhs == rhs); }
2315 template<
typename T>
2316 auto compareEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2317 template<
typename T>
2318 auto compareEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2319 template<
typename T>
2320 auto compareEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2321 template<
typename T>
2322 auto compareEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2324 template<
typename LhsT,
typename RhsT>
2325 auto compareNotEqual( LhsT
const& lhs, RhsT&& rhs ) ->
bool {
return static_cast<bool>(lhs != rhs); }
2326 template<
typename T>
2327 auto compareNotEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2328 template<
typename T>
2329 auto compareNotEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2330 template<
typename T>
2331 auto compareNotEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2332 template<
typename T>
2333 auto compareNotEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2335 template<
typename LhsT>
2341 template<
typename RhsT>
2343 return {
compareEqual( m_lhs, rhs ), m_lhs,
"==", rhs };
2346 return { m_lhs == rhs, m_lhs,
"==", rhs };
2349 template<
typename RhsT>
2354 return { m_lhs != rhs, m_lhs,
"!=", rhs };
2357 template<
typename RhsT>
2359 return {
static_cast<bool>(m_lhs > rhs), m_lhs,
">", rhs };
2361 template<
typename RhsT>
2363 return {
static_cast<bool>(m_lhs < rhs), m_lhs,
"<", rhs };
2365 template<
typename RhsT>
2367 return {
static_cast<bool>(m_lhs >= rhs), m_lhs,
">=", rhs };
2369 template<
typename RhsT>
2371 return {
static_cast<bool>(m_lhs <= rhs), m_lhs,
"<=", rhs };
2373 template <
typename RhsT>
2375 return {
static_cast<bool>(m_lhs | rhs), m_lhs,
"|", rhs };
2377 template <
typename RhsT>
2379 return {
static_cast<bool>(m_lhs & rhs), m_lhs,
"&", rhs };
2381 template <
typename RhsT>
2383 return {
static_cast<bool>(m_lhs ^ rhs), m_lhs,
"^", rhs };
2386 template<
typename RhsT>
2389 "operator&& is not supported inside assertions, " 2390 "wrap the expression inside parentheses, or decompose it");
2393 template<
typename RhsT>
2396 "operator|| is not supported inside assertions, " 2397 "wrap the expression inside parentheses, or decompose it");
2407 template<
typename T>
2413 template<
typename T>
2426 #pragma warning(pop) 2437 class AssertionResult;
2450 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2451 struct BenchmarkInfo;
2452 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2453 struct BenchmarkStats;
2454 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2460 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
2461 Counts& assertions ) = 0;
2463 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo ) = 0;
2467 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2468 virtual void benchmarkPreparing( std::string
const& name ) = 0;
2469 virtual void benchmarkStarting( BenchmarkInfo
const& info ) = 0;
2470 virtual void benchmarkEnded( BenchmarkStats<>
const& stats ) = 0;
2471 virtual void benchmarkFailed( std::string
const& error ) = 0;
2472 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2474 virtual void pushScopedMessage(
MessageInfo const& message ) = 0;
2475 virtual void popScopedMessage(
MessageInfo const& message ) = 0;
2477 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder ) = 0;
2479 virtual void handleFatalErrorCondition(
StringRef message ) = 0;
2481 virtual void handleExpr
2485 virtual void handleMessage
2490 virtual void handleUnexpectedExceptionNotThrown
2493 virtual void handleUnexpectedInflightException
2495 std::string
const& message,
2497 virtual void handleIncomplete
2499 virtual void handleNonExpr
2504 virtual bool lastAssertionPassed() = 0;
2505 virtual void assertionPassed() = 0;
2508 virtual std::string getCurrentTestName()
const = 0;
2509 virtual const AssertionResult* getLastResult()
const = 0;
2510 virtual void exceptionEarlyReported() = 0;
2520 struct AssertionResultData;
2526 friend struct AssertionStats;
2527 friend class RunContext;
2536 explicit operator bool()
const;
2542 bool shouldDebugBreak =
false;
2543 bool shouldThrow =
false;
2549 bool m_completed =
false;
2559 if ( !m_completed ) {
2564 template<
typename T>
2572 void handleExceptionThrownAsExpected();
2573 void handleUnexpectedExceptionNotThrown();
2574 void handleExceptionNotThrownAsExpected();
2575 void handleThrowingCallSkipped();
2576 void handleUnexpectedInflightException();
2579 void setCompleted();
2582 auto allowThrows()
const -> bool;
2608 bool operator == (
MessageInfo const& other )
const;
2609 bool operator < (
MessageInfo const& other )
const;
2616 template<
typename T>
2630 template<
typename T>
2653 size_t m_captured = 0;
2658 void captureValue(
size_t index, std::string
const&
value );
2660 template<
typename T>
2665 template<
typename T,
typename... Ts>
2668 captureValues( index+1, values... );
2675 #if !defined(CATCH_CONFIG_DISABLE) 2677 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) 2678 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ 2680 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" 2683 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 2688 #define INTERNAL_CATCH_TRY 2689 #define INTERNAL_CATCH_CATCH( capturer ) 2691 #else // CATCH_CONFIG_FAST_COMPILE 2693 #define INTERNAL_CATCH_TRY try 2694 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } 2698 #define INTERNAL_CATCH_REACT( handler ) handler.complete(); 2701 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ 2703 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ 2704 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2705 INTERNAL_CATCH_TRY { \ 2706 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2707 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 2708 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ 2709 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 2710 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 2711 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2712 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) 2715 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ 2716 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2717 if( Catch::getResultCapture().lastAssertionPassed() ) 2720 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ 2721 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2722 if( !Catch::getResultCapture().lastAssertionPassed() ) 2725 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ 2727 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2729 static_cast<void>(__VA_ARGS__); \ 2730 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ 2733 catchAssertionHandler.handleUnexpectedInflightException(); \ 2735 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2739 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ 2741 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ 2742 if( catchAssertionHandler.allowThrows() ) \ 2744 static_cast<void>(__VA_ARGS__); \ 2745 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2748 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2751 catchAssertionHandler.handleThrowingCallSkipped(); \ 2752 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2756 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ 2758 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ 2759 if( catchAssertionHandler.allowThrows() ) \ 2761 static_cast<void>(expr); \ 2762 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2764 catch( exceptionType const& ) { \ 2765 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2768 catchAssertionHandler.handleUnexpectedInflightException(); \ 2771 catchAssertionHandler.handleThrowingCallSkipped(); \ 2772 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2776 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ 2778 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ 2779 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ 2780 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2784 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ 2785 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ 2786 varName.captureValues( 0, __VA_ARGS__ ) 2789 #define INTERNAL_CATCH_INFO( macroName, log ) \ 2790 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); 2793 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ 2794 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) 2798 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ 2800 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 2801 if( catchAssertionHandler.allowThrows() ) \ 2803 static_cast<void>(__VA_ARGS__); \ 2804 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2807 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ 2810 catchAssertionHandler.handleThrowingCallSkipped(); \ 2811 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2814 #endif // CATCH_CONFIG_DISABLE 2831 std::size_t total()
const;
2832 bool allPassed()
const;
2835 std::size_t passed = 0;
2836 std::size_t failed = 0;
2837 std::size_t failedButOk = 0;
2861 std::string
const& _name );
2866 std::string
const& _name,
2867 std::string
const& ) :
SectionInfo( _lineInfo, _name ) {}
2893 uint64_t m_nanoseconds = 0;
2896 auto getElapsedNanoseconds() const -> uint64_t;
2897 auto getElapsedMicroseconds() const -> uint64_t;
2898 auto getElapsedMilliseconds() const ->
unsigned int;
2899 auto getElapsedSeconds() const ->
double;
2915 explicit operator bool()
const;
2928 #define INTERNAL_CATCH_SECTION( ... ) \ 2929 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2930 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2931 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ 2932 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2934 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ 2935 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2936 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2937 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ 2938 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2951 struct ITestCaseRegistry;
2952 struct IExceptionTranslatorRegistry;
2953 struct IExceptionTranslator;
2954 struct IReporterRegistry;
2955 struct IReporterFactory;
2956 struct ITagAliasRegistry;
2957 struct IMutableEnumValuesRegistry;
2959 class StartupExceptionRegistry;
2966 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2968 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2971 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
2976 virtual void registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory ) = 0;
2978 virtual void registerTest(
TestCase const& testInfo ) = 0;
2980 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) = 0;
2981 virtual void registerStartupException() noexcept = 0;
2993 #if defined(CATCH_CONFIG_DISABLE) 2994 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ 2995 static std::string translatorName( signature ) 2998 #include <exception> 3010 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3020 template<
typename T>
3025 : m_translateFunction( translateFunction )
3028 std::string
translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const override {
3029 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3034 std::rethrow_exception(std::current_exception());
3036 return (*it)->translate( it+1, itEnd );
3039 return m_translateFunction( ex );
3045 std::string(*m_translateFunction)( T& );
3049 template<
typename T>
3058 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ 3059 static std::string translatorName( signature ); \ 3060 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 3061 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 3062 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ 3063 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 3064 static std::string translatorName( signature ) 3066 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 3071 #include <type_traits> 3078 bool equalityComparisonImpl(
double other)
const;
3081 void setMargin(
double margin);
3084 void setEpsilon(
double epsilon);
3091 Approx operator-()
const;
3095 Approx approx( static_cast<double>(value) );
3107 friend bool operator == (
const T& lhs,
Approx const& rhs ) {
3108 auto lhs_v =
static_cast<double>(lhs);
3113 friend bool operator == (
Approx const& lhs,
const T& rhs ) {
3118 friend bool operator != ( T
const& lhs,
Approx const& rhs ) {
3123 friend bool operator != (
Approx const& lhs, T
const& rhs ) {
3128 friend bool operator <= ( T
const& lhs,
Approx const& rhs ) {
3129 return static_cast<double>(lhs) < rhs.
m_value || lhs == rhs;
3133 friend bool operator <= (
Approx const& lhs, T
const& rhs ) {
3134 return lhs.
m_value <
static_cast<double>(rhs) || lhs == rhs;
3138 friend bool operator >= ( T
const& lhs,
Approx const& rhs ) {
3139 return static_cast<double>(lhs) > rhs.
m_value || lhs == rhs;
3143 friend bool operator >= (
Approx const& lhs, T
const& rhs ) {
3144 return lhs.
m_value >
static_cast<double>(rhs) || lhs == rhs;
3149 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3150 setEpsilon(epsilonAsDouble);
3156 double marginAsDouble =
static_cast<double>(newMargin);
3157 setMargin(marginAsDouble);
3163 m_scale =
static_cast<double>(newScale);
3167 std::string toString()
const;
3177 namespace literals {
3198 bool startsWith( std::string
const&
s, std::string
const& prefix );
3199 bool startsWith( std::string
const& s,
char prefix );
3200 bool endsWith( std::string
const& s, std::string
const& suffix );
3201 bool endsWith( std::string
const& s,
char suffix );
3202 bool contains( std::string
const& s, std::string
const& infix );
3204 std::string
toLower( std::string
const& s );
3206 std::string
trim( std::string
const& str );
3212 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
3215 pluralise( std::size_t count, std::string
const& label );
3225 #ifndef CATCH_CONFIG_DISABLE_MATCHERS 3234 namespace Matchers {
3246 std::string toString()
const;
3250 virtual std::string describe()
const = 0;
3255 # pragma clang diagnostic push 3256 # pragma clang diagnostic ignored "-Wnon-virtual-dtor" 3259 template<
typename ObjectT>
3261 virtual bool match( ObjectT
const& arg )
const = 0;
3264 #if defined(__OBJC__) 3269 virtual bool match( NSString* arg )
const = 0;
3274 # pragma clang diagnostic pop 3277 template<
typename T>
3285 template<
typename ArgT>
3287 bool match( ArgT
const& arg )
const override {
3288 for(
auto matcher : m_matchers ) {
3289 if (!matcher->match(arg))
3295 std::string description;
3296 description.reserve( 4 + m_matchers.size()*32 );
3297 description +=
"( ";
3299 for(
auto matcher : m_matchers ) {
3303 description +=
" and ";
3304 description += matcher->toString();
3306 description +=
" )";
3312 copy.m_matchers.push_back( &other );
3318 template<
typename ArgT>
3321 bool match( ArgT
const& arg )
const override {
3322 for(
auto matcher : m_matchers ) {
3323 if (matcher->match(arg))
3329 std::string description;
3330 description.reserve( 4 + m_matchers.size()*32 );
3331 description +=
"( ";
3333 for(
auto matcher : m_matchers ) {
3337 description +=
" or ";
3338 description += matcher->toString();
3340 description +=
" )";
3346 copy.m_matchers.push_back( &other );
3353 template<
typename ArgT>
3358 bool match( ArgT
const& arg )
const override {
3359 return !m_underlyingMatcher.match( arg );
3363 return "not " + m_underlyingMatcher.toString();
3368 template<
typename T>
3372 template<
typename T>
3376 template<
typename T>
3385 using namespace Matchers;
3394 namespace Matchers {
3395 namespace Exception {
3405 bool match(std::exception
const& ex)
const override;
3407 std::string describe()
const override;
3421 namespace Matchers {
3423 namespace Floating {
3425 enum class FloatingPointKind : uint8_t;
3429 bool match(
double const& matchee)
const override;
3430 std::string describe()
const override;
3438 bool match(
double const& matchee)
const override;
3439 std::string describe()
const override;
3454 bool match(
double const& matchee)
const override;
3455 std::string describe()
const override;
3481 #include <functional> 3485 namespace Matchers {
3492 template <
typename T>
3499 :m_predicate(
std::move(elem)),
3503 bool match( T
const& item )
const override {
3504 return m_predicate(item);
3508 return m_description;
3518 template<
typename T>
3532 namespace Matchers {
3534 namespace StdString {
3539 std::string adjustString( std::string
const& str )
const;
3540 std::string caseSensitivitySuffix()
const;
3548 std::string describe()
const override;
3556 bool match( std::string
const& source )
const override;
3560 bool match( std::string
const& source )
const override;
3564 bool match( std::string
const& source )
const override;
3568 bool match( std::string
const& source )
const override;
3573 bool match( std::string
const& matchee )
const override;
3574 std::string describe()
const override;
3598 #include <algorithm> 3601 namespace Matchers {
3604 template<
typename T,
typename Alloc>
3609 bool match(std::vector<T, Alloc>
const &v)
const override {
3610 for (
auto const& el : v) {
3611 if (el == m_comparator) {
3625 template<
typename T,
typename AllocComp,
typename AllocMatch>
3628 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3630 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3632 if (m_comparator.size() > v.size())
3634 for (
auto const& comparator : m_comparator) {
3635 auto present =
false;
3636 for (
const auto& el : v) {
3637 if (el == comparator) {
3655 template<
typename T,
typename AllocComp,
typename AllocMatch>
3658 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3660 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3665 if (m_comparator.size() != v.size())
3667 for (std::size_t i = 0; i < v.size(); ++i)
3668 if (m_comparator[i] != v[i])
3678 template<
typename T,
typename AllocComp,
typename AllocMatch>
3681 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3683 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3684 if (m_comparator.size() != v.size())
3686 for (std::size_t i = 0; i < v.size(); ++i)
3687 if (m_comparator[i] != approx(v[i]))
3701 approx.
margin(newMargin);
3706 approx.
scale(newScale);
3714 template<
typename T,
typename AllocComp,
typename AllocMatch>
3717 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3718 if (m_target.size() != vec.size()) {
3721 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3736 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3741 template<
typename T,
typename Alloc = std::allocator<T>>
3746 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3751 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3756 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3767 template<
typename ArgT,
typename MatcherT>
3776 m_matcher( matcher ),
3777 m_matcherString( matcherString )
3781 auto matcherAsString = m_matcher.toString();
3784 os << m_matcherString;
3786 os << matcherAsString;
3794 template<
typename ArgT,
typename MatcherT>
3802 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ 3804 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3805 INTERNAL_CATCH_TRY { \ 3806 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ 3807 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 3808 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3812 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ 3814 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3815 if( catchAssertionHandler.allowThrows() ) \ 3817 static_cast<void>(__VA_ARGS__ ); \ 3818 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 3820 catch( exceptionType const& ex ) { \ 3821 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ 3824 catchAssertionHandler.handleUnexpectedInflightException(); \ 3827 catchAssertionHandler.handleThrowingCallSkipped(); \ 3828 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3851 virtual bool next() = 0;
3859 virtual auto hasGenerator()
const ->
bool = 0;
3869 #include <exception> 3872 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3873 template <
typename Ex>
3878 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 3892 #define CATCH_MAKE_MSG(...) \ 3893 (Catch::ReusableStringStream() << __VA_ARGS__).str() 3895 #define CATCH_INTERNAL_ERROR(...) \ 3896 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) 3898 #define CATCH_ERROR(...) \ 3899 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3901 #define CATCH_RUNTIME_ERROR(...) \ 3902 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3904 #define CATCH_ENFORCE( condition, ... ) \ 3905 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) 3913 #include <exception> 3918 const char*
const m_msg =
"";
3925 const char* what()
const noexcept
override final;
3928 namespace Generators {
3932 template<
typename T,
typename... Args>
3934 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
3938 template<
typename T>
3946 virtual T
const&
get()
const = 0;
3950 template<
typename T>
3956 T
const&
get()
const override {
3964 template<
typename T>
3967 "FixedValuesGenerator does not support bools because of std::vector<bool>" 3968 "specialization, use SingleValue Generator instead.");
3974 T
const&
get()
const override {
3975 return m_values[m_idx];
3979 return m_idx < m_values.size();
3983 template <
typename T>
3988 m_generator(
std::move(generator))
3990 T
const&
get()
const {
3991 return m_generator->get();
3994 return m_generator->next();
3998 template <
typename T>
4002 template <
typename T>
4007 template<
typename T>
4010 size_t m_current = 0;
4013 m_generators.emplace_back(std::move(generator));
4016 m_generators.emplace_back(
value(std::forward<T>(val)));
4018 template<
typename U>
4020 populate(T(std::forward<U>(val)));
4022 template<
typename U,
typename... Gs>
4023 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4024 populate(std::forward<U>(valueOrGenerator));
4025 populate(std::forward<Gs>(moreGenerators)...);
4029 template <
typename... Gs>
4031 m_generators.reserve(
sizeof...(Gs));
4032 populate(std::forward<Gs>(moreGenerators)...);
4035 T
const&
get()
const override {
4036 return m_generators[m_current].get();
4040 if (m_current >= m_generators.size()) {
4043 const bool current_status = m_generators[m_current].next();
4044 if (!current_status) {
4047 return m_current < m_generators.size();
4051 template<
typename... Ts>
4052 GeneratorWrapper<std::tuple<Ts...>>
table( std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples ) {
4053 return values<std::tuple<Ts...>>( tuples );
4057 template <
typename T>
4060 template<
typename T,
typename... Gs>
4062 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4064 template<
typename T>
4068 template<
typename T,
typename... Gs>
4070 return makeGenerators(
value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4072 template<
typename T,
typename U,
typename... Gs>
4074 return makeGenerators(
value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4079 template<
typename L>
4083 auto generate(
StringRef generatorName,
SourceLineInfo const& lineInfo, L
const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().
get()) {
4084 using UnderlyingType =
typename decltype(generatorExpression())::type;
4092 return generator.
get();
4098 #define GENERATE( ... ) \ 4099 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4100 CATCH_INTERNAL_LINEINFO, \ 4101 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4102 #define GENERATE_COPY( ... ) \ 4103 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4104 CATCH_INTERNAL_LINEINFO, \ 4105 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4106 #define GENERATE_REF( ... ) \ 4107 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4108 CATCH_INTERNAL_LINEINFO, \ 4109 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4115 namespace Generators {
4117 template <
typename T>
4120 size_t m_returned = 0;
4124 m_generator(
std::move(generator)),
4127 assert(target != 0 &&
"Empty generators are not allowed");
4129 T
const&
get()
const override {
4130 return m_generator.
get();
4134 if (m_returned >= m_target) {
4138 const auto success = m_generator.
next();
4142 m_returned = m_target;
4148 template <
typename T>
4150 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4153 template <
typename T,
typename Predicate>
4158 template <
typename P = Predicate>
4160 m_generator(
std::move(generator)),
4161 m_predicate(
std::forward<P>(pred))
4163 if (!m_predicate(m_generator.
get())) {
4166 auto has_initial_value = next();
4167 if (!has_initial_value) {
4173 T
const&
get()
const override {
4174 return m_generator.
get();
4178 bool success = m_generator.
next();
4182 while (!m_predicate(m_generator.
get()) && (success = m_generator.
next()) ==
true);
4187 template <
typename T,
typename Predicate>
4189 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4192 template <
typename T>
4195 "RepeatGenerator currently does not support bools" 4196 "because of std::vector<bool> specialization");
4200 size_t m_current_repeat = 0;
4201 size_t m_repeat_index = 0;
4204 m_generator(
std::move(generator)),
4205 m_target_repeats(repeats)
4207 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4210 T
const&
get()
const override {
4211 if (m_current_repeat == 0) {
4212 m_returned.push_back(m_generator.
get());
4213 return m_returned.back();
4215 return m_returned[m_repeat_index];
4225 if (m_current_repeat == 0) {
4226 const auto success = m_generator.
next();
4230 return m_current_repeat < m_target_repeats;
4235 if (m_repeat_index == m_returned.size()) {
4239 return m_current_repeat < m_target_repeats;
4243 template <
typename T>
4245 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4248 template <
typename T,
typename U,
typename Func>
4256 template <
typename F2 = Func>
4258 m_generator(
std::move(generator)),
4259 m_function(
std::forward<F2>(function)),
4260 m_cache(m_function(m_generator.
get()))
4263 T
const&
get()
const override {
4267 const auto success = m_generator.
next();
4269 m_cache = m_function(m_generator.
get());
4275 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4278 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4282 template <
typename T,
typename U,
typename Func>
4285 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4289 template <
typename T>
4294 bool m_used_up =
false;
4297 m_chunk_size(size), m_generator(
std::move(generator))
4299 m_chunk.reserve(m_chunk_size);
4300 if (m_chunk_size != 0) {
4301 m_chunk.push_back(m_generator.
get());
4302 for (
size_t i = 1; i < m_chunk_size; ++i) {
4303 if (!m_generator.
next()) {
4306 m_chunk.push_back(m_generator.
get());
4310 std::vector<T>
const&
get()
const override {
4315 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4316 if (!m_generator.
next()) {
4319 m_chunk.push_back(m_generator.
get());
4325 template <
typename T>
4328 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4356 virtual IRunner* getRunner() = 0;
4357 virtual IConfigPtr const& getConfig()
const = 0;
4363 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4364 virtual void setRunner(
IRunner* runner ) = 0;
4365 virtual void setConfig(
IConfigPtr const& config ) = 0;
4371 static void createContext();
4401 template<
typename T>
4406 : nullableValue( new( storage ) T( _value ) )
4409 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4417 if( &_other !=
this ) {
4420 nullableValue =
new( storage ) T( *_other );
4426 nullableValue =
new( storage ) T( _value );
4432 nullableValue->~T();
4433 nullableValue =
nullptr;
4442 return nullableValue ? *nullableValue : defaultValue;
4445 bool some()
const {
return nullableValue !=
nullptr; }
4446 bool none()
const {
return nullableValue ==
nullptr; }
4448 bool operator !()
const {
return nullableValue ==
nullptr; }
4449 explicit operator bool()
const {
4455 alignas(
alignof(T))
char storage[
sizeof(T)];
4477 NoAssertions = 0x01,
4500 BeforeStartAndExit = BeforeStart | BeforeExit
4509 virtual bool allowThrows()
const = 0;
4510 virtual std::ostream& stream()
const = 0;
4511 virtual std::string name()
const = 0;
4512 virtual bool includeSuccessfulResults()
const = 0;
4513 virtual bool shouldDebugBreak()
const = 0;
4514 virtual bool warnAboutMissingAssertions()
const = 0;
4515 virtual bool warnAboutNoTests()
const = 0;
4516 virtual int abortAfter()
const = 0;
4517 virtual bool showInvisibles()
const = 0;
4519 virtual double minDuration()
const = 0;
4520 virtual TestSpec
const& testSpec()
const = 0;
4521 virtual bool hasTestFilters()
const = 0;
4522 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4524 virtual unsigned int rngSeed()
const = 0;
4526 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4527 virtual Verbosity verbosity()
const = 0;
4529 virtual bool benchmarkNoAnalysis()
const = 0;
4530 virtual int benchmarkSamples()
const = 0;
4531 virtual double benchmarkConfidenceInterval()
const = 0;
4532 virtual unsigned int benchmarkResamples()
const = 0;
4533 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4536 using IConfigPtr = std::shared_ptr<IConfig const>;
4568 void discard(uint64_t skip);
4584 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4593 namespace Generators {
4595 template <
typename Float>
4598 std::uniform_real_distribution<Float>
m_dist;
4605 static_cast<void>(next());
4608 Float
const&
get()
const override {
4609 return m_current_number;
4612 m_current_number = m_dist(m_rng);
4617 template <
typename Integer>
4620 std::uniform_int_distribution<Integer>
m_dist;
4627 static_cast<void>(next());
4630 Integer
const&
get()
const override {
4631 return m_current_number;
4634 m_current_number = m_dist(m_rng);
4641 template <
typename T>
4646 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4650 template <
typename T>
4655 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4659 template <
typename T>
4671 m_positive(m_step > T(0))
4673 assert(m_current != m_end &&
"Range start and end cannot be equal");
4674 assert(m_step != T(0) &&
"Step size cannot be zero");
4675 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4682 T
const&
get()
const override {
4687 m_current += m_step;
4688 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4692 template <
typename T>
4698 template <
typename T>
4704 template <
typename T>
4707 "IteratorGenerator currently does not support bools" 4708 "because of std::vector<bool> specialization");
4711 size_t m_current = 0;
4713 template <
typename InputIterator,
typename InputSentinel>
4715 if (m_elems.empty()) {
4720 T
const&
get()
const override {
4721 return m_elems[m_current];
4726 return m_current != m_elems.size();
4730 template <
typename InputIterator,
4731 typename InputSentinel,
4732 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4737 template <
typename Container,
4738 typename ResultType =
typename Container::value_type>
4757 #pragma clang diagnostic push 4758 #pragma clang diagnostic ignored "-Wpadded" 4769 ShouldFail = 1 << 2,
4772 NonPortable = 1 << 5,
4777 std::string
const& _className,
4778 std::string
const& _description,
4779 std::vector<std::string>
const& _tags,
4782 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4784 bool isHidden()
const;
4785 bool throws()
const;
4786 bool okToFail()
const;
4787 bool expectedToFail()
const;
4789 std::string tagsAsString()
const;
4805 TestCase withName( std::string
const& _newName )
const;
4807 void invoke()
const;
4811 bool operator == (
TestCase const& other )
const;
4812 bool operator < (
TestCase const& other )
const;
4815 std::shared_ptr<ITestInvoker>
test;
4819 std::string
const& className,
4825 #pragma clang diagnostic pop 4835 virtual bool aborting()
const = 0;
4844 #import <objc/runtime.h> 4869 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4871 virtual void invoke()
const {
4872 id obj = [[m_cls alloc] init];
4874 performOptionalSelector( obj,
@selector(setUp) );
4875 performOptionalSelector( obj, m_sel );
4876 performOptionalSelector( obj,
@selector(tearDown) );
4878 arcSafeRelease( obj );
4881 virtual ~OcMethod() {}
4889 inline std::string getAnnotation( Class cls,
4890 std::string
const& annotationName,
4891 std::string
const& testCaseName ) {
4892 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4893 SEL sel = NSSelectorFromString( selStr );
4894 arcSafeRelease( selStr );
4895 id value = performOptionalSelector( cls, sel );
4897 return [(NSString*)value UTF8String];
4902 inline std::size_t registerTestMethods() {
4903 std::size_t noTestMethods = 0;
4904 int noClasses = objc_getClassList(
nullptr, 0 );
4906 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4907 objc_getClassList( classes, noClasses );
4909 for(
int c = 0; c < noClasses; c++ ) {
4910 Class cls = classes[c];
4913 Method* methods = class_copyMethodList( cls, &count );
4914 for( u_int m = 0; m < count ; m++ ) {
4915 SEL selector = method_getName(methods[m]);
4916 std::string methodName = sel_getName(selector);
4917 if(
startsWith( methodName,
"Catch_TestCase_" ) ) {
4918 std::string testCaseName = methodName.substr( 15 );
4919 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4920 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4921 const char* className = class_getName( cls );
4930 return noTestMethods;
4933 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 4935 namespace Matchers {
4937 namespace NSStringMatchers {
4940 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4941 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4943 arcSafeRelease( m_substr );
4946 bool match( NSString* str )
const override {
4950 NSString* CATCH_ARC_STRONG m_substr;
4953 struct Equals : StringHolder {
4954 Equals( NSString* substr ) : StringHolder( substr ){}
4956 bool match( NSString* str )
const override {
4957 return (str != nil || m_substr == nil ) &&
4958 [str isEqualToString:m_substr];
4961 std::string describe()
const override {
4967 Contains( NSString* substr ) : StringHolder( substr ){}
4969 bool match( NSString* str )
const override {
4970 return (str != nil || m_substr == nil ) &&
4971 [str rangeOfString:m_substr].location != NSNotFound;
4974 std::string describe()
const override {
4980 StartsWith( NSString* substr ) : StringHolder( substr ){}
4982 bool match( NSString* str )
const override {
4983 return (str != nil || m_substr == nil ) &&
4984 [str rangeOfString:m_substr].location == 0;
4987 std::string describe()
const override {
4992 EndsWith( NSString* substr ) : StringHolder( substr ){}
4994 bool match( NSString* str )
const override {
4995 return (str != nil || m_substr == nil ) &&
4996 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4999 std::string describe()
const override {
5021 using namespace Matchers;
5023 #endif // CATCH_CONFIG_DISABLE_MATCHERS 5028 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix 5029 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ 5030 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ 5034 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ 5038 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) 5040 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) 5046 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5058 #pragma clang diagnostic push 5059 #pragma clang diagnostic ignored "-Wpadded" 5065 #pragma clang diagnostic push 5066 #pragma clang diagnostic ignored "-Wpadded" 5073 class WildcardPattern {
5074 enum WildcardPosition {
5076 WildcardAtStart = 1,
5078 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5084 virtual ~WildcardPattern() =
default;
5085 virtual bool matches( std::string
const& str )
const;
5088 std::string normaliseString( std::string
const& str )
const;
5090 WildcardPosition m_wildcard = NoWildcard;
5091 std::string m_pattern;
5107 explicit Pattern( std::string
const& name );
5109 virtual bool matches(
TestCaseInfo const& testCase )
const = 0;
5110 std::string
const& name()
const;
5112 std::string
const m_name;
5114 using PatternPtr = std::shared_ptr<Pattern>;
5116 class NamePattern :
public Pattern {
5118 explicit NamePattern( std::string
const& name, std::string
const& filterString );
5119 bool matches(
TestCaseInfo const& testCase )
const override;
5121 WildcardPattern m_wildcardPattern;
5124 class TagPattern :
public Pattern {
5126 explicit TagPattern( std::string
const& tag, std::string
const& filterString );
5127 bool matches(
TestCaseInfo const& testCase )
const override;
5132 class ExcludedPattern :
public Pattern {
5134 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5135 bool matches(
TestCaseInfo const& testCase )
const override;
5137 PatternPtr m_underlyingPattern;
5141 std::vector<PatternPtr> m_patterns;
5144 std::string name()
const;
5148 struct FilterMatch {
5150 std::vector<TestCase const*> tests;
5152 using Matches = std::vector<FilterMatch>;
5153 using vectorStrings = std::vector<std::string>;
5155 bool hasFilters()
const;
5157 Matches matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const;
5158 const vectorStrings & getInvalidArgs()
const;
5161 std::vector<Filter> m_filters;
5162 std::vector<std::string> m_invalidArgs;
5163 friend class TestSpecParser;
5168 #pragma clang diagnostic pop 5180 struct ITagAliasRegistry {
5181 virtual ~ITagAliasRegistry();
5183 virtual TagAlias
const* find( std::string
const& alias )
const = 0;
5184 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
5186 static ITagAliasRegistry
const&
get();
5194 class TestSpecParser {
5195 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5197 Mode lastMode = None;
5198 bool m_exclusion =
false;
5199 std::size_t m_pos = 0;
5200 std::size_t m_realPatternPos = 0;
5202 std::string m_substring;
5203 std::string m_patternName;
5204 std::vector<std::size_t> m_escapeChars;
5205 TestSpec::Filter m_currentFilter;
5206 TestSpec m_testSpec;
5207 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5210 TestSpecParser( ITagAliasRegistry
const& tagAliases );
5212 TestSpecParser& parse( std::string
const& arg );
5213 TestSpec testSpec();
5216 bool visitChar(
char c );
5217 void startNewMode( Mode mode );
5218 bool processNoneChar(
char c );
5219 void processNameChar(
char c );
5220 bool processOtherChar(
char c );
5223 bool isControlChar(
char c )
const;
5224 void saveLastMode();
5225 void revertBackToLastMode();
5230 std::string preprocessPattern();
5232 void addNamePattern();
5234 void addTagPattern();
5236 inline void addCharToPattern(
char c) {
5243 TestSpec parseTestSpec( std::string
const& arg );
5248 #pragma clang diagnostic pop 5258 #ifndef CATCH_CONFIG_CONSOLE_WIDTH 5259 #define CATCH_CONFIG_CONSOLE_WIDTH 80 5267 bool listTests =
false;
5268 bool listTags =
false;
5269 bool listReporters =
false;
5270 bool listTestNamesOnly =
false;
5272 bool showSuccessfulTests =
false;
5273 bool shouldDebugBreak =
false;
5274 bool noThrow =
false;
5275 bool showHelp =
false;
5276 bool showInvisibles =
false;
5277 bool filenamesAsTags =
false;
5278 bool libIdentify =
false;
5280 int abortAfter = -1;
5283 bool benchmarkNoAnalysis =
false;
5284 unsigned int benchmarkSamples = 100;
5285 double benchmarkConfidenceInterval = 0.95;
5286 unsigned int benchmarkResamples = 100000;
5287 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5292 double minDuration = -1;
5297 std::string outputFilename;
5299 std::string processName;
5300 #ifndef CATCH_CONFIG_DEFAULT_REPORTER 5301 #define CATCH_CONFIG_DEFAULT_REPORTER "console" 5303 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5304 #undef CATCH_CONFIG_DEFAULT_REPORTER 5306 std::vector<std::string> testsOrTags;
5307 std::vector<std::string> sectionsToRun;
5310 class Config :
public IConfig {
5314 Config( ConfigData
const& data );
5315 virtual ~Config() =
default;
5317 std::string
const& getFilename()
const;
5319 bool listTests()
const;
5320 bool listTestNamesOnly()
const;
5321 bool listTags()
const;
5322 bool listReporters()
const;
5324 std::string getProcessName()
const;
5325 std::string
const& getReporterName()
const;
5327 std::vector<std::string>
const& getTestsOrTags()
const override;
5328 std::vector<std::string>
const& getSectionsToRun()
const override;
5330 TestSpec
const& testSpec()
const override;
5331 bool hasTestFilters()
const override;
5333 bool showHelp()
const;
5336 bool allowThrows()
const override;
5337 std::ostream& stream()
const override;
5338 std::string name()
const override;
5339 bool includeSuccessfulResults()
const override;
5340 bool warnAboutMissingAssertions()
const override;
5341 bool warnAboutNoTests()
const override;
5343 double minDuration()
const override;
5345 unsigned int rngSeed()
const override;
5347 bool shouldDebugBreak()
const override;
5348 int abortAfter()
const override;
5349 bool showInvisibles()
const override;
5351 bool benchmarkNoAnalysis()
const override;
5352 int benchmarkSamples()
const override;
5353 double benchmarkConfidenceInterval()
const override;
5354 unsigned int benchmarkResamples()
const override;
5355 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5362 std::unique_ptr<IStream const> m_stream;
5363 TestSpec m_testSpec;
5364 bool m_hasTestFilters =
false;
5376 struct AssertionResultData
5378 AssertionResultData() =
delete;
5382 std::string message;
5383 mutable std::string reconstructedExpression;
5387 std::string reconstructExpression()
const;
5390 class AssertionResult {
5392 AssertionResult() =
delete;
5393 AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data );
5396 bool succeeded()
const;
5398 bool hasExpression()
const;
5399 bool hasMessage()
const;
5400 std::string getExpression()
const;
5401 std::string getExpressionInMacro()
const;
5402 bool hasExpandedExpression()
const;
5403 std::string getExpandedExpression()
const;
5404 std::string getMessage()
const;
5410 AssertionResultData m_resultData;
5416 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5423 namespace Benchmark {
5424 template <
typename Duration>
5427 Duration lower_bound;
5428 Duration upper_bound;
5429 double confidence_interval;
5431 template <
typename Duration2>
5432 operator Estimate<Duration2>()
const {
5433 return { point, lower_bound, upper_bound, confidence_interval };
5445 namespace Benchmark {
5446 struct OutlierClassification {
5447 int samples_seen = 0;
5451 int high_severe = 0;
5454 return low_severe + low_mild + high_mild + high_severe;
5463 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5470 #include <algorithm> 5474 struct ReporterConfig {
5475 explicit ReporterConfig(
IConfigPtr const& _fullConfig );
5477 ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream );
5479 std::ostream& stream()
const;
5483 std::ostream* m_stream;
5487 struct ReporterPreferences {
5488 bool shouldRedirectStdOut =
false;
5489 bool shouldReportAllAssertions =
false;
5492 template<
typename T>
5493 struct LazyStat :
Option<T> {
5494 LazyStat& operator=( T
const& _value ) {
5506 struct TestRunInfo {
5507 TestRunInfo( std::string
const& _name );
5511 GroupInfo( std::string
const& _name,
5512 std::size_t _groupIndex,
5513 std::size_t _groupsCount );
5516 std::size_t groupIndex;
5517 std::size_t groupsCounts;
5520 struct AssertionStats {
5521 AssertionStats( AssertionResult
const& _assertionResult,
5522 std::vector<MessageInfo>
const& _infoMessages,
5525 AssertionStats( AssertionStats
const& ) =
default;
5526 AssertionStats( AssertionStats && ) =
default;
5527 AssertionStats& operator = ( AssertionStats
const& ) =
delete;
5528 AssertionStats& operator = ( AssertionStats && ) =
delete;
5529 virtual ~AssertionStats();
5531 AssertionResult assertionResult;
5532 std::vector<MessageInfo> infoMessages;
5536 struct SectionStats {
5538 Counts const& _assertions,
5539 double _durationInSeconds,
5540 bool _missingAssertions );
5541 SectionStats( SectionStats
const& ) =
default;
5542 SectionStats( SectionStats && ) =
default;
5543 SectionStats& operator = ( SectionStats
const& ) =
default;
5544 SectionStats& operator = ( SectionStats && ) =
default;
5545 virtual ~SectionStats();
5549 double durationInSeconds;
5550 bool missingAssertions;
5553 struct TestCaseStats {
5556 std::string
const& _stdOut,
5557 std::string
const& _stdErr,
5560 TestCaseStats( TestCaseStats
const& ) =
default;
5561 TestCaseStats( TestCaseStats && ) =
default;
5562 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5563 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5564 virtual ~TestCaseStats();
5573 struct TestGroupStats {
5574 TestGroupStats( GroupInfo
const& _groupInfo,
5577 TestGroupStats( GroupInfo
const& _groupInfo );
5579 TestGroupStats( TestGroupStats
const& ) =
default;
5580 TestGroupStats( TestGroupStats && ) =
default;
5581 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5582 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5583 virtual ~TestGroupStats();
5585 GroupInfo groupInfo;
5590 struct TestRunStats {
5591 TestRunStats( TestRunInfo
const& _runInfo,
5595 TestRunStats( TestRunStats
const& ) =
default;
5596 TestRunStats( TestRunStats && ) =
default;
5597 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5598 TestRunStats& operator = ( TestRunStats && ) =
default;
5599 virtual ~TestRunStats();
5601 TestRunInfo runInfo;
5606 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5607 struct BenchmarkInfo {
5609 double estimatedDuration;
5612 unsigned int resamples;
5613 double clockResolution;
5617 template <
class Duration>
5618 struct BenchmarkStats {
5621 std::vector<Duration> samples;
5622 Benchmark::Estimate<Duration> mean;
5623 Benchmark::Estimate<Duration> standardDeviation;
5624 Benchmark::OutlierClassification outliers;
5625 double outlierVariance;
5627 template <
typename Duration2>
5628 operator BenchmarkStats<Duration2>()
const {
5629 std::vector<Duration2> samples2;
5630 samples2.reserve(samples.size());
5631 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration
d) {
return Duration2(
d); });
5634 std::move(samples2),
5642 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5644 struct IStreamingReporter {
5645 virtual ~IStreamingReporter() =
default;
5651 virtual ReporterPreferences getPreferences()
const = 0;
5653 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5655 virtual void reportInvalidArguments(std::string
const&) {}
5657 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5658 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5660 virtual void testCaseStarting(
TestCaseInfo const& testInfo ) = 0;
5661 virtual void sectionStarting(
SectionInfo const& sectionInfo ) = 0;
5663 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5664 virtual void benchmarkPreparing( std::string
const& ) {}
5665 virtual void benchmarkStarting( BenchmarkInfo
const& ) {}
5666 virtual void benchmarkEnded( BenchmarkStats<>
const& ) {}
5667 virtual void benchmarkFailed( std::string
const& ) {}
5668 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5670 virtual void assertionStarting(
AssertionInfo const& assertionInfo ) = 0;
5673 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5675 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5676 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5677 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5678 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5680 virtual void skipTest(
TestCaseInfo const& testInfo ) = 0;
5683 virtual void fatalErrorEncountered(
StringRef name );
5685 virtual bool isMulti()
const;
5687 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5689 struct IReporterFactory {
5690 virtual ~IReporterFactory();
5691 virtual IStreamingReporterPtr create( ReporterConfig
const& config )
const = 0;
5692 virtual std::string getDescription()
const = 0;
5696 struct IReporterRegistry {
5697 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5698 using Listeners = std::vector<IReporterFactoryPtr>;
5700 virtual ~IReporterRegistry();
5701 virtual IStreamingReporterPtr create( std::string
const& name,
IConfigPtr const& config )
const = 0;
5702 virtual FactoryMap
const& getFactories()
const = 0;
5703 virtual Listeners
const& getListeners()
const = 0;
5709 #include <algorithm> 5718 void prepareExpandedExpression(AssertionResult& result);
5721 std::string getFormattedDuration(
double duration );
5724 bool shouldShowDuration(
IConfig const& config,
double duration );
5726 std::string serializeFilters( std::vector<std::string>
const& container );
5728 template<
typename DerivedT>
5729 struct StreamingReporterBase : IStreamingReporter {
5731 StreamingReporterBase( ReporterConfig
const& _config )
5732 : m_config( _config.fullConfig() ),
5733 stream( _config.stream() )
5735 m_reporterPrefs.shouldRedirectStdOut =
false;
5736 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5737 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5740 ReporterPreferences getPreferences()
const override {
5741 return m_reporterPrefs;
5744 static std::set<Verbosity> getSupportedVerbosities() {
5748 ~StreamingReporterBase()
override =
default;
5750 void noMatchingTestCases(std::string
const&)
override {}
5752 void reportInvalidArguments(std::string
const&)
override {}
5754 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5755 currentTestRunInfo = _testRunInfo;
5758 void testGroupStarting(GroupInfo
const& _groupInfo)
override {
5759 currentGroupInfo = _groupInfo;
5762 void testCaseStarting(
TestCaseInfo const& _testInfo)
override {
5763 currentTestCaseInfo = _testInfo;
5765 void sectionStarting(
SectionInfo const& _sectionInfo)
override {
5766 m_sectionStack.push_back(_sectionInfo);
5769 void sectionEnded(SectionStats
const& )
override {
5770 m_sectionStack.pop_back();
5772 void testCaseEnded(TestCaseStats
const& )
override {
5773 currentTestCaseInfo.reset();
5775 void testGroupEnded(TestGroupStats
const& )
override {
5776 currentGroupInfo.reset();
5778 void testRunEnded(TestRunStats
const& )
override {
5779 currentTestCaseInfo.reset();
5780 currentGroupInfo.reset();
5781 currentTestRunInfo.reset();
5790 std::ostream& stream;
5792 LazyStat<TestRunInfo> currentTestRunInfo;
5793 LazyStat<GroupInfo> currentGroupInfo;
5794 LazyStat<TestCaseInfo> currentTestCaseInfo;
5796 std::vector<SectionInfo> m_sectionStack;
5797 ReporterPreferences m_reporterPrefs;
5800 template<
typename DerivedT>
5801 struct CumulativeReporterBase : IStreamingReporter {
5802 template<
typename T,
typename ChildNodeT>
5804 explicit Node( T
const& _value ) :
value( _value ) {}
5807 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5809 ChildNodes children;
5811 struct SectionNode {
5812 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5813 virtual ~SectionNode() =
default;
5815 bool operator == (SectionNode
const& other)
const {
5816 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5818 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5823 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5824 using Assertions = std::vector<AssertionStats>;
5825 ChildSections childSections;
5826 Assertions assertions;
5831 struct BySectionInfo {
5832 BySectionInfo(
SectionInfo const& other ) : m_other( other ) {}
5833 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
5834 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5835 return ((node->stats.sectionInfo.name == m_other.name) &&
5836 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5838 void operator=(BySectionInfo
const&) =
delete;
5844 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5845 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5846 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5848 CumulativeReporterBase( ReporterConfig
const& _config )
5849 : m_config( _config.fullConfig() ),
5850 stream( _config.stream() )
5852 m_reporterPrefs.shouldRedirectStdOut =
false;
5853 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5854 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5856 ~CumulativeReporterBase()
override =
default;
5858 ReporterPreferences getPreferences()
const override {
5859 return m_reporterPrefs;
5862 static std::set<Verbosity> getSupportedVerbosities() {
5866 void testRunStarting( TestRunInfo
const& )
override {}
5867 void testGroupStarting( GroupInfo
const& )
override {}
5869 void testCaseStarting(
TestCaseInfo const& )
override {}
5871 void sectionStarting(
SectionInfo const& sectionInfo )
override {
5872 SectionStats incompleteStats( sectionInfo,
Counts(), 0,
false );
5873 std::shared_ptr<SectionNode> node;
5874 if( m_sectionStack.empty() ) {
5875 if( !m_rootSection )
5876 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5877 node = m_rootSection;
5880 SectionNode& parentNode = *m_sectionStack.back();
5882 std::find_if( parentNode.childSections.begin(),
5883 parentNode.childSections.end(),
5884 BySectionInfo( sectionInfo ) );
5885 if( it == parentNode.childSections.end() ) {
5886 node = std::make_shared<SectionNode>( incompleteStats );
5887 parentNode.childSections.push_back( node );
5892 m_sectionStack.push_back( node );
5893 m_deepestSection = std::move(node);
5898 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5899 assert(!m_sectionStack.empty());
5905 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5906 SectionNode& sectionNode = *m_sectionStack.back();
5907 sectionNode.assertions.push_back(assertionStats);
5910 void sectionEnded(SectionStats
const& sectionStats)
override {
5911 assert(!m_sectionStack.empty());
5912 SectionNode& node = *m_sectionStack.back();
5913 node.stats = sectionStats;
5914 m_sectionStack.pop_back();
5916 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5917 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5918 assert(m_sectionStack.size() == 0);
5919 node->children.push_back(m_rootSection);
5920 m_testCases.push_back(node);
5921 m_rootSection.reset();
5923 assert(m_deepestSection);
5924 m_deepestSection->stdOut = testCaseStats.stdOut;
5925 m_deepestSection->stdErr = testCaseStats.stdErr;
5927 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5928 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5929 node->children.swap(m_testCases);
5930 m_testGroups.push_back(node);
5932 void testRunEnded(TestRunStats
const& testRunStats)
override {
5933 auto node = std::make_shared<TestRunNode>(testRunStats);
5934 node->children.swap(m_testGroups);
5935 m_testRuns.push_back(node);
5936 testRunEndedCumulative();
5938 virtual void testRunEndedCumulative() = 0;
5943 std::ostream& stream;
5944 std::vector<AssertionStats> m_assertions;
5945 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5946 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5947 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5949 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5951 std::shared_ptr<SectionNode> m_rootSection;
5952 std::shared_ptr<SectionNode> m_deepestSection;
5953 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5954 ReporterPreferences m_reporterPrefs;
5958 char const* getLineOfChars() {
5959 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5961 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5962 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5967 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5968 TestEventListenerBase( ReporterConfig
const& _config );
5970 static std::set<Verbosity> getSupportedVerbosities();
5973 bool assertionEnded(AssertionStats
const&)
override;
5997 BrightRed = Bright | Red,
5998 BrightGreen = Bright | Green,
5999 LightGrey = Bright | Grey,
6000 BrightWhite = Bright | White,
6001 BrightYellow = Bright | Yellow,
6004 FileName = LightGrey,
6005 Warning = BrightYellow,
6006 ResultError = BrightRed,
6007 ResultSuccess = BrightGreen,
6008 ResultExpectedFailure = Warning,
6013 OriginalExpression = Cyan,
6014 ReconstructedExpression = BrightYellow,
6016 SecondaryText = LightGrey,
6021 Colour( Code _colourCode );
6022 Colour( Colour&& other ) noexcept;
6023 Colour& operator=( Colour&& other ) noexcept;
6027 static void use( Code _colourCode );
6030 bool m_moved =
false;
6033 std::ostream&
operator << ( std::ostream& os, Colour
const& );
6043 template<
typename T>
6044 class ReporterRegistrar {
6046 class ReporterFactory :
public IReporterFactory {
6048 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6049 return std::unique_ptr<T>(
new T( config ) );
6052 std::string getDescription()
const override {
6053 return T::getDescription();
6059 explicit ReporterRegistrar( std::string
const& name ) {
6064 template<
typename T>
6065 class ListenerRegistrar {
6067 class ListenerFactory :
public IReporterFactory {
6069 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6070 return std::unique_ptr<T>(
new T( config ) );
6072 std::string getDescription()
const override {
6073 return std::string();
6079 ListenerRegistrar() {
6085 #if !defined(CATCH_CONFIG_DISABLE) 6087 #define CATCH_REGISTER_REPORTER( name, reporterType ) \ 6088 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6089 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6090 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ 6091 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6093 #define CATCH_REGISTER_LISTENER( listenerType ) \ 6094 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6095 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6096 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ 6097 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6098 #else // CATCH_CONFIG_DISABLE 6100 #define CATCH_REGISTER_REPORTER(name, reporterType) 6101 #define CATCH_REGISTER_LISTENER(listenerType) 6103 #endif // CATCH_CONFIG_DISABLE 6111 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6113 using StreamingReporterBase::StreamingReporterBase;
6115 ~CompactReporter()
override;
6117 static std::string getDescription();
6119 void noMatchingTestCases(std::string
const& spec)
override;
6123 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6125 void sectionEnded(SectionStats
const& _sectionStats)
override;
6127 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6136 #if defined(_MSC_VER) 6137 #pragma warning(push) 6138 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 6145 struct SummaryColumn;
6148 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6149 std::unique_ptr<TablePrinter> m_tablePrinter;
6151 ConsoleReporter(ReporterConfig
const& config);
6152 ~ConsoleReporter()
override;
6153 static std::string getDescription();
6155 void noMatchingTestCases(std::string
const& spec)
override;
6157 void reportInvalidArguments(std::string
const&arg)
override;
6161 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6163 void sectionStarting(
SectionInfo const& _sectionInfo)
override;
6164 void sectionEnded(SectionStats
const& _sectionStats)
override;
6166 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6167 void benchmarkPreparing(std::string
const& name)
override;
6168 void benchmarkStarting(BenchmarkInfo
const& info)
override;
6169 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6170 void benchmarkFailed(std::string
const& error)
override;
6171 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6173 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6174 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6175 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6176 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6181 void lazyPrintWithoutClosingBenchmarkTable();
6182 void lazyPrintRunInfo();
6183 void lazyPrintGroupInfo();
6184 void printTestCaseAndSectionHeader();
6186 void printClosedHeader(std::string
const& _name);
6187 void printOpenHeader(std::string
const& _name);
6191 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6193 void printTotals(
Totals const& totals);
6194 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row);
6196 void printTotalsDivider(
Totals const& totals);
6197 void printSummaryDivider();
6198 void printTestFilters();
6201 bool m_headerPrinted =
false;
6206 #if defined(_MSC_VER) 6207 #pragma warning(pop) 6218 enum class XmlFormatting {
6224 XmlFormatting
operator | (XmlFormatting lhs, XmlFormatting rhs);
6225 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6229 enum ForWhat { ForTextNodes, ForAttributes };
6231 XmlEncode( std::string
const& str, ForWhat forWhat = ForTextNodes );
6233 void encodeTo( std::ostream& os )
const;
6235 friend std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode );
6245 class ScopedElement {
6247 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6249 ScopedElement( ScopedElement&& other ) noexcept;
6250 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6254 ScopedElement& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6256 template<
typename T>
6257 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
6258 m_writer->writeAttribute( name, attribute );
6263 mutable XmlWriter* m_writer =
nullptr;
6264 XmlFormatting m_fmt;
6270 XmlWriter( XmlWriter
const& ) =
delete;
6271 XmlWriter& operator=( XmlWriter
const& ) =
delete;
6273 XmlWriter& startElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6275 ScopedElement scopedElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6277 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6279 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute );
6281 XmlWriter& writeAttribute( std::string
const& name,
bool attribute );
6283 template<
typename T>
6284 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
6287 return writeAttribute( name, rss.
str() );
6290 XmlWriter& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6292 XmlWriter& writeComment(std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6294 void writeStylesheetRef( std::string
const& url );
6296 XmlWriter& writeBlankLine();
6298 void ensureTagClosed();
6302 void applyFormatting(XmlFormatting fmt);
6304 void writeDeclaration();
6306 void newlineIfNecessary();
6308 bool m_tagIsOpen =
false;
6309 bool m_needsNewline =
false;
6310 std::vector<std::string> m_tags;
6311 std::string m_indent;
6320 class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6322 JunitReporter(ReporterConfig
const& _config);
6324 ~JunitReporter()
override;
6326 static std::string getDescription();
6328 void noMatchingTestCases(std::string
const& )
override;
6330 void testRunStarting(TestRunInfo
const& runInfo)
override;
6332 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6334 void testCaseStarting(
TestCaseInfo const& testCaseInfo)
override;
6335 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6337 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6339 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6341 void testRunEndedCumulative()
override;
6343 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6345 void writeTestCase(TestCaseNode
const& testCaseNode);
6347 void writeSection( std::string
const& className,
6348 std::string
const& rootName,
6349 SectionNode
const& sectionNode,
6350 bool testOkToFail );
6352 void writeAssertions(SectionNode
const& sectionNode);
6353 void writeAssertion(AssertionStats
const& stats);
6357 std::string stdOutForSuite;
6358 std::string stdErrForSuite;
6359 unsigned int unexpectedExceptions = 0;
6360 bool m_okToFail =
false;
6369 class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6371 XmlReporter(ReporterConfig
const& _config);
6373 ~XmlReporter()
override;
6375 static std::string getDescription();
6377 virtual std::string getStylesheetRef()
const;
6383 void noMatchingTestCases(std::string
const&
s)
override;
6385 void testRunStarting(TestRunInfo
const& testInfo)
override;
6387 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6389 void testCaseStarting(
TestCaseInfo const& testInfo)
override;
6391 void sectionStarting(
SectionInfo const& sectionInfo)
override;
6395 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6397 void sectionEnded(SectionStats
const& sectionStats)
override;
6399 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6401 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6403 void testRunEnded(TestRunStats
const& testRunStats)
override;
6405 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6406 void benchmarkPreparing(std::string
const& name)
override;
6407 void benchmarkStarting(BenchmarkInfo
const&)
override;
6408 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6409 void benchmarkFailed(std::string
const&)
override;
6410 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6413 Timer m_testCaseTimer;
6415 int m_sectionDepth = 0;
6425 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6450 namespace Benchmark {
6451 template <
typename Clock>
6452 using ClockDuration =
typename Clock::duration;
6453 template <
typename Clock>
6454 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6456 template <
typename Clock>
6457 using TimePoint =
typename Clock::time_point;
6459 using default_clock = std::chrono::steady_clock;
6461 template <
typename Clock>
6463 TimePoint<Clock> operator()()
const {
6464 return Clock::now();
6468 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6478 #if defined(_MSC_VER) 6483 namespace Benchmark {
6484 #if defined(__GNUC__) || defined(__clang__) 6485 template <
typename T>
6486 inline void keep_memory(T* p) {
6487 asm volatile(
"" : :
"g"(p) :
"memory");
6489 inline void keep_memory() {
6490 asm volatile(
"" : : :
"memory");
6494 inline void optimizer_barrier() { keep_memory(); }
6496 #elif defined(_MSC_VER) 6498 #pragma optimize("", off) 6499 template <
typename T>
6500 inline void keep_memory(T* p) {
6502 *
reinterpret_cast<char volatile*
>(p) = *reinterpret_cast<char const volatile*>(p);
6505 #pragma optimize("", on) 6508 inline void optimizer_barrier() {
6509 std::atomic_thread_fence(std::memory_order_seq_cst);
6515 template <
typename T>
6516 inline void deoptimize_value(T&& x) {
6520 template <
typename Fn,
typename... Args>
6521 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<!std::is_same<void, decltype(fn(args...))>
::value>::type {
6522 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6525 template <
typename Fn,
typename... Args>
6526 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<std::is_same<void, decltype(fn(args...))>
::value>::type {
6527 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6538 #include <type_traits> 6542 namespace Benchmark {
6544 template <
typename T>
6545 struct CompleteType {
using type = T; };
6547 struct CompleteType<void> {
struct type {}; };
6549 template <
typename T>
6550 using CompleteType_t =
typename CompleteType<T>::type;
6552 template <
typename Result>
6553 struct CompleteInvoker {
6554 template <
typename Fun,
typename... Args>
6555 static Result invoke(Fun&& fun, Args&&... args) {
6556 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6560 struct CompleteInvoker<void> {
6561 template <
typename Fun,
typename... Args>
6562 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6563 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6569 template <
typename Fun,
typename... Args>
6570 CompleteType_t<
FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6571 return CompleteInvoker<
FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6574 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6577 template <
typename Fun>
6578 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6580 return Detail::complete_invoke(std::forward<Fun>(fun));
6591 namespace Benchmark {
6593 struct ChronometerConcept {
6594 virtual void start() = 0;
6595 virtual void finish() = 0;
6596 virtual ~ChronometerConcept() =
default;
6598 template <
typename Clock>
6599 struct ChronometerModel final :
public ChronometerConcept {
6600 void start()
override { started = Clock::now(); }
6601 void finish()
override { finished = Clock::now(); }
6603 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6605 TimePoint<Clock> started;
6606 TimePoint<Clock> finished;
6610 struct Chronometer {
6612 template <
typename Fun>
6613 void measure(Fun&& fun) { measure(std::forward<Fun>(fun),
is_callable<Fun(
int)>()); }
6615 int runs()
const {
return k; }
6617 Chronometer(Detail::ChronometerConcept& meter,
int k)
6622 template <
typename Fun>
6623 void measure(Fun&& fun, std::false_type) {
6624 measure([&fun](
int) {
return fun(); }, std::true_type());
6627 template <
typename Fun>
6628 void measure(Fun&& fun, std::true_type) {
6629 Detail::optimizer_barrier();
6631 for (
int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6633 Detail::optimizer_barrier();
6636 Detail::ChronometerConcept* impl;
6649 namespace Benchmark {
6650 template <
typename Duration>
6651 struct EnvironmentEstimate {
6653 OutlierClassification outliers;
6655 template <
typename Duration2>
6656 operator EnvironmentEstimate<Duration2>()
const {
6657 return { mean, outliers };
6660 template <
typename Clock>
6661 struct Environment {
6662 using clock_type = Clock;
6663 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6664 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6681 #include <type_traits> 6686 namespace Benchmark {
6688 template <
typename T>
6689 using Decay =
typename std::decay<T>::type;
6690 template <
typename T,
typename U>
6692 : std::is_same<Decay<T>, Decay<U>> {};
6701 struct BenchmarkFunction {
6704 virtual void call(Chronometer meter)
const = 0;
6705 virtual callable* clone()
const = 0;
6706 virtual ~callable() =
default;
6708 template <
typename Fun>
6709 struct model :
public callable {
6710 model(Fun&& fun) : fun(std::move(fun)) {}
6711 model(Fun
const& fun) : fun(fun) {}
6713 model<Fun>* clone()
const override {
return new model<Fun>(*this); }
6715 void call(Chronometer meter)
const override {
6718 void call(Chronometer meter, std::true_type)
const {
6721 void call(Chronometer meter, std::false_type)
const {
6728 struct do_nothing {
void operator()()
const {} };
6730 template <
typename T>
6731 BenchmarkFunction(model<T>* c) :
f(c) {}
6735 :
f(
new model<do_nothing>{ {} }) {}
6737 template <
typename Fun,
6739 BenchmarkFunction(Fun&& fun)
6740 :
f(
new model<
typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6742 BenchmarkFunction(BenchmarkFunction&& that)
6743 :
f(std::move(that.f)) {}
6745 BenchmarkFunction(BenchmarkFunction
const& that)
6746 :
f(that.f->clone()) {}
6748 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6749 f = std::move(that.f);
6753 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6754 f.reset(that.f->clone());
6758 void operator()(Chronometer meter)
const {
f->call(meter); }
6761 std::unique_ptr<callable>
f;
6773 #include <type_traits> 6777 namespace Benchmark {
6779 template <
typename Fun>
6781 void operator()(
int k)
const {
6782 for (
int i = 0; i < k; ++i) {
6788 template <
typename Fun>
6789 repeater<typename std::decay<Fun>::type>
repeat(Fun&& fun) {
6790 return { std::forward<Fun>(fun) };
6813 #include <type_traits> 6816 namespace Benchmark {
6817 template <
typename Duration,
typename Result>
6823 template <
typename Clock,
typename Func,
typename... Args>
6824 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<
FunctionReturnType<Func, Args...>>>;
6832 namespace Benchmark {
6834 template <
typename Clock,
typename Fun,
typename... Args>
6835 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6836 auto start = Clock::now();
6837 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6838 auto end = Clock::now();
6839 auto delta = end -
start;
6840 return { delta, std::forward<decltype(r)>(r), 1 };
6848 #include <type_traits> 6851 namespace Benchmark {
6853 template <
typename Clock,
typename Fun>
6854 TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6855 return Detail::measure<Clock>(fun, iters);
6857 template <
typename Clock,
typename Fun>
6858 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6859 Detail::ChronometerModel<Clock> meter;
6860 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6862 return { meter.elapsed(), std::move(result), iters };
6865 template <
typename Clock,
typename Fun>
6868 struct optimized_away_error : std::exception {
6869 const char* what()
const noexcept
override {
6870 return "could not measure benchmark, maybe it was optimized away";
6874 template <
typename Clock,
typename Fun>
6875 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6877 while (iters < (1 << 30)) {
6880 if (Timing.elapsed >= how_long) {
6881 return { Timing.elapsed, std::move(Timing.result), iters };
6892 #include <algorithm> 6896 namespace Benchmark {
6897 template <
typename Duration>
6898 struct ExecutionPlan {
6899 int iterations_per_sample;
6900 Duration estimated_duration;
6901 Detail::BenchmarkFunction benchmark;
6902 Duration warmup_time;
6903 int warmup_iterations;
6905 template <
typename Duration2>
6906 operator ExecutionPlan<Duration2>()
const {
6907 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6910 template <
typename Clock>
6911 std::vector<FloatDuration<Clock>> run(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
6913 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
Detail::repeat(now<Clock>{}));
6915 std::vector<FloatDuration<Clock>> times;
6917 std::generate_n(std::back_inserter(times), cfg.
benchmarkSamples(), [this, env] {
6918 Detail::ChronometerModel<Clock> model;
6919 this->benchmark(Chronometer(model, iterations_per_sample));
6920 auto sample_time = model.elapsed() - env.clock_cost.mean;
6921 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6922 return sample_time / iterations_per_sample;
6941 #include <algorithm> 6942 #include <functional> 6953 namespace Benchmark {
6955 using sample = std::vector<double>;
6957 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6959 template <
typename Iterator>
6960 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6961 std::vector<double> copy(first, last);
6963 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6964 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6966 auto los = q1 - (iqr * 3.);
6967 auto lom = q1 - (iqr * 1.5);
6968 auto him = q3 + (iqr * 1.5);
6969 auto his = q3 + (iqr * 3.);
6971 OutlierClassification o;
6972 for (; first != last; ++first) {
6974 if (t < los) ++o.low_severe;
6975 else if (t < lom) ++o.low_mild;
6976 else if (t > his) ++o.high_severe;
6977 else if (t > him) ++o.high_mild;
6983 template <
typename Iterator>
6984 double mean(Iterator first, Iterator last) {
6985 auto count = last - first;
6986 double sum = std::accumulate(first, last, 0.);
6990 template <
typename URng,
typename Iterator,
typename Estimator>
6991 sample resample(URng&
rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
6992 auto n = last - first;
6993 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6996 out.reserve(resamples);
6997 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
6998 std::vector<double> resampled;
6999 resampled.reserve(n);
7000 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
return first[dist(rng)]; });
7001 return estimator(resampled.begin(), resampled.end());
7003 std::sort(out.begin(), out.end());
7007 template <
typename Estimator,
typename Iterator>
7008 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7009 auto n = last - first;
7010 auto second = std::next(first);
7014 for (
auto it = first; it != last; ++it) {
7015 std::iter_swap(it, first);
7016 results.push_back(estimator(second, last));
7022 inline double normal_cdf(
double x) {
7023 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7026 double erfc_inv(
double x);
7028 double normal_quantile(
double p);
7030 template <
typename Iterator,
typename Estimator>
7031 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last, sample
const& resample, Estimator&& estimator) {
7032 auto n_samples = last - first;
7034 double point = estimator(first, last);
7036 if (n_samples == 1)
return { point, point, point, confidence_level };
7038 sample jack = jackknife(estimator, first, last);
7039 double jack_mean = mean(jack.begin(), jack.end());
7040 double sum_squares, sum_cubes;
7041 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> {
7042 auto d = jack_mean - x;
7045 return { sqcb.first + d2, sqcb.second + d3 };
7048 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7049 int n =
static_cast<int>(resample.size());
7050 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) {
return x < point; }) / (
double)n;
7052 if (prob_n == 0)
return { point, point, point, confidence_level };
7054 double bias = normal_quantile(prob_n);
7055 double z1 = normal_quantile((1. - confidence_level) / 2.);
7057 auto cumn = [n](
double x) ->
int {
7058 return std::lround(normal_cdf(x) * n); };
7059 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7060 double b1 = bias + z1;
7061 double b2 = bias - z1;
7064 auto lo = (std::max)(cumn(a1), 0);
7065 auto hi = (std::min)(cumn(a2), n - 1);
7067 return { point, resample[lo], resample[hi], confidence_level };
7070 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7072 struct bootstrap_analysis {
7073 Estimate<double> mean;
7074 Estimate<double> standard_deviation;
7075 double outlier_variance;
7078 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7084 #include <algorithm> 7091 namespace Benchmark {
7093 template <
typename Clock>
7094 std::vector<double> resolution(
int k) {
7095 std::vector<TimePoint<Clock>> times;
7096 times.reserve(k + 1);
7097 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7099 std::vector<double> deltas;
7101 std::transform(std::next(times.begin()), times.end(), times.begin(),
7102 std::back_inserter(deltas),
7103 [](TimePoint<Clock> a, TimePoint<Clock> b) {
return static_cast<double>((a - b).count()); });
7108 const auto warmup_iterations = 10000;
7109 const auto warmup_time = std::chrono::milliseconds(100);
7110 const auto minimum_ticks = 1000;
7111 const auto warmup_seed = 10000;
7112 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7113 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7114 const auto clock_cost_estimation_tick_limit = 100000;
7115 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7116 const auto clock_cost_estimation_iterations = 10000;
7118 template <
typename Clock>
7120 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7123 template <
typename Clock>
7124 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7125 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7128 FloatDuration<Clock>(mean(r.begin(), r.end())),
7129 classify_outliers(r.begin(), r.end()),
7132 template <
typename Clock>
7133 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7134 auto time_limit = (std::min)(
7135 resolution * clock_cost_estimation_tick_limit,
7136 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7137 auto time_clock = [](
int k) {
7138 return Detail::measure<Clock>([k] {
7139 for (
int i = 0; i < k; ++i) {
7140 volatile auto ignored = Clock::now();
7146 int iters = clock_cost_estimation_iterations;
7147 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7148 std::vector<double> times;
7149 int nsamples =
static_cast<int>(std::ceil(time_limit / r.elapsed));
7150 times.reserve(nsamples);
7151 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7152 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7155 FloatDuration<Clock>(mean(times.begin(), times.end())),
7156 classify_outliers(times.begin(), times.end()),
7160 template <
typename Clock>
7161 Environment<FloatDuration<Clock>> measure_environment() {
7162 static Environment<FloatDuration<Clock>>* env =
nullptr;
7167 auto iters = Detail::warmup<Clock>();
7168 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7169 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7171 env =
new Environment<FloatDuration<Clock>>{ resolution, cost };
7189 #include <algorithm> 7195 namespace Benchmark {
7196 template <
typename Duration>
7197 struct SampleAnalysis {
7198 std::vector<Duration> samples;
7199 Estimate<Duration> mean;
7200 Estimate<Duration> standard_deviation;
7201 OutlierClassification outliers;
7202 double outlier_variance;
7204 template <
typename Duration2>
7205 operator SampleAnalysis<Duration2>()
const {
7206 std::vector<Duration2> samples2;
7207 samples2.reserve(samples.size());
7208 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration
d) {
return Duration2(
d); });
7210 std::move(samples2),
7222 #include <algorithm> 7227 namespace Benchmark {
7229 template <
typename Duration,
typename Iterator>
7230 SampleAnalysis<Duration> analyse(
const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7232 std::vector<double> samples;
7233 samples.reserve(last - first);
7234 std::transform(first, last, std::back_inserter(samples), [](Duration
d) {
return d.count(); });
7237 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7239 auto wrap_estimate = [](Estimate<double> e) {
7240 return Estimate<Duration> {
7242 Duration(e.lower_bound),
7243 Duration(e.upper_bound),
7244 e.confidence_interval,
7247 std::vector<Duration> samples2;
7248 samples2.reserve(samples.size());
7249 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
double d) {
return Duration(d); });
7251 std::move(samples2),
7252 wrap_estimate(analysis.mean),
7253 wrap_estimate(analysis.standard_deviation),
7255 analysis.outlier_variance,
7258 std::vector<Duration> samples;
7259 samples.reserve(last - first);
7261 Duration mean = Duration(0);
7263 for (
auto it = first; it < last; ++it, ++i) {
7264 samples.push_back(Duration(*it));
7265 mean += Duration(*it);
7271 Estimate<Duration>{mean, mean, mean, 0.0},
7272 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7273 OutlierClassification{},
7283 #include <algorithm> 7284 #include <functional> 7290 namespace Benchmark {
7292 Benchmark(std::string &&name)
7293 : name(std::move(name)) {}
7295 template <
class FUN>
7296 Benchmark(std::string &&name, FUN &&func)
7297 : fun(std::move(func)), name(std::move(name)) {}
7299 template <
typename Clock>
7300 ExecutionPlan<FloatDuration<Clock>> prepare(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
7301 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7302 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.
benchmarkWarmupTime()));
7303 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7304 int new_iters =
static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7305 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.
benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.
benchmarkWarmupTime()), Detail::warmup_iterations };
7308 template <
typename Clock = default_clock>
7312 auto env = Detail::measure_environment<Clock>();
7316 auto plan = user_code([&] {
7317 return prepare<Clock>(*cfg, env);
7320 BenchmarkInfo info {
7322 plan.estimated_duration.count(),
7323 plan.iterations_per_sample,
7324 cfg->benchmarkSamples(),
7325 cfg->benchmarkResamples(),
7326 env.clock_resolution.mean.count(),
7327 env.clock_cost.mean.count()
7332 auto samples = user_code([&] {
7333 return plan.template run<Clock>(*cfg, env);
7336 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7337 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7342 std::rethrow_exception(std::current_exception());
7347 template <
typename Fun,
7349 Benchmark & operator=(Fun func) {
7350 fun = Detail::BenchmarkFunction(func);
7355 explicit operator bool() {
7360 Detail::BenchmarkFunction fun;
7366 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1 7367 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2 7369 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\ 7370 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ 7371 BenchmarkName = [&](int benchmarkIndex) 7373 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\ 7374 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ 7383 #include <type_traits> 7386 namespace Benchmark {
7388 template <
typename T,
bool Destruct>
7389 struct ObjectStorage
7393 ObjectStorage() : data() {}
7395 ObjectStorage(
const ObjectStorage& other)
7397 new(&data) T(other.stored_object());
7400 ObjectStorage(ObjectStorage&& other)
7402 new(&data) T(std::move(other.stored_object()));
7405 ~ObjectStorage() { destruct_on_exit<T>(); }
7407 template <
typename... Args>
7408 void construct(Args&&... args)
7410 new (&data) T(std::forward<Args>(args)...);
7413 template <
bool AllowManualDestruction = !Destruct>
7414 typename std::enable_if<AllowManualDestruction>::type destruct()
7416 stored_object().~T();
7421 template <
typename U>
7422 void destruct_on_exit(
typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7424 template <
typename U>
7425 void destruct_on_exit(
typename std::enable_if<!Destruct, U>::type* = 0) { }
7427 T& stored_object() {
7428 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7431 T
const& stored_object()
const {
7432 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7439 template <
typename T>
7440 using storage_for = Detail::ObjectStorage<T, true>;
7442 template <
typename T>
7443 using destructable_object = Detail::ObjectStorage<T, false>;
7451 #endif // ! CATCH_CONFIG_IMPL_ONLY 7457 #pragma clang diagnostic push 7458 #pragma clang diagnostic ignored "-Wweak-vtables" 7469 namespace TestCaseTracking {
7471 struct NameAndLocation {
7475 NameAndLocation( std::string
const& _name,
SourceLineInfo const& _location );
7476 friend bool operator==(NameAndLocation
const& lhs, NameAndLocation
const& rhs) {
7477 return lhs.name == rhs.name
7478 && lhs.location == rhs.location;
7484 using ITrackerPtr = std::shared_ptr<ITracker>;
7487 NameAndLocation m_nameAndLocation;
7490 ITracker(NameAndLocation
const& nameAndLoc) :
7491 m_nameAndLocation(nameAndLoc)
7495 NameAndLocation
const& nameAndLocation()
const {
7496 return m_nameAndLocation;
7499 virtual ~ITracker();
7502 virtual bool isComplete()
const = 0;
7503 virtual bool isSuccessfullyCompleted()
const = 0;
7504 virtual bool isOpen()
const = 0;
7505 virtual bool hasChildren()
const = 0;
7506 virtual bool hasStarted()
const = 0;
7508 virtual ITracker& parent() = 0;
7511 virtual void close() = 0;
7512 virtual void fail() = 0;
7513 virtual void markAsNeedingAnotherRun() = 0;
7515 virtual void addChild( ITrackerPtr
const& child ) = 0;
7516 virtual ITrackerPtr findChild( NameAndLocation
const& nameAndLocation ) = 0;
7517 virtual void openChild() = 0;
7520 virtual bool isSectionTracker()
const = 0;
7521 virtual bool isGeneratorTracker()
const = 0;
7524 class TrackerContext {
7532 ITrackerPtr m_rootTracker;
7533 ITracker* m_currentTracker =
nullptr;
7534 RunState m_runState = NotStarted;
7538 ITracker& startRun();
7542 void completeCycle();
7544 bool completedCycle()
const;
7545 ITracker& currentTracker();
7546 void setCurrentTracker( ITracker* tracker );
7549 class TrackerBase :
public ITracker {
7556 CompletedSuccessfully,
7560 using Children = std::vector<ITrackerPtr>;
7561 TrackerContext& m_ctx;
7563 Children m_children;
7564 CycleState m_runState = NotStarted;
7567 TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7569 bool isComplete()
const override;
7570 bool isSuccessfullyCompleted()
const override;
7571 bool isOpen()
const override;
7572 bool hasChildren()
const override;
7573 bool hasStarted()
const override {
7574 return m_runState != NotStarted;
7577 void addChild( ITrackerPtr
const& child )
override;
7579 ITrackerPtr findChild( NameAndLocation
const& nameAndLocation )
override;
7580 ITracker& parent()
override;
7582 void openChild()
override;
7584 bool isSectionTracker()
const override;
7585 bool isGeneratorTracker()
const override;
7589 void close()
override;
7590 void fail()
override;
7591 void markAsNeedingAnotherRun()
override;
7594 void moveToParent();
7598 class SectionTracker :
public TrackerBase {
7599 std::vector<std::string> m_filters;
7600 std::string m_trimmed_name;
7602 SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7604 bool isSectionTracker()
const override;
7606 bool isComplete()
const override;
7608 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation );
7612 void addInitialFilters( std::vector<std::string>
const& filters );
7613 void addNextFilters( std::vector<std::string>
const& filters );
7615 std::vector<std::string>
const& getFilters()
const;
7617 std::string
const& trimmedName()
const;
7622 using TestCaseTracking::ITracker;
7623 using TestCaseTracking::TrackerContext;
7624 using TestCaseTracking::SectionTracker;
7634 struct LeakDetector {
7646 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 7651 #if defined(CATCH_CONFIG_USE_ASYNC) 7656 double erf_inv(
double x) {
7660 w = -log((1.0 - x) * (1.0 + x));
7664 p = -3.6444120640178196996e-21;
7665 p = -1.685059138182016589e-19 + p * w;
7666 p = 1.2858480715256400167e-18 + p * w;
7667 p = 1.115787767802518096e-17 + p * w;
7668 p = -1.333171662854620906e-16 + p * w;
7669 p = 2.0972767875968561637e-17 + p * w;
7670 p = 6.6376381343583238325e-15 + p * w;
7671 p = -4.0545662729752068639e-14 + p * w;
7672 p = -8.1519341976054721522e-14 + p * w;
7673 p = 2.6335093153082322977e-12 + p * w;
7674 p = -1.2975133253453532498e-11 + p * w;
7675 p = -5.4154120542946279317e-11 + p * w;
7676 p = 1.051212273321532285e-09 + p * w;
7677 p = -4.1126339803469836976e-09 + p * w;
7678 p = -2.9070369957882005086e-08 + p * w;
7679 p = 4.2347877827932403518e-07 + p * w;
7680 p = -1.3654692000834678645e-06 + p * w;
7681 p = -1.3882523362786468719e-05 + p * w;
7682 p = 0.0001867342080340571352 + p * w;
7683 p = -0.00074070253416626697512 + p * w;
7684 p = -0.0060336708714301490533 + p * w;
7685 p = 0.24015818242558961693 + p * w;
7686 p = 1.6536545626831027356 + p * w;
7687 }
else if (w < 16.000000) {
7688 w = sqrt(w) - 3.250000;
7689 p = 2.2137376921775787049e-09;
7690 p = 9.0756561938885390979e-08 + p * w;
7691 p = -2.7517406297064545428e-07 + p * w;
7692 p = 1.8239629214389227755e-08 + p * w;
7693 p = 1.5027403968909827627e-06 + p * w;
7694 p = -4.013867526981545969e-06 + p * w;
7695 p = 2.9234449089955446044e-06 + p * w;
7696 p = 1.2475304481671778723e-05 + p * w;
7697 p = -4.7318229009055733981e-05 + p * w;
7698 p = 6.8284851459573175448e-05 + p * w;
7699 p = 2.4031110387097893999e-05 + p * w;
7700 p = -0.0003550375203628474796 + p * w;
7701 p = 0.00095328937973738049703 + p * w;
7702 p = -0.0016882755560235047313 + p * w;
7703 p = 0.0024914420961078508066 + p * w;
7704 p = -0.0037512085075692412107 + p * w;
7705 p = 0.005370914553590063617 + p * w;
7706 p = 1.0052589676941592334 + p * w;
7707 p = 3.0838856104922207635 + p * w;
7709 w = sqrt(w) - 5.000000;
7710 p = -2.7109920616438573243e-11;
7711 p = -2.5556418169965252055e-10 + p * w;
7712 p = 1.5076572693500548083e-09 + p * w;
7713 p = -3.7894654401267369937e-09 + p * w;
7714 p = 7.6157012080783393804e-09 + p * w;
7715 p = -1.4960026627149240478e-08 + p * w;
7716 p = 2.9147953450901080826e-08 + p * w;
7717 p = -6.7711997758452339498e-08 + p * w;
7718 p = 2.2900482228026654717e-07 + p * w;
7719 p = -9.9298272942317002539e-07 + p * w;
7720 p = 4.5260625972231537039e-06 + p * w;
7721 p = -1.9681778105531670567e-05 + p * w;
7722 p = 7.5995277030017761139e-05 + p * w;
7723 p = -0.00021503011930044477347 + p * w;
7724 p = -0.00013871931833623122026 + p * w;
7725 p = 1.0103004648645343977 + p * w;
7726 p = 4.8499064014085844221 + p * w;
7731 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7732 auto m = Catch::Benchmark::Detail::mean(first, last);
7733 double variance = std::accumulate(first, last, 0., [m](
double a,
double b) {
7734 double diff = b - m;
7735 return a + diff * diff;
7736 }) / (last - first);
7737 return std::sqrt(variance);
7743 namespace Benchmark {
7746 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7747 auto count = last - first;
7748 double idx = (count - 1) * k / static_cast<double>(q);
7749 int j =
static_cast<int>(idx);
7751 std::nth_element(first, first + j, last);
7753 if (g == 0)
return xj;
7755 auto xj1 = *std::min_element(first + (j + 1), last);
7756 return xj + g * (xj1 - xj);
7759 double erfc_inv(
double x) {
7760 return erf_inv(1.0 - x);
7763 double normal_quantile(
double p) {
7764 static const double ROOT_TWO = std::sqrt(2.0);
7766 double result = 0.0;
7767 assert(p >= 0 && p <= 1);
7768 if (p < 0 || p > 1) {
7772 result = -erfc_inv(2.0 * p);
7779 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7780 double sb = stddev.point;
7781 double mn = mean.point / n;
7782 double mg_min = mn / 2.;
7783 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7784 double sg2 = sg * sg;
7785 double sb2 = sb * sb;
7787 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7791 double k0 = -n * nd;
7792 double k1 = sb2 - n * sg2 + nd;
7793 double det = k1 * k1 - 4 * sg2 * k0;
7794 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7797 auto var_out = [n, sb2, sg2](
double c) {
7799 return (nc / n) * (sb2 - nc * sg2);
7802 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7805 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7808 static std::random_device entropy;
7811 auto n =
static_cast<int>(last - first);
7813 auto mean = &Detail::mean<std::vector<double>::iterator>;
7814 auto stddev = &standard_deviation;
7816 #if defined(CATCH_CONFIG_USE_ASYNC) 7817 auto Estimate = [=](double(*
f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7818 auto seed = entropy();
7819 return std::async(std::launch::async, [=] {
7820 std::mt19937
rng(seed);
7821 auto resampled = resample(rng, n_resamples, first, last,
f);
7822 return bootstrap(confidence_level, first, last, resampled,
f);
7826 auto mean_future = Estimate(mean);
7827 auto stddev_future = Estimate(stddev);
7829 auto mean_estimate = mean_future.get();
7830 auto stddev_estimate = stddev_future.get();
7832 auto Estimate = [=](double(*
f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7833 auto seed = entropy();
7834 std::mt19937
rng(seed);
7835 auto resampled = resample(rng, n_resamples, first, last,
f);
7836 return bootstrap(confidence_level, first, last, resampled,
f);
7839 auto mean_estimate = Estimate(mean);
7840 auto stddev_estimate = Estimate(stddev);
7841 #endif // CATCH_USE_ASYNC 7843 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7845 return { mean_estimate, stddev_estimate, outlier_variance };
7851 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 7862 bool marginComparison(
double lhs,
double rhs,
double margin) {
7863 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7872 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7878 Approx Approx::custom() {
7882 Approx Approx::operator-()
const {
7884 temp.m_value = -temp.m_value;
7888 std::string Approx::toString()
const {
7894 bool Approx::equalityComparisonImpl(
const double other)
const {
7897 return marginComparison(m_value, other, m_margin)
7898 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7901 void Approx::setMargin(
double newMargin) {
7903 "Invalid Approx::margin: " << newMargin <<
'.' 7904 <<
" Approx::Margin has to be non-negative.");
7905 m_margin = newMargin;
7908 void Approx::setEpsilon(
double newEpsilon) {
7910 "Invalid Approx::epsilon: " << newEpsilon <<
'.' 7911 <<
" Approx::epsilon has to be in [0, 1]");
7912 m_epsilon = newEpsilon;
7917 namespace literals {
7937 bool isDebuggerActive();
7940 #ifdef CATCH_PLATFORM_MAC 7942 #if defined(__i386__) || defined(__x86_64__) 7943 #define CATCH_TRAP() __asm__("int $3\n" : : ) 7944 #elif defined(__aarch64__) 7945 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7948 #elif defined(CATCH_PLATFORM_IPHONE) 7951 #if defined(__i386__) || defined(__x86_64__) 7952 #define CATCH_TRAP() __asm__("int $3") 7953 #elif defined(__aarch64__) 7954 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7955 #elif defined(__arm__) && !defined(__thumb__) 7956 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") 7957 #elif defined(__arm__) && defined(__thumb__) 7958 #define CATCH_TRAP() __asm__(".inst 0xde01") 7961 #elif defined(CATCH_PLATFORM_LINUX) 7965 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) 7966 #define CATCH_TRAP() asm volatile ("int $3") 7967 #else // Fall back to the generic way. 7970 #define CATCH_TRAP() raise(SIGTRAP) 7972 #elif defined(_MSC_VER) 7973 #define CATCH_TRAP() __debugbreak() 7974 #elif defined(__MINGW32__) 7975 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7976 #define CATCH_TRAP() DebugBreak() 7979 #ifndef CATCH_BREAK_INTO_DEBUGGER 7981 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() 7983 #define CATCH_BREAK_INTO_DEBUGGER() []{}() 8004 class FatalConditionHandler {
8005 bool m_started =
false;
8010 void engage_platform();
8011 void disengage_platform();
8014 FatalConditionHandler();
8015 ~FatalConditionHandler();
8018 assert(!m_started &&
"Handler cannot be installed twice.");
8024 assert(m_started &&
"Handler cannot be uninstalled without being installed first");
8026 disengage_platform();
8031 class FatalConditionHandlerGuard {
8032 FatalConditionHandler* m_handler;
8034 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8035 m_handler(handler) {
8036 m_handler->engage();
8038 ~FatalConditionHandlerGuard() {
8039 m_handler->disengage();
8057 RunContext( RunContext
const& ) =
delete;
8058 RunContext& operator =( RunContext
const& ) =
delete;
8060 explicit RunContext(
IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8062 ~RunContext()
override;
8064 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8065 void testGroupEnded( std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8070 IStreamingReporter& reporter()
const;
8084 void handleUnexpectedExceptionNotThrown
8087 void handleUnexpectedInflightException
8089 std::string
const& message,
8091 void handleIncomplete
8098 bool sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions )
override;
8101 void sectionEndedEarly(
SectionEndInfo const& endInfo )
override;
8105 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 8106 void benchmarkPreparing( std::string
const& name )
override;
8107 void benchmarkStarting( BenchmarkInfo
const& info )
override;
8108 void benchmarkEnded( BenchmarkStats<>
const& stats )
override;
8109 void benchmarkFailed( std::string
const& error )
override;
8110 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 8112 void pushScopedMessage(
MessageInfo const& message )
override;
8113 void popScopedMessage(
MessageInfo const& message )
override;
8115 void emplaceUnscopedMessage(
MessageBuilder const& builder )
override;
8117 std::string getCurrentTestName()
const override;
8119 const AssertionResult* getLastResult()
const override;
8121 void exceptionEarlyReported()
override;
8123 void handleFatalErrorCondition(
StringRef message )
override;
8125 bool lastAssertionPassed()
override;
8127 void assertionPassed()
override;
8131 bool aborting()
const final;
8135 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8136 void invokeActiveTestCase();
8138 void resetAssertionInfo();
8139 bool testForMissingAssertions(
Counts& assertions );
8141 void assertionEnded( AssertionResult
const& result );
8152 void handleUnfinishedSections();
8154 TestRunInfo m_runInfo;
8156 TestCase const* m_activeTestCase =
nullptr;
8157 ITracker* m_testCaseTracker =
nullptr;
8162 IStreamingReporterPtr m_reporter;
8163 std::vector<MessageInfo> m_messages;
8164 std::vector<ScopedMessage> m_messageScopes;
8166 std::vector<SectionEndInfo> m_unfinishedSections;
8167 std::vector<ITracker*> m_activeSections;
8168 TrackerContext m_trackerContext;
8169 FatalConditionHandler m_fatalConditionhandler;
8170 bool m_lastAssertionPassed =
false;
8171 bool m_shouldReportUnexpected =
true;
8172 bool m_includeSuccessfulResults;
8175 void seedRng(
IConfig const& config);
8190 : m_isNegated( isNegated )
8195 LazyExpression::operator bool()
const {
8196 return m_transientExpression !=
nullptr;
8210 os <<
"{** error - unchecked empty expression requested **}";
8220 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8225 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8228 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8237 if( m_reaction.shouldDebugBreak ) {
8243 CATCH_BREAK_INTO_DEBUGGER();
8245 if (m_reaction.shouldThrow) {
8246 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 8249 CATCH_ERROR(
"Test failure requires aborting test!" );
8262 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8265 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8269 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8273 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8288 lazyExpression(_lazyExpression),
8289 resultType(_resultType) {}
8291 std::string AssertionResultData::reconstructExpression()
const {
8293 if( reconstructedExpression.empty() ) {
8294 if( lazyExpression ) {
8296 rss << lazyExpression;
8297 reconstructedExpression = rss.
str();
8300 return reconstructedExpression;
8303 AssertionResult::AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data )
8305 m_resultData( data )
8309 bool AssertionResult::succeeded()
const {
8319 return m_resultData.resultType;
8322 bool AssertionResult::hasExpression()
const {
8323 return !m_info.capturedExpression.empty();
8326 bool AssertionResult::hasMessage()
const {
8327 return !m_resultData.message.empty();
8330 std::string AssertionResult::getExpression()
const {
8332 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8336 expr += m_info.capturedExpression;
8343 std::string AssertionResult::getExpressionInMacro()
const {
8345 if( m_info.macroName.empty() )
8346 expr = static_cast<std::string>(m_info.capturedExpression);
8348 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8349 expr += m_info.macroName;
8351 expr += m_info.capturedExpression;
8357 bool AssertionResult::hasExpandedExpression()
const {
8358 return hasExpression() && getExpandedExpression() != getExpression();
8361 std::string AssertionResult::getExpandedExpression()
const {
8362 std::string expr = m_resultData.reconstructExpression();
8368 std::string AssertionResult::getMessage()
const {
8369 return m_resultData.message;
8372 return m_info.lineInfo;
8375 StringRef AssertionResult::getTestMacroName()
const {
8376 return m_info.macroName;
8405 #ifdef CLARA_CONFIG_CONSOLE_WIDTH 8406 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8407 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8409 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 8412 #pragma clang diagnostic push 8413 #pragma clang diagnostic ignored "-Wweak-vtables" 8414 #pragma clang diagnostic ignored "-Wexit-time-destructors" 8415 #pragma clang diagnostic ignored "-Wshadow" 8429 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8430 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 8433 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8434 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8437 #ifndef CLARA_CONFIG_OPTIONAL_TYPE 8438 #ifdef __has_include 8439 #if __has_include(<optional>) && __cplusplus >= 201703L 8441 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional 8463 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8464 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 8469 namespace TextFlow {
8471 inline auto isWhitespace(
char c) ->
bool {
8472 static std::string chars =
" \t\n\r";
8473 return chars.find(c) != std::string::npos;
8475 inline auto isBreakableBefore(
char c) ->
bool {
8476 static std::string chars =
"[({<|";
8477 return chars.find(c) != std::string::npos;
8479 inline auto isBreakableAfter(
char c) ->
bool {
8480 static std::string chars =
"])}>.,:;*+-=&/\\";
8481 return chars.find(c) != std::string::npos;
8487 std::vector<std::string> m_strings;
8488 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8489 size_t m_indent = 0;
8490 size_t m_initialIndent = std::string::npos;
8496 Column
const& m_column;
8497 size_t m_stringIndex = 0;
8502 bool m_suffix =
false;
8504 iterator(Column
const& column,
size_t stringIndex)
8506 m_stringIndex(stringIndex) {}
8508 auto line()
const -> std::string
const& {
return m_column.m_strings[m_stringIndex]; }
8510 auto isBoundary(
size_t at)
const ->
bool {
8512 assert(at <= line().size());
8514 return at == line().size() ||
8515 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8516 isBreakableBefore(line()[at]) ||
8517 isBreakableAfter(line()[at - 1]);
8521 assert(m_stringIndex < m_column.m_strings.size());
8524 auto width = m_column.m_width - indent();
8526 if (line()[m_pos] ==
'\n') {
8529 while (m_end < line().size() && line()[m_end] !=
'\n')
8532 if (m_end < m_pos + width) {
8533 m_len = m_end - m_pos;
8536 while (len > 0 && !isBoundary(m_pos + len))
8538 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8550 auto indent()
const ->
size_t {
8551 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8552 return initial == std::string::npos ? m_column.m_indent : initial;
8555 auto addIndentAndSuffix(std::string
const &plain)
const -> std::string {
8556 return std::string(indent(),
' ') + (m_suffix ? plain +
"-" : plain);
8560 using difference_type = std::ptrdiff_t;
8561 using value_type = std::string;
8562 using pointer = value_type * ;
8563 using reference = value_type & ;
8564 using iterator_category = std::forward_iterator_tag;
8566 explicit iterator(Column
const& column) : m_column(column) {
8567 assert(m_column.m_width > m_column.m_indent);
8568 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8574 auto operator *()
const -> std::string {
8575 assert(m_stringIndex < m_column.m_strings.size());
8576 assert(m_pos <= m_end);
8577 return addIndentAndSuffix(line().substr(m_pos, m_len));
8580 auto operator ++() -> iterator& {
8582 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8585 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8588 if (m_pos == line().size()) {
8592 if (m_stringIndex < m_column.m_strings.size())
8596 auto operator ++(
int) -> iterator {
8597 iterator prev(*
this);
8602 auto operator ==(iterator
const& other)
const ->
bool {
8604 m_pos == other.m_pos &&
8605 m_stringIndex == other.m_stringIndex &&
8606 &m_column == &other.m_column;
8608 auto operator !=(iterator
const& other)
const ->
bool {
8612 using const_iterator = iterator;
8614 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8616 auto width(
size_t newWidth) -> Column& {
8617 assert(newWidth > 0);
8621 auto indent(
size_t newIndent) -> Column& {
8622 m_indent = newIndent;
8625 auto initialIndent(
size_t newIndent) -> Column& {
8626 m_initialIndent = newIndent;
8630 auto width()
const ->
size_t {
return m_width; }
8631 auto begin()
const -> iterator {
return iterator(*
this); }
8632 auto end()
const -> iterator {
return { *
this, m_strings.size() }; }
8634 inline friend std::ostream&
operator << (std::ostream& os, Column
const& col) {
8636 for (
auto line : col) {
8646 auto operator + (Column
const& other)->Columns;
8648 auto toString()
const -> std::string {
8649 std::ostringstream oss;
8655 class Spacer :
public Column {
8658 explicit Spacer(
size_t spaceWidth) : Column(
"") {
8664 std::vector<Column> m_columns;
8672 std::vector<Column>
const& m_columns;
8673 std::vector<Column::iterator> m_iterators;
8674 size_t m_activeIterators;
8676 iterator(Columns
const& columns, EndTag)
8677 : m_columns(columns.m_columns),
8678 m_activeIterators(0) {
8679 m_iterators.reserve(m_columns.size());
8681 for (
auto const& col : m_columns)
8682 m_iterators.push_back(col.end());
8686 using difference_type = std::ptrdiff_t;
8687 using value_type = std::string;
8688 using pointer = value_type * ;
8689 using reference = value_type & ;
8690 using iterator_category = std::forward_iterator_tag;
8692 explicit iterator(Columns
const& columns)
8693 : m_columns(columns.m_columns),
8694 m_activeIterators(m_columns.size()) {
8695 m_iterators.reserve(m_columns.size());
8697 for (
auto const& col : m_columns)
8698 m_iterators.push_back(col.begin());
8701 auto operator ==(iterator
const& other)
const ->
bool {
8702 return m_iterators == other.m_iterators;
8704 auto operator !=(iterator
const& other)
const ->
bool {
8705 return m_iterators != other.m_iterators;
8707 auto operator *()
const -> std::string {
8708 std::string row, padding;
8710 for (
size_t i = 0; i < m_columns.size(); ++i) {
8711 auto width = m_columns[i].width();
8712 if (m_iterators[i] != m_columns[i].end()) {
8713 std::string col = *m_iterators[i];
8714 row += padding + col;
8715 if (col.size() < width)
8716 padding = std::string(width - col.size(),
' ');
8720 padding += std::string(width,
' ');
8725 auto operator ++() -> iterator& {
8726 for (
size_t i = 0; i < m_columns.size(); ++i) {
8727 if (m_iterators[i] != m_columns[i].end())
8732 auto operator ++(
int) -> iterator {
8733 iterator prev(*
this);
8738 using const_iterator = iterator;
8740 auto begin()
const -> iterator {
return iterator(*
this); }
8741 auto end()
const -> iterator {
return { *
this, iterator::EndTag() }; }
8743 auto operator += (Column
const& col) -> Columns& {
8744 m_columns.push_back(col);
8747 auto operator + (Column
const& col) -> Columns {
8748 Columns combined = *
this;
8753 inline friend std::ostream&
operator << (std::ostream& os, Columns
const& cols) {
8756 for (
auto line : cols) {
8766 auto toString()
const -> std::string {
8767 std::ostringstream oss;
8791 #include <algorithm> 8793 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) 8794 #define CATCH_PLATFORM_WINDOWS 8797 namespace Catch {
namespace clara {
8801 template<
typename L>
8802 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8804 template<
typename ClassT,
typename ReturnT,
typename... Args>
8805 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8806 static const bool isValid =
false;
8809 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8810 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8811 static const bool isValid =
true;
8812 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8813 using ReturnType = ReturnT;
8821 std::string m_exeName;
8822 std::vector<std::string> m_args;
8825 Args(
int argc,
char const*
const* argv )
8826 : m_exeName(argv[0]),
8827 m_args(argv + 1, argv + argc) {}
8829 Args( std::initializer_list<std::string> args )
8830 : m_exeName( *args.begin() ),
8831 m_args( args.begin()+1, args.end() )
8834 auto exeName()
const -> std::string {
8841 enum class TokenType {
8849 inline auto isOptPrefix(
char c ) ->
bool {
8851 #ifdef CATCH_PLATFORM_WINDOWS 8859 using Iterator = std::vector<std::string>::const_iterator;
8862 std::vector<Token> m_tokenBuffer;
8865 m_tokenBuffer.resize( 0 );
8868 while( it != itEnd && it->empty() )
8872 auto const &next = *it;
8873 if( isOptPrefix( next[0] ) ) {
8874 auto delimiterPos = next.find_first_of(
" :=" );
8875 if( delimiterPos != std::string::npos ) {
8876 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8877 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8879 if( next[1] !=
'-' && next.size() > 2 ) {
8880 std::string opt =
"- ";
8881 for(
size_t i = 1; i < next.size(); ++i ) {
8883 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8886 m_tokenBuffer.push_back( { TokenType::Option, next } );
8890 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8896 explicit TokenStream( Args
const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8898 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8902 explicit operator bool()
const {
8903 return !m_tokenBuffer.empty() || it != itEnd;
8906 auto count()
const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8908 auto operator*()
const -> Token {
8909 assert( !m_tokenBuffer.empty() );
8910 return m_tokenBuffer.front();
8913 auto operator->()
const -> Token
const * {
8914 assert( !m_tokenBuffer.empty() );
8915 return &m_tokenBuffer.front();
8918 auto operator++() -> TokenStream & {
8919 if( m_tokenBuffer.size() >= 2 ) {
8920 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8933 Ok, LogicError, RuntimeError
8937 ResultBase( Type type ) : m_type( type ) {}
8938 virtual ~ResultBase() =
default;
8940 virtual void enforceOk()
const = 0;
8945 template<
typename T>
8946 class ResultValueBase :
public ResultBase {
8948 auto value()
const -> T
const & {
8954 ResultValueBase( Type type ) : ResultBase( type ) {}
8956 ResultValueBase( ResultValueBase
const &other ) : ResultBase( other ) {
8957 if( m_type == ResultBase::Ok )
8958 new( &m_value ) T( other.m_value );
8961 ResultValueBase( Type, T
const &
value ) : ResultBase( Ok ) {
8962 new( &m_value ) T( value );
8965 auto operator=( ResultValueBase
const &other ) -> ResultValueBase & {
8966 if( m_type == ResultBase::Ok )
8968 ResultBase::operator=(other);
8969 if( m_type == ResultBase::Ok )
8970 new( &m_value ) T( other.m_value );
8974 ~ResultValueBase()
override {
8985 class ResultValueBase<void> :
public ResultBase {
8987 using ResultBase::ResultBase;
8990 template<
typename T =
void>
8991 class BasicResult :
public ResultValueBase<T> {
8993 template<
typename U>
8994 explicit BasicResult( BasicResult<U>
const &other )
8995 : ResultValueBase<T>( other.type() ),
8996 m_errorMessage( other.errorMessage() )
8998 assert( type() != ResultBase::Ok );
9001 template<
typename U>
9002 static auto ok( U
const &
value ) -> BasicResult {
return { ResultBase::Ok, value }; }
9003 static auto ok() -> BasicResult {
return { ResultBase::Ok }; }
9004 static auto logicError( std::string
const &message ) -> BasicResult {
return { ResultBase::LogicError, message }; }
9005 static auto runtimeError( std::string
const &message ) -> BasicResult {
return { ResultBase::RuntimeError, message }; }
9007 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9008 auto type()
const -> ResultBase::Type {
return m_type; }
9009 auto errorMessage()
const -> std::string {
return m_errorMessage; }
9012 void enforceOk()
const override {
9016 assert( m_type != ResultBase::LogicError );
9017 assert( m_type != ResultBase::RuntimeError );
9018 if( m_type != ResultBase::Ok )
9022 std::string m_errorMessage;
9024 BasicResult( ResultBase::Type type, std::string
const &message )
9025 : ResultValueBase<T>(type),
9026 m_errorMessage(message)
9028 assert( m_type != ResultBase::Ok );
9031 using ResultValueBase<T>::ResultValueBase;
9032 using ResultBase::m_type;
9035 enum class ParseResultType {
9036 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9042 ParseState( ParseResultType type, TokenStream
const &remainingTokens )
9044 m_remainingTokens( remainingTokens )
9047 auto type()
const -> ParseResultType {
return m_type; }
9048 auto remainingTokens()
const -> TokenStream {
return m_remainingTokens; }
9051 ParseResultType m_type;
9052 TokenStream m_remainingTokens;
9055 using Result = BasicResult<void>;
9056 using ParserResult = BasicResult<ParseResultType>;
9057 using InternalParseResult = BasicResult<ParseState>;
9059 struct HelpColumns {
9064 template<
typename T>
9065 inline auto convertInto( std::string
const &source, T& target ) -> ParserResult {
9066 std::stringstream ss;
9070 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9072 return ParserResult::ok( ParseResultType::Matched );
9074 inline auto convertInto( std::string
const &source, std::string& target ) -> ParserResult {
9076 return ParserResult::ok( ParseResultType::Matched );
9078 inline auto convertInto( std::string
const &source,
bool &target ) -> ParserResult {
9079 std::string srcLC = source;
9080 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
unsigned char c ) {
return static_cast<char>( std::tolower(c) ); } );
9081 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9083 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9086 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9087 return ParserResult::ok( ParseResultType::Matched );
9089 #ifdef CLARA_CONFIG_OPTIONAL_TYPE 9090 template<
typename T>
9091 inline auto convertInto( std::string
const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9093 auto result = convertInto( source, temp );
9095 target = std::move(temp);
9098 #endif // CLARA_CONFIG_OPTIONAL_TYPE 9109 virtual ~BoundRef() =
default;
9110 virtual auto isContainer()
const ->
bool {
return false; }
9111 virtual auto isFlag()
const ->
bool {
return false; }
9113 struct BoundValueRefBase : BoundRef {
9114 virtual auto setValue( std::string
const &arg ) -> ParserResult = 0;
9116 struct BoundFlagRefBase : BoundRef {
9117 virtual auto setFlag(
bool flag ) -> ParserResult = 0;
9118 virtual auto isFlag()
const ->
bool {
return true; }
9121 template<
typename T>
9122 struct BoundValueRef : BoundValueRefBase {
9125 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9127 auto setValue( std::string
const &arg ) -> ParserResult
override {
9128 return convertInto( arg, m_ref );
9132 template<
typename T>
9133 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9134 std::vector<T> &m_ref;
9136 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9138 auto isContainer()
const ->
bool override {
return true; }
9140 auto setValue( std::string
const &arg ) -> ParserResult
override {
9142 auto result = convertInto( arg, temp );
9144 m_ref.push_back( temp );
9149 struct BoundFlagRef : BoundFlagRefBase {
9152 explicit BoundFlagRef(
bool &ref ) : m_ref( ref ) {}
9154 auto setFlag(
bool flag ) -> ParserResult
override {
9156 return ParserResult::ok( ParseResultType::Matched );
9160 template<
typename ReturnType>
9161 struct LambdaInvoker {
9164 template<
typename L,
typename ArgType>
9165 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9166 return lambda( arg );
9171 struct LambdaInvoker<void> {
9172 template<
typename L,
typename ArgType>
9173 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9175 return ParserResult::ok( ParseResultType::Matched );
9179 template<
typename ArgType,
typename L>
9180 inline auto invokeLambda( L
const &lambda, std::string
const &arg ) -> ParserResult {
9182 auto result = convertInto( arg, temp );
9185 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9188 template<
typename L>
9189 struct BoundLambda : BoundValueRefBase {
9192 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9193 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9195 auto setValue( std::string
const &arg ) -> ParserResult
override {
9196 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9200 template<
typename L>
9201 struct BoundFlagLambda : BoundFlagRefBase {
9204 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9205 static_assert( std::is_same<
typename UnaryLambdaTraits<L>::ArgType,
bool>::
value,
"flags must be boolean" );
9207 explicit BoundFlagLambda( L
const &lambda ) : m_lambda( lambda ) {}
9209 auto setFlag(
bool flag ) -> ParserResult
override {
9210 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9214 enum class Optionality { Optional, Required };
9220 virtual ~ParserBase() =
default;
9221 virtual auto validate()
const -> Result {
return Result::ok(); }
9222 virtual auto parse( std::string
const& exeName, TokenStream
const &tokens)
const -> InternalParseResult = 0;
9223 virtual auto cardinality()
const ->
size_t {
return 1; }
9225 auto parse( Args
const &args )
const -> InternalParseResult {
9226 return parse( args.exeName(), TokenStream( args ) );
9230 template<
typename DerivedT>
9231 class ComposableParserImpl :
public ParserBase {
9233 template<
typename T>
9234 auto operator|( T
const &other )
const -> Parser;
9236 template<
typename T>
9237 auto operator+( T
const &other )
const -> Parser;
9241 template<
typename DerivedT>
9242 class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9244 Optionality m_optionality = Optionality::Optional;
9245 std::shared_ptr<BoundRef> m_ref;
9247 std::string m_description;
9249 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &ref ) : m_ref( ref ) {}
9252 template<
typename T>
9253 ParserRefImpl( T &ref, std::string
const &hint )
9254 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9258 template<
typename LambdaT>
9259 ParserRefImpl( LambdaT
const &ref, std::string
const &hint )
9260 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9264 auto operator()( std::string
const &description ) -> DerivedT & {
9265 m_description = description;
9266 return static_cast<DerivedT &
>( *this );
9269 auto optional() -> DerivedT & {
9270 m_optionality = Optionality::Optional;
9271 return static_cast<DerivedT &
>( *this );
9274 auto required() -> DerivedT & {
9275 m_optionality = Optionality::Required;
9276 return static_cast<DerivedT &
>( *this );
9279 auto isOptional()
const ->
bool {
9280 return m_optionality == Optionality::Optional;
9283 auto cardinality()
const ->
size_t override {
9284 if( m_ref->isContainer() )
9290 auto hint()
const -> std::string {
return m_hint; }
9293 class ExeName :
public ComposableParserImpl<ExeName> {
9294 std::shared_ptr<std::string> m_name;
9295 std::shared_ptr<BoundValueRefBase> m_ref;
9297 template<
typename LambdaT>
9298 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9299 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9303 ExeName() : m_name( std::make_shared<std::string>(
"<executable>" ) ) {}
9305 explicit ExeName( std::string &ref ) : ExeName() {
9306 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9309 template<
typename LambdaT>
9310 explicit ExeName( LambdaT
const& lambda ) : ExeName() {
9311 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9315 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9316 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9319 auto name()
const -> std::string {
return *m_name; }
9320 auto set( std::string
const& newName ) -> ParserResult {
9322 auto lastSlash = newName.find_last_of(
"\\/" );
9323 auto filename = ( lastSlash == std::string::npos )
9325 : newName.substr( lastSlash+1 );
9329 return m_ref->setValue( filename );
9331 return ParserResult::ok( ParseResultType::Matched );
9335 class Arg :
public ParserRefImpl<Arg> {
9337 using ParserRefImpl::ParserRefImpl;
9339 auto parse( std::string
const &, TokenStream
const &tokens )
const -> InternalParseResult
override {
9340 auto validationResult =
validate();
9341 if( !validationResult )
9342 return InternalParseResult( validationResult );
9344 auto remainingTokens = tokens;
9345 auto const &token = *remainingTokens;
9346 if( token.type != TokenType::Argument )
9347 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9349 assert( !m_ref->isFlag() );
9350 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9352 auto result = valueRef->setValue( remainingTokens->token );
9354 return InternalParseResult( result );
9356 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9360 inline auto normaliseOpt( std::string
const &optName ) -> std::string {
9361 #ifdef CATCH_PLATFORM_WINDOWS 9362 if( optName[0] ==
'/' )
9363 return "-" + optName.substr( 1 );
9369 class Opt :
public ParserRefImpl<Opt> {
9371 std::vector<std::string> m_optNames;
9374 template<
typename LambdaT>
9375 explicit Opt( LambdaT
const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9377 explicit Opt(
bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9379 template<
typename LambdaT>
9380 Opt( LambdaT
const &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9382 template<
typename T>
9383 Opt( T &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9385 auto operator[]( std::string
const &optName ) -> Opt & {
9386 m_optNames.push_back( optName );
9390 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9391 std::ostringstream oss;
9393 for(
auto const &opt : m_optNames ) {
9400 if( !m_hint.empty() )
9401 oss <<
" <" << m_hint <<
">";
9402 return { { oss.str(), m_description } };
9405 auto isMatch( std::string
const &optToken )
const ->
bool {
9406 auto normalisedToken = normaliseOpt( optToken );
9407 for(
auto const &name : m_optNames ) {
9408 if( normaliseOpt( name ) == normalisedToken )
9414 using ParserBase::parse;
9416 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9417 auto validationResult =
validate();
9418 if( !validationResult )
9419 return InternalParseResult( validationResult );
9421 auto remainingTokens = tokens;
9422 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9423 auto const &token = *remainingTokens;
9424 if( isMatch(token.token ) ) {
9425 if( m_ref->isFlag() ) {
9426 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>( m_ref.get() );
9427 auto result = flagRef->setFlag(
true );
9429 return InternalParseResult( result );
9430 if( result.value() == ParseResultType::ShortCircuitAll )
9431 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9433 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9435 if( !remainingTokens )
9436 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9437 auto const &argToken = *remainingTokens;
9438 if( argToken.type != TokenType::Argument )
9439 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9440 auto result = valueRef->setValue( argToken.token );
9442 return InternalParseResult( result );
9443 if( result.value() == ParseResultType::ShortCircuitAll )
9444 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9446 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9449 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9452 auto validate()
const -> Result
override {
9453 if( m_optNames.empty() )
9454 return Result::logicError(
"No options supplied to Opt" );
9455 for(
auto const &name : m_optNames ) {
9457 return Result::logicError(
"Option name cannot be empty" );
9458 #ifdef CATCH_PLATFORM_WINDOWS 9459 if( name[0] !=
'-' && name[0] !=
'/' )
9460 return Result::logicError(
"Option name must begin with '-' or '/'" );
9462 if( name[0] !=
'-' )
9463 return Result::logicError(
"Option name must begin with '-'" );
9466 return ParserRefImpl::validate();
9471 Help(
bool &showHelpFlag )
9472 : Opt([&](
bool flag ) {
9473 showHelpFlag = flag;
9474 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9477 static_cast<Opt &
>( *this )
9478 (
"display usage information")
9479 [
"-?"][
"-h"][
"--help"]
9484 struct Parser : ParserBase {
9486 mutable ExeName m_exeName;
9487 std::vector<Opt> m_options;
9488 std::vector<Arg> m_args;
9490 auto operator|=( ExeName
const &exeName ) -> Parser & {
9491 m_exeName = exeName;
9495 auto operator|=( Arg
const &arg ) -> Parser & {
9496 m_args.push_back(arg);
9500 auto operator|=( Opt
const &opt ) -> Parser & {
9501 m_options.push_back(opt);
9505 auto operator|=( Parser
const &other ) -> Parser & {
9506 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9507 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9511 template<
typename T>
9512 auto operator|( T
const &other )
const -> Parser {
9513 return Parser( *
this ) |= other;
9517 template<
typename T>
9518 auto operator+=( T
const &other ) -> Parser & {
return operator|=( other ); }
9519 template<
typename T>
9522 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9523 std::vector<HelpColumns> cols;
9524 for (
auto const &o : m_options) {
9525 auto childCols = o.getHelpColumns();
9526 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9531 void writeToStream( std::ostream &os )
const {
9532 if (!m_exeName.name().empty()) {
9533 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9534 bool required =
true, first =
true;
9535 for(
auto const &arg : m_args ) {
9540 if( arg.isOptional() && required ) {
9544 os <<
"<" << arg.hint() <<
">";
9545 if( arg.cardinality() == 0 )
9550 if( !m_options.empty() )
9552 os <<
"\n\nwhere options are:" << std::endl;
9555 auto rows = getHelpColumns();
9556 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9557 size_t optWidth = 0;
9558 for(
auto const &cols : rows )
9559 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9561 optWidth = (std::min)(optWidth, consoleWidth/2);
9563 for(
auto const &cols : rows ) {
9565 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9566 TextFlow::Spacer(4) +
9567 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9568 os << row << std::endl;
9572 friend auto operator<<( std::ostream &os, Parser
const &parser ) -> std::ostream& {
9573 parser.writeToStream( os );
9577 auto validate()
const -> Result
override {
9578 for(
auto const &opt : m_options ) {
9579 auto result = opt.validate();
9583 for(
auto const &arg : m_args ) {
9584 auto result = arg.validate();
9588 return Result::ok();
9591 using ParserBase::parse;
9593 auto parse( std::string
const& exeName, TokenStream
const &tokens )
const -> InternalParseResult
override {
9596 ParserBase
const* parser =
nullptr;
9599 const size_t totalParsers = m_options.size() + m_args.size();
9600 assert( totalParsers < 512 );
9602 ParserInfo parseInfos[512];
9606 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9607 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9610 m_exeName.set( exeName );
9612 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9613 while( result.value().remainingTokens() ) {
9614 bool tokenParsed =
false;
9616 for(
size_t i = 0; i < totalParsers; ++i ) {
9617 auto& parseInfo = parseInfos[i];
9618 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9619 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9622 if (result.value().type() != ParseResultType::NoMatch) {
9630 if( result.value().type() == ParseResultType::ShortCircuitAll )
9633 return InternalParseResult::runtimeError(
"Unrecognised token: " + result.value().remainingTokens()->token );
9640 template<
typename DerivedT>
9641 template<
typename T>
9643 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9648 using detail::Parser;
9660 using detail::ExeName;
9666 using detail::ParseResultType;
9669 using detail::ParserResult;
9675 #pragma clang diagnostic pop 9679 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9680 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9681 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9687 clara::Parser makeCommandLineParser( ConfigData& config );
9697 clara::Parser makeCommandLineParser( ConfigData& config ) {
9699 using namespace clara;
9701 auto const setWarning = [&]( std::string
const& warning ) {
9702 auto warningSet = [&]() {
9703 if( warning ==
"NoAssertions" )
9706 if ( warning ==
"NoTests" )
9713 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9714 config.warnings =
static_cast<WarnAbout::What>( config.warnings | warningSet );
9715 return ParserResult::ok( ParseResultType::Matched );
9717 auto const loadTestNamesFromFile = [&]( std::string
const& filename ) {
9718 std::ifstream
f( filename.c_str() );
9720 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'" );
9723 while( std::getline(
f, line ) ) {
9725 if( !line.empty() && !
startsWith( line,
'#' ) ) {
9727 line =
'"' + line +
'"';
9728 config.testsOrTags.push_back( line );
9729 config.testsOrTags.emplace_back(
"," );
9733 if(!config.testsOrTags.empty())
9734 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9736 return ParserResult::ok( ParseResultType::Matched );
9738 auto const setTestOrder = [&]( std::string
const& order ) {
9746 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'" );
9747 return ParserResult::ok( ParseResultType::Matched );
9749 auto const setRngSeed = [&]( std::string
const& seed ) {
9750 if( seed !=
"time" )
9751 return clara::detail::convertInto( seed, config.rngSeed );
9752 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9753 return ParserResult::ok( ParseResultType::Matched );
9755 auto const setColourUsage = [&]( std::string
const& useColour ) {
9756 auto mode =
toLower( useColour );
9760 else if( mode ==
"no" )
9762 else if( mode ==
"auto" )
9765 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9766 return ParserResult::ok( ParseResultType::Matched );
9768 auto const setWaitForKeypress = [&]( std::string
const& keypress ) {
9769 auto keypressLc =
toLower( keypress );
9770 if (keypressLc ==
"never")
9772 else if( keypressLc ==
"start" )
9774 else if( keypressLc ==
"exit" )
9776 else if( keypressLc ==
"both" )
9779 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9780 return ParserResult::ok( ParseResultType::Matched );
9782 auto const setVerbosity = [&]( std::string
const& verbosity ) {
9783 auto lcVerbosity =
toLower( verbosity );
9784 if( lcVerbosity ==
"quiet" )
9786 else if( lcVerbosity ==
"normal" )
9788 else if( lcVerbosity ==
"high" )
9791 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9792 return ParserResult::ok( ParseResultType::Matched );
9794 auto const setReporter = [&]( std::string
const& reporter ) {
9797 auto lcReporter =
toLower( reporter );
9798 auto result = factories.find( lcReporter );
9800 if( factories.end() != result )
9801 config.reporterName = lcReporter;
9803 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9804 return ParserResult::ok( ParseResultType::Matched );
9808 = ExeName( config.processName )
9809 | Help( config.showHelp )
9810 | Opt( config.listTests )
9811 ["-l"]["--list-tests"]
9812 (
"list all/matching test cases" )
9813 | Opt( config.listTags )
9814 ["-t"]["--list-tags"]
9815 (
"list all/matching tags" )
9816 | Opt( config.showSuccessfulTests )
9818 (
"include successful tests in output" )
9819 | Opt( config.shouldDebugBreak )
9821 (
"break into debugger on failure" )
9822 | Opt( config.noThrow )
9824 (
"skip exception tests" )
9825 | Opt( config.showInvisibles )
9826 ["-i"]["--invisibles"]
9827 (
"show invisibles (tabs, newlines)" )
9828 | Opt( config.outputFilename,
"filename" )
9830 (
"output filename" )
9831 | Opt( setReporter,
"name" )
9832 ["-r"]["--reporter"]
9833 (
"reporter to use (defaults to console)" )
9834 | Opt( config.name,
"name" )
9837 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9839 (
"abort at first failure" )
9840 | Opt( [&](
int x ){ config.abortAfter = x; },
"no. failures" )
9842 (
"abort after x failures" )
9843 | Opt( setWarning,
"warning name" )
9845 (
"enable warnings" )
9847 [
"-d"][
"--durations"]
9848 (
"show test durations" )
9849 | Opt( config.minDuration,
"seconds" )
9850 ["-D"]["--min-duration"]
9851 (
"show test durations for tests taking at least the given number of seconds" )
9852 | Opt( loadTestNamesFromFile,
"filename" )
9853 ["-f"]["--input-file"]
9854 (
"load test names to run from a file" )
9855 | Opt( config.filenamesAsTags )
9856 ["-#"]["--filenames-as-tags"]
9857 (
"adds a tag for the filename" )
9858 | Opt( config.sectionsToRun,
"section name" )
9860 (
"specify section to run" )
9862 ["-v"]["--verbosity"]
9863 (
"set output verbosity" )
9864 | Opt( config.listTestNamesOnly )
9865 ["--list-test-names-only"]
9866 (
"list all/matching test cases names only" )
9867 | Opt( config.listReporters )
9868 ["--list-reporters"]
9869 (
"list all reporters" )
9870 | Opt( setTestOrder,
"decl|lex|rand" )
9872 (
"test case order (defaults to decl)" )
9873 | Opt( setRngSeed,
"'time'|number" )
9875 (
"set a specific seed for random numbers" )
9876 | Opt( setColourUsage,
"yes|no" )
9878 (
"should output be colourised" )
9879 | Opt( config.libIdentify )
9881 (
"report name and version according to libidentify standard" )
9882 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9883 ["--wait-for-keypress"]
9884 (
"waits for a keypress before exiting" )
9885 | Opt( config.benchmarkSamples,
"samples" )
9886 ["--benchmark-samples"]
9887 (
"number of samples to collect (default: 100)" )
9888 | Opt( config.benchmarkResamples,
"resamples" )
9889 ["--benchmark-resamples"]
9890 (
"number of resamples for the bootstrap (default: 100000)" )
9891 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9892 ["--benchmark-confidence-interval"]
9893 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9894 | Opt( config.benchmarkNoAnalysis )
9895 ["--benchmark-no-analysis"]
9896 (
"perform only measurements; do not perform any analysis" )
9897 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9898 ["--benchmark-warmup-time"]
9899 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9900 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9901 (
"which test or tests to use" );
9916 return line == other.
line && (file == other.
file || std::strcmp(file, other.
file) == 0);
9921 return line < other.
line || ( line == other.
line && file != other.
file && (std::strcmp(file, other.
file) < 0));
9926 os << info.
file <<
'(' << info.
line <<
')';
9928 os << info.
file <<
':' << info.
line;
9934 return std::string();
9946 Config::Config( ConfigData
const& data )
9948 m_stream( openStream() )
9954 for (
auto& elem : m_data.testsOrTags) {
9957 for (
auto& elem : m_data.sectionsToRun) {
9961 TestSpecParser parser(ITagAliasRegistry::get());
9962 if (!m_data.testsOrTags.empty()) {
9963 m_hasTestFilters =
true;
9964 for (
auto const& testOrTags : m_data.testsOrTags) {
9965 parser.parse(testOrTags);
9968 m_testSpec = parser.testSpec();
9971 std::string
const& Config::getFilename()
const {
9972 return m_data.outputFilename ;
9975 bool Config::listTests()
const {
return m_data.listTests; }
9976 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
9977 bool Config::listTags()
const {
return m_data.listTags; }
9978 bool Config::listReporters()
const {
return m_data.listReporters; }
9980 std::string Config::getProcessName()
const {
return m_data.processName; }
9981 std::string
const& Config::getReporterName()
const {
return m_data.reporterName; }
9983 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
9984 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
9986 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
9987 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
9989 bool Config::showHelp()
const {
return m_data.showHelp; }
9992 bool Config::allowThrows()
const {
return !m_data.noThrow; }
9993 std::ostream& Config::stream()
const {
return m_stream->stream(); }
9994 std::string Config::name()
const {
return m_data.name.empty() ? m_data.processName : m_data.name; }
9995 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
9997 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings &
WarnAbout::NoTests); }
9999 double Config::minDuration()
const {
return m_data.minDuration; }
10003 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
10004 int Config::abortAfter()
const {
return m_data.abortAfter; }
10005 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
10006 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
10008 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
10009 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
10010 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
10011 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
10012 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10014 IStream const* Config::openStream() {
10022 #if defined(__clang__) 10023 # pragma clang diagnostic push 10024 # pragma clang diagnostic ignored "-Wexit-time-destructors" 10045 #if defined(CATCH_PLATFORM_WINDOWS) 10047 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) 10048 # define CATCH_DEFINED_NOMINMAX 10051 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) 10052 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN 10053 # define WIN32_LEAN_AND_MEAN 10057 #include <AfxWin.h> 10059 #include <windows.h> 10062 #ifdef CATCH_DEFINED_NOMINMAX 10065 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN 10066 # undef WIN32_LEAN_AND_MEAN 10069 #endif // defined(CATCH_PLATFORM_WINDOWS) 10077 struct IColourImpl {
10078 virtual ~IColourImpl() =
default;
10079 virtual void use( Colour::Code _colourCode ) = 0;
10082 struct NoColourImpl : IColourImpl {
10083 void use( Colour::Code )
override {}
10085 static IColourImpl* instance() {
10086 static NoColourImpl s_instance;
10087 return &s_instance;
10094 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) 10095 # ifdef CATCH_PLATFORM_WINDOWS 10096 # define CATCH_CONFIG_COLOUR_WINDOWS 10098 # define CATCH_CONFIG_COLOUR_ANSI 10102 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) 10107 class Win32ColourImpl :
public IColourImpl {
10109 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10111 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10112 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10113 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10114 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10117 void use( Colour::Code _colourCode )
override {
10118 switch( _colourCode ) {
10119 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
10120 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10121 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
10122 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
10123 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
10124 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10125 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10126 case Colour::Grey:
return setTextAttribute( 0 );
10128 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
10129 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10130 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10131 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10132 case Colour::BrightYellow:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10142 void setTextAttribute( WORD _textAttribute ) {
10143 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10145 HANDLE stdoutHandle;
10146 WORD originalForegroundAttributes;
10147 WORD originalBackgroundAttributes;
10150 IColourImpl* platformColourInstance() {
10151 static Win32ColourImpl s_instance;
10155 ? config->useColour()
10161 : NoColourImpl::instance();
10167 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) 10169 #include <unistd.h> 10178 class PosixColourImpl :
public IColourImpl {
10180 void use( Colour::Code _colourCode )
override {
10181 switch( _colourCode ) {
10183 case Colour::White:
return setColour(
"[0m" );
10184 case Colour::Red:
return setColour(
"[0;31m" );
10185 case Colour::Green:
return setColour(
"[0;32m" );
10186 case Colour::Blue:
return setColour(
"[0;34m" );
10187 case Colour::Cyan:
return setColour(
"[0;36m" );
10188 case Colour::Yellow:
return setColour(
"[0;33m" );
10189 case Colour::Grey:
return setColour(
"[1;30m" );
10191 case Colour::LightGrey:
return setColour(
"[0;37m" );
10192 case Colour::BrightRed:
return setColour(
"[1;31m" );
10193 case Colour::BrightGreen:
return setColour(
"[1;32m" );
10194 case Colour::BrightWhite:
return setColour(
"[1;37m" );
10195 case Colour::BrightYellow:
return setColour(
"[1;33m" );
10201 static IColourImpl* instance() {
10202 static PosixColourImpl s_instance;
10203 return &s_instance;
10207 void setColour(
const char* _escapeCode ) {
10209 <<
'\033' << _escapeCode;
10213 bool useColourOnPlatform() {
10215 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10216 !isDebuggerActive() &&
10218 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) 10219 isatty(STDOUT_FILENO)
10225 IColourImpl* platformColourInstance() {
10229 ? config->useColour()
10232 colourMode = useColourOnPlatform()
10236 ? PosixColourImpl::instance()
10237 : NoColourImpl::instance();
10243 #else // not Windows or ANSI 10247 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
10251 #endif // Windows/ ANSI/ None 10255 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10256 Colour::Colour( Colour&& other ) noexcept {
10257 m_moved = other.m_moved;
10258 other.m_moved =
true;
10260 Colour& Colour::operator=( Colour&& other ) noexcept {
10261 m_moved = other.m_moved;
10262 other.m_moved =
true;
10266 Colour::~Colour(){
if( !m_moved ) use( None ); }
10268 void Colour::use( Code _colourCode ) {
10269 static IColourImpl* impl = platformColourInstance();
10274 if (impl !=
nullptr) {
10275 impl->use( _colourCode );
10279 std::ostream&
operator << ( std::ostream& os, Colour
const& ) {
10285 #if defined(__clang__) 10286 # pragma clang diagnostic pop 10298 return m_resultCapture;
10300 IRunner* getRunner()
override {
10304 IConfigPtr const& getConfig()
const override {
10308 ~Context()
override;
10311 void setResultCapture(
IResultCapture* resultCapture )
override {
10312 m_resultCapture = resultCapture;
10314 void setRunner(
IRunner* runner )
override {
10317 void setConfig(
IConfigPtr const& config )
override {
10333 currentContext =
new Context();
10338 IMutableContext::currentContext =
nullptr;
10342 Context::~Context() =
default;
10358 void writeToDebugConsole( std::string
const& text );
10362 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE) 10363 #include <android/log.h> 10366 void writeToDebugConsole( std::string
const& text ) {
10367 __android_log_write( ANDROID_LOG_DEBUG,
"Catch", text.c_str() );
10371 #elif defined(CATCH_PLATFORM_WINDOWS) 10374 void writeToDebugConsole( std::string
const& text ) {
10375 ::OutputDebugStringA( text.c_str() );
10382 void writeToDebugConsole( std::string
const& text ) {
10392 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10394 # include <cassert> 10395 # include <sys/types.h> 10396 # include <unistd.h> 10397 # include <cstddef> 10398 # include <ostream> 10400 #ifdef __apple_build_version__ 10403 # include <sys/sysctl.h> 10407 #ifdef __apple_build_version__ 10413 bool isDebuggerActive(){
10415 struct kinfo_proc info;
10421 info.kp_proc.p_flag = 0;
10427 mib[1] = KERN_PROC;
10428 mib[2] = KERN_PROC_PID;
10433 size =
sizeof(info);
10434 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0 ) {
10435 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10441 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10444 bool isDebuggerActive() {
10451 #elif defined(CATCH_PLATFORM_LINUX) 10463 bool isDebuggerActive(){
10467 std::ifstream in(
"/proc/self/status");
10468 for( std::string line; std::getline(in, line); ) {
10469 static const int PREFIX_LEN = 11;
10470 if( line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
10474 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
10481 #elif defined(_MSC_VER) 10482 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10484 bool isDebuggerActive() {
10485 return IsDebuggerPresent() != 0;
10488 #elif defined(__MINGW32__) 10489 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10491 bool isDebuggerActive() {
10492 return IsDebuggerPresent() != 0;
10497 bool isDebuggerActive() {
return false; }
10508 if( lhs.size() + rhs.size() < 40 &&
10509 lhs.find(
'\n') == std::string::npos &&
10510 rhs.find(
'\n') == std::string::npos )
10511 os << lhs <<
" " << op <<
" " << rhs;
10513 os << lhs <<
"\n" << op <<
"\n" << rhs;
10519 #include <stdexcept> 10522 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) 10525 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n" 10526 <<
"The message was: " << e.what() <<
'\n';
10558 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const&
values );
10562 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10564 EnumInfo
const& registerEnum(
StringRef enumName,
StringRef allEnums, std::vector<int>
const& values)
override;
10567 std::vector<StringRef> parseEnums(
StringRef enums );
10589 size_t name_start = enumInstance.
size();
10590 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10593 return enumInstance.
substr(name_start, enumInstance.
size() - name_start);
10597 std::vector<StringRef> parseEnums(
StringRef enums ) {
10599 std::vector<StringRef> parsed;
10600 parsed.reserve( enumValues.size() );
10601 for(
auto const& enumValue : enumValues ) {
10602 parsed.push_back(
trim(extractInstanceName(enumValue)));
10607 EnumInfo::~EnumInfo() {}
10610 for(
auto const& valueToName : m_values ) {
10611 if( valueToName.first == value )
10612 return valueToName.second;
10614 return "{** unexpected enum value **}"_sr;
10617 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const&
values ) {
10618 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo );
10619 enumInfo->m_name = enumName;
10620 enumInfo->m_values.reserve( values.size() );
10622 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10623 assert( valueNames.size() == values.size() );
10625 for(
auto value : values )
10626 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10631 EnumInfo
const& EnumValuesRegistry::registerEnum(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const& values ) {
10632 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10633 return *m_enumInfos.back();
10645 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10646 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10661 ~ExceptionTranslatorRegistry();
10664 std::string tryTranslators()
const;
10667 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10673 #import "Foundation/Foundation.h" 10678 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10681 void ExceptionTranslatorRegistry::registerTranslator(
const IExceptionTranslator* translator ) {
10682 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10685 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 10691 return tryTranslators();
10693 @catch (NSException *exception) {
10705 if (std::current_exception() ==
nullptr) {
10706 return "Non C++ exception. Possibly a CLR exception.";
10708 return tryTranslators();
10712 std::rethrow_exception(std::current_exception());
10714 catch( std::exception& ex ) {
10717 catch( std::string& msg ) {
10720 catch(
const char* msg ) {
10724 return "Unknown exception";
10728 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10729 if (m_translators.empty()) {
10730 std::rethrow_exception(std::current_exception());
10732 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10736 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 10738 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10741 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10742 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10750 #include <algorithm> 10752 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS ) 10758 void FatalConditionHandler::engage_platform() {}
10759 void FatalConditionHandler::disengage_platform() {}
10760 FatalConditionHandler::FatalConditionHandler() =
default;
10761 FatalConditionHandler::~FatalConditionHandler() =
default;
10765 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS 10767 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS ) 10768 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" 10769 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS 10771 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) 10775 void reportFatal(
char const *
const message ) {
10782 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10785 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS 10787 #if defined( CATCH_CONFIG_WINDOWS_SEH ) 10791 struct SignalDefs { DWORD id;
const char* name; };
10796 static SignalDefs signalDefs[] = {
10797 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10798 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10799 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10800 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10803 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10804 for (
auto const& def : signalDefs) {
10805 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10806 reportFatal(def.name);
10811 return EXCEPTION_CONTINUE_SEARCH;
10817 static PVOID exceptionHandlerHandle =
nullptr;
10821 FatalConditionHandler::FatalConditionHandler() {
10822 ULONG guaranteeSize =
static_cast<ULONG
>(minStackSizeForErrors);
10823 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10827 <<
"Failed to reserve piece of stack." 10828 <<
" Stack overflows will not be reported successfully.";
10834 FatalConditionHandler::~FatalConditionHandler() =
default;
10836 void FatalConditionHandler::engage_platform() {
10838 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10839 if (!exceptionHandlerHandle) {
10844 void FatalConditionHandler::disengage_platform() {
10845 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10848 exceptionHandlerHandle =
nullptr;
10853 #endif // CATCH_CONFIG_WINDOWS_SEH 10855 #if defined( CATCH_CONFIG_POSIX_SIGNALS ) 10857 #include <signal.h> 10861 struct SignalDefs {
10866 static SignalDefs signalDefs[] = {
10867 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10868 { SIGILL,
"SIGILL - Illegal instruction signal" },
10869 { SIGFPE,
"SIGFPE - Floating point error signal" },
10870 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10871 { SIGTERM,
"SIGTERM - Termination request signal" },
10872 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10878 #if defined(__GNUC__) 10879 # pragma GCC diagnostic push 10880 # pragma GCC diagnostic ignored "-Wmissing-field-initializers" 10883 static char* altStackMem =
nullptr;
10884 static std::size_t altStackSize = 0;
10885 static stack_t oldSigStack{};
10886 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10888 static void restorePreviousSignalHandlers() {
10893 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
10894 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10897 sigaltstack(&oldSigStack,
nullptr);
10900 static void handleSignal(
int sig ) {
10901 char const * name =
"<unknown signal>";
10902 for (
auto const& def : signalDefs) {
10903 if (sig == def.id) {
10911 restorePreviousSignalHandlers();
10912 reportFatal( name );
10916 FatalConditionHandler::FatalConditionHandler() {
10917 assert(!altStackMem &&
"Cannot initialize POSIX signal handler when one already exists");
10918 if (altStackSize == 0) {
10919 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10921 altStackMem =
new char[altStackSize]();
10924 FatalConditionHandler::~FatalConditionHandler() {
10925 delete[] altStackMem;
10928 altStackMem =
nullptr;
10931 void FatalConditionHandler::engage_platform() {
10933 sigStack.ss_sp = altStackMem;
10934 sigStack.ss_size = altStackSize;
10935 sigStack.ss_flags = 0;
10936 sigaltstack(&sigStack, &oldSigStack);
10937 struct sigaction sa = { };
10939 sa.sa_handler = handleSignal;
10940 sa.sa_flags = SA_ONSTACK;
10941 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
10942 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
10946 #if defined(__GNUC__) 10947 # pragma GCC diagnostic pop 10950 void FatalConditionHandler::disengage_platform() {
10951 restorePreviousSignalHandlers();
10956 #endif // CATCH_CONFIG_POSIX_SIGNALS 10971 namespace Generators {
10973 GeneratorUntypedBase::~GeneratorUntypedBase() {}
11014 class ListeningReporter :
public IStreamingReporter {
11015 using Reporters = std::vector<IStreamingReporterPtr>;
11016 Reporters m_listeners;
11017 IStreamingReporterPtr m_reporter =
nullptr;
11018 ReporterPreferences m_preferences;
11021 ListeningReporter();
11023 void addListener( IStreamingReporterPtr&& listener );
11024 void addReporter( IStreamingReporterPtr&& reporter );
11028 ReporterPreferences getPreferences()
const override;
11030 void noMatchingTestCases( std::string
const& spec )
override;
11032 void reportInvalidArguments(std::string
const&arg)
override;
11034 static std::set<Verbosity> getSupportedVerbosities();
11036 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 11037 void benchmarkPreparing(std::string
const& name)
override;
11038 void benchmarkStarting( BenchmarkInfo
const& benchmarkInfo )
override;
11039 void benchmarkEnded( BenchmarkStats<>
const& benchmarkStats )
override;
11040 void benchmarkFailed(std::string
const&)
override;
11041 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 11043 void testRunStarting( TestRunInfo
const& testRunInfo )
override;
11044 void testGroupStarting( GroupInfo
const& groupInfo )
override;
11045 void testCaseStarting(
TestCaseInfo const& testInfo )
override;
11046 void sectionStarting(
SectionInfo const& sectionInfo )
override;
11047 void assertionStarting(
AssertionInfo const& assertionInfo )
override;
11050 bool assertionEnded( AssertionStats
const& assertionStats )
override;
11051 void sectionEnded( SectionStats
const& sectionStats )
override;
11052 void testCaseEnded( TestCaseStats
const& testCaseStats )
override;
11053 void testGroupEnded( TestGroupStats
const& testGroupStats )
override;
11054 void testRunEnded( TestRunStats
const& testRunStats )
override;
11056 void skipTest(
TestCaseInfo const& testInfo )
override;
11057 bool isMulti()
const override;
11066 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig )
11067 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11069 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream )
11070 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11072 std::ostream& ReporterConfig::stream()
const {
return *m_stream; }
11073 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
11075 TestRunInfo::TestRunInfo( std::string
const& _name ) : name( _name ) {}
11077 GroupInfo::GroupInfo( std::string
const& _name,
11078 std::size_t _groupIndex,
11079 std::size_t _groupsCount )
11081 groupIndex( _groupIndex ),
11082 groupsCounts( _groupsCount )
11085 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
11086 std::vector<MessageInfo>
const& _infoMessages,
11088 : assertionResult( _assertionResult ),
11089 infoMessages( _infoMessages ),
11092 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11094 if( assertionResult.hasMessage() ) {
11097 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11098 builder << assertionResult.getMessage();
11101 infoMessages.push_back( builder.m_info );
11105 AssertionStats::~AssertionStats() =
default;
11107 SectionStats::SectionStats(
SectionInfo const& _sectionInfo,
11108 Counts const& _assertions,
11109 double _durationInSeconds,
11110 bool _missingAssertions )
11111 : sectionInfo( _sectionInfo ),
11112 assertions( _assertions ),
11113 durationInSeconds( _durationInSeconds ),
11114 missingAssertions( _missingAssertions )
11117 SectionStats::~SectionStats() =
default;
11119 TestCaseStats::TestCaseStats(
TestCaseInfo const& _testInfo,
11121 std::string
const& _stdOut,
11122 std::string
const& _stdErr,
11124 : testInfo( _testInfo ),
11128 aborting( _aborting )
11131 TestCaseStats::~TestCaseStats() =
default;
11133 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11136 : groupInfo( _groupInfo ),
11138 aborting( _aborting )
11141 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11142 : groupInfo( _groupInfo ),
11146 TestGroupStats::~TestGroupStats() =
default;
11148 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11151 : runInfo( _runInfo ),
11153 aborting( _aborting )
11156 TestRunStats::~TestRunStats() =
default;
11158 void IStreamingReporter::fatalErrorEncountered(
StringRef ) {}
11159 bool IStreamingReporter::isMulti()
const {
return false; }
11161 IReporterFactory::~IReporterFactory() =
default;
11162 IReporterRegistry::~IReporterRegistry() =
default;
11181 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG 11182 #include <crtdbg.h> 11186 LeakDetector::LeakDetector() {
11187 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11188 flag |= _CRTDBG_LEAK_CHECK_DF;
11189 flag |= _CRTDBG_ALLOC_MEM_DF;
11190 _CrtSetDbgFlag(flag);
11191 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11192 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11194 _CrtSetBreakAlloc(-1);
11200 Catch::LeakDetector::LeakDetector() {}
11204 Catch::LeakDetector::~LeakDetector() {
11216 std::size_t listTests( Config
const& config );
11218 std::size_t listTestsNamesOnly( Config
const& config );
11221 void add( std::string
const& spelling );
11222 std::string all()
const;
11224 std::set<std::string> spellings;
11225 std::size_t count = 0;
11228 std::size_t listTags( Config
const& config );
11230 std::size_t listReporters();
11240 using namespace clara::TextFlow;
11245 #include <algorithm> 11250 std::size_t listTests( Config
const& config ) {
11251 TestSpec
const& testSpec = config.testSpec();
11252 if( config.hasTestFilters() )
11259 for(
auto const& testCaseInfo : matchedTestCases ) {
11260 Colour::Code colour = testCaseInfo.isHidden()
11261 ? Colour::SecondaryText
11263 Colour colourGuard( colour );
11265 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11268 std::string description = testCaseInfo.description;
11269 if( description.empty() )
11270 description =
"(NO DESCRIPTION)";
11271 Catch::cout() << Column( description ).indent(4) << std::endl;
11273 if( !testCaseInfo.tags.empty() )
11274 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) <<
"\n";
11277 if( !config.hasTestFilters() )
11280 Catch::cout() <<
pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11281 return matchedTestCases.size();
11284 std::size_t listTestsNamesOnly( Config
const& config ) {
11285 TestSpec
const& testSpec = config.testSpec();
11286 std::size_t matchedTests = 0;
11288 for(
auto const& testCaseInfo : matchedTestCases ) {
11291 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11298 return matchedTests;
11301 void TagInfo::add( std::string
const& spelling ) {
11303 spellings.insert( spelling );
11306 std::string TagInfo::all()
const {
11308 for (
auto const& spelling : spellings) {
11310 size += spelling.size() + 2;
11313 std::string out; out.reserve(size);
11314 for (
auto const& spelling : spellings) {
11322 std::size_t listTags( Config
const& config ) {
11323 TestSpec
const& testSpec = config.testSpec();
11324 if( config.hasTestFilters() )
11325 Catch::cout() <<
"Tags for matching test cases:\n";
11330 std::map<std::string, TagInfo> tagCounts;
11333 for(
auto const& testCase : matchedTestCases ) {
11334 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11335 std::string lcaseTagName =
toLower( tagName );
11336 auto countIt = tagCounts.find( lcaseTagName );
11337 if( countIt == tagCounts.end() )
11338 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11339 countIt->second.add( tagName );
11343 for(
auto const& tagCount : tagCounts ) {
11345 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11346 auto str = rss.
str();
11347 auto wrapper = Column( tagCount.second.all() )
11348 .initialIndent( 0 )
11349 .indent( str.size() )
11350 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11354 return tagCounts.size();
11357 std::size_t listReporters() {
11360 std::size_t maxNameLen = 0;
11361 for(
auto const& factoryKvp : factories )
11362 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11364 for(
auto const& factoryKvp : factories ) {
11366 << Column( factoryKvp.first +
":" )
11368 .width( 5+maxNameLen )
11369 + Column( factoryKvp.second->getDescription() )
11372 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11376 return factories.size();
11382 if( config->listTests() )
11383 listedCount = listedCount.
valueOr(0) + listTests( *config );
11384 if( config->listTestNamesOnly() )
11385 listedCount = listedCount.
valueOr(0) + listTestsNamesOnly( *config );
11386 if( config->listTags() )
11387 listedCount = listedCount.
valueOr(0) + listTags( *config );
11388 if( config->listReporters() )
11389 listedCount = listedCount.
valueOr(0) + listReporters();
11390 return listedCount;
11398 namespace Matchers {
11401 std::string MatcherUntypedBase::toString()
const {
11402 if( m_cachedToString.empty() )
11403 m_cachedToString = describe();
11404 return m_cachedToString;
11407 MatcherUntypedBase::~MatcherUntypedBase() =
default;
11412 using namespace Matchers;
11420 namespace Matchers {
11421 namespace Exception {
11423 bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11424 return ex.what() == m_message;
11427 std::string ExceptionMessageMatcher::describe()
const {
11428 return "exception message matches \"" + m_message +
"\"";
11445 bool isnan(
float f);
11446 bool isnan(
double d);
11455 template <
typename T>
11456 std::string to_string(T
const& t) {
11457 #if defined(CATCH_CONFIG_CPP11_TO_STRING) 11458 return std::to_string(t);
11468 #include <algorithm> 11474 #include <type_traits> 11481 int32_t convert(
float f) {
11482 static_assert(
sizeof(
float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11484 std::memcpy(&i, &f,
sizeof(f));
11488 int64_t convert(
double d) {
11489 static_assert(
sizeof(
double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11491 std::memcpy(&i, &d,
sizeof(d));
11495 template <
typename FP>
11496 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11499 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11503 auto lc = convert(lhs);
11504 auto rc = convert(rhs);
11506 if ((lc < 0) != (rc < 0)) {
11512 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11513 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11516 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11518 float nextafter(
float x,
float y) {
11519 return ::nextafterf(x, y);
11522 double nextafter(
double x,
double y) {
11523 return ::nextafter(x, y);
11526 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^ 11528 template <
typename FP>
11529 FP step(FP
start, FP direction, uint64_t steps) {
11530 for (uint64_t i = 0; i < steps; ++i) {
11531 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11532 start = Catch::nextafter(start, direction);
11534 start = std::nextafter(start, direction);
11542 bool marginComparison(
double lhs,
double rhs,
double margin) {
11543 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11546 template <
typename FloatingPo
int>
11547 void write(std::ostream& out, FloatingPoint num) {
11548 out << std::scientific
11549 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11555 namespace Matchers {
11556 namespace Floating {
11558 enum class FloatingPointKind : uint8_t {
11563 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11564 :m_target{ target }, m_margin{ margin } {
11565 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.' 11566 <<
" Margin has to be non-negative.");
11571 bool WithinAbsMatcher::match(
double const& matchee)
const {
11572 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11575 std::string WithinAbsMatcher::describe()
const {
11579 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11580 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11582 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11583 "Provided ULP is impossibly large for a float comparison.");
11586 #if defined(__clang__) 11587 #pragma clang diagnostic push 11589 #pragma clang diagnostic ignored "-Wunreachable-code" 11592 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11594 case FloatingPointKind::Float:
11595 return almostEqualUlps<float>(
static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11596 case FloatingPointKind::Double:
11597 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11603 #if defined(__clang__) 11604 #pragma clang diagnostic pop 11607 std::string WithinUlpsMatcher::describe()
const {
11608 std::stringstream ret;
11610 ret <<
"is within " << m_ulps <<
" ULPs of ";
11612 if (m_type == FloatingPointKind::Float) {
11613 write(ret, static_cast<float>(m_target));
11616 write(ret, m_target);
11620 if (m_type == FloatingPointKind::Double) {
11621 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11623 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11626 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11628 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11635 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11637 m_epsilon(epsilon){
11638 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11639 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
"); 11642 bool WithinRelMatcher::match(double const& matchee) const { 11643 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); 11644 return marginComparison(matchee, m_target, 11645 std::isinf(relMargin)? 0 : relMargin); 11648 std::string WithinRelMatcher::describe() const { 11649 Catch::ReusableStringStream sstr; 11650 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
"; 11654 }// namespace Floating 11656 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { 11657 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); 11660 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { 11661 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); 11664 Floating::WithinAbsMatcher WithinAbs(double target, double margin) { 11665 return Floating::WithinAbsMatcher(target, margin); 11668 Floating::WithinRelMatcher WithinRel(double target, double eps) { 11669 return Floating::WithinRelMatcher(target, eps); 11672 Floating::WithinRelMatcher WithinRel(double target) { 11673 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); 11676 Floating::WithinRelMatcher WithinRel(float target, float eps) { 11677 return Floating::WithinRelMatcher(target, eps); 11680 Floating::WithinRelMatcher WithinRel(float target) { 11681 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); 11684 } // namespace Matchers 11685 } // namespace Catch 11686 // end catch_matchers_floating.cpp 11687 // start catch_matchers_generic.cpp 11689 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { 11690 if (desc.empty()) { 11691 return "matches undescribed predicate
"; 11693 return "matches predicate: \
"" + desc +
'"';
11702 namespace Matchers {
11704 namespace StdString {
11707 : m_caseSensitivity( caseSensitivity ),
11708 m_str( adjustString( str ) )
11710 std::string CasedString::adjustString( std::string
const& str )
const {
11715 std::string CasedString::caseSensitivitySuffix()
const {
11717 ?
" (case insensitive)" 11721 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
11722 : m_comparator( comparator ),
11723 m_operation( operation ) {
11726 std::string StringMatcherBase::describe()
const {
11727 std::string description;
11728 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11729 m_comparator.caseSensitivitySuffix().size());
11730 description += m_operation;
11731 description +=
": \"";
11732 description += m_comparator.m_str;
11733 description +=
"\"";
11734 description += m_comparator.caseSensitivitySuffix();
11735 return description;
11738 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11740 bool EqualsMatcher::match( std::string
const& source )
const {
11741 return m_comparator.adjustString( source ) == m_comparator.m_str;
11744 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11746 bool ContainsMatcher::match( std::string
const& source )
const {
11747 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11750 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11752 bool StartsWithMatcher::match( std::string
const& source )
const {
11753 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11756 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11758 bool EndsWithMatcher::match( std::string
const& source )
const {
11759 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11762 RegexMatcher::RegexMatcher(std::string regex,
CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11764 bool RegexMatcher::match(std::string
const& matchee)
const {
11765 auto flags = std::regex::ECMAScript;
11766 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11767 flags |= std::regex::icase;
11769 auto reg = std::regex(m_regex, flags);
11770 return std::regex_match(matchee, reg);
11773 std::string RegexMatcher::describe()
const {
11774 return "matches " +
::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)?
" case sensitively" :
" case insensitively");
11804 bool uncaught_exceptions();
11816 : macroName( _macroName ),
11817 lineInfo( _lineInfo ),
11819 sequence( ++globalCount )
11823 return sequence == other.
sequence;
11838 :m_info(macroName, lineInfo, type) {}
11843 : m_info( builder.
m_info ), m_moved()
11850 : m_info( old.m_info ), m_moved()
11852 old.m_moved =
true;
11856 if ( !uncaught_exceptions() && !m_moved ){
11862 auto trimmed = [&] (
size_t start,
size_t end) {
11863 while (names[start] ==
',' || isspace(static_cast<unsigned char>(names[start]))) {
11866 while (names[end] ==
',' || isspace(static_cast<unsigned char>(names[end]))) {
11869 return names.
substr(start, end - start + 1);
11871 auto skipq = [&] (
size_t start,
char quote) {
11872 for (
auto i = start + 1; i < names.
size() ; ++i) {
11873 if (names[i] == quote)
11875 if (names[i] ==
'\\')
11882 std::stack<char> openings;
11883 for (
size_t pos = 0; pos < names.
size(); ++pos) {
11884 char c = names[pos];
11902 pos = skipq(pos, c);
11905 if (start != pos && openings.empty()) {
11906 m_messages.emplace_back(macroName, lineInfo, resultType);
11907 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11908 m_messages.back().message +=
" := ";
11913 assert(openings.empty() &&
"Mismatched openings");
11914 m_messages.emplace_back(macroName, lineInfo, resultType);
11915 m_messages.back().message =
static_cast<std::string
>(trimmed(start, names.
size() - 1));
11916 m_messages.back().message +=
" := ";
11919 if ( !uncaught_exceptions() ){
11920 assert( m_captured == m_messages.size() );
11921 for(
size_t i = 0; i < m_captured; ++i )
11922 m_resultCapture.popScopedMessage( m_messages[i] );
11927 assert( index < m_messages.size() );
11928 m_messages[index].message +=
value;
11929 m_resultCapture.pushScopedMessage( m_messages[index] );
11938 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11939 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11947 class RedirectedStream {
11948 std::ostream& m_originalStream;
11949 std::ostream& m_redirectionStream;
11950 std::streambuf* m_prevBuf;
11953 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11954 ~RedirectedStream();
11957 class RedirectedStdOut {
11959 RedirectedStream m_cout;
11961 RedirectedStdOut();
11962 auto str()
const -> std::string;
11968 class RedirectedStdErr {
11970 RedirectedStream m_cerr;
11971 RedirectedStream m_clog;
11973 RedirectedStdErr();
11974 auto str()
const -> std::string;
11977 class RedirectedStreams {
11979 RedirectedStreams(RedirectedStreams
const&) =
delete;
11980 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
11981 RedirectedStreams(RedirectedStreams&&) =
delete;
11982 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
11984 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11985 ~RedirectedStreams();
11987 std::string& m_redirectedCout;
11988 std::string& m_redirectedCerr;
11989 RedirectedStdOut m_redirectedStdOut;
11990 RedirectedStdErr m_redirectedStdErr;
11993 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12001 TempFile(TempFile
const&) =
delete;
12002 TempFile& operator=(TempFile
const&) =
delete;
12003 TempFile(TempFile&&) =
delete;
12004 TempFile& operator=(TempFile&&) =
delete;
12009 std::FILE* getFile();
12010 std::string getContents();
12013 std::FILE* m_file =
nullptr;
12014 #if defined(_MSC_VER) 12015 char m_buffer[L_tmpnam] = { 0 };
12019 class OutputRedirect {
12021 OutputRedirect(OutputRedirect
const&) =
delete;
12022 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
12023 OutputRedirect(OutputRedirect&&) =
delete;
12024 OutputRedirect& operator=(OutputRedirect&&) =
delete;
12026 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12030 int m_originalStdout = -1;
12031 int m_originalStderr = -1;
12032 TempFile m_stdoutFile;
12033 TempFile m_stderrFile;
12034 std::string& m_stdoutDest;
12035 std::string& m_stderrDest;
12042 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 12048 #include <stdexcept> 12050 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12051 #if defined(_MSC_VER) 12055 #define fileno _fileno 12057 #include <unistd.h> 12063 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12064 : m_originalStream( originalStream ),
12065 m_redirectionStream( redirectionStream ),
12066 m_prevBuf( m_originalStream.rdbuf() )
12068 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12071 RedirectedStream::~RedirectedStream() {
12072 m_originalStream.rdbuf( m_prevBuf );
12075 RedirectedStdOut::RedirectedStdOut() : m_cout(
Catch::cout(), m_rss.get() ) {}
12076 auto RedirectedStdOut::str()
const -> std::string {
return m_rss.str(); }
12078 RedirectedStdErr::RedirectedStdErr()
12082 auto RedirectedStdErr::str()
const -> std::string {
return m_rss.str(); }
12084 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12085 : m_redirectedCout(redirectedCout),
12086 m_redirectedCerr(redirectedCerr)
12089 RedirectedStreams::~RedirectedStreams() {
12090 m_redirectedCout += m_redirectedStdOut.str();
12091 m_redirectedCerr += m_redirectedStdErr.str();
12094 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12096 #if defined(_MSC_VER) 12097 TempFile::TempFile() {
12098 if (tmpnam_s(m_buffer)) {
12101 if (fopen_s(&m_file, m_buffer,
"w+")) {
12103 if (strerror_s(buffer, errno)) {
12106 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12110 TempFile::TempFile() {
12111 m_file = std::tmpfile();
12119 TempFile::~TempFile() {
12121 std::fclose(m_file);
12124 #if defined(_MSC_VER) 12125 std::remove(m_buffer);
12129 FILE* TempFile::getFile() {
12133 std::string TempFile::getContents() {
12134 std::stringstream sstr;
12135 char buffer[100] = {};
12136 std::rewind(m_file);
12137 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12143 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12144 m_originalStdout(dup(1)),
12145 m_originalStderr(dup(2)),
12146 m_stdoutDest(stdout_dest),
12147 m_stderrDest(stderr_dest) {
12148 dup2(fileno(m_stdoutFile.getFile()), 1);
12149 dup2(fileno(m_stderrFile.getFile()), 2);
12152 OutputRedirect::~OutputRedirect() {
12161 dup2(m_originalStdout, 1);
12162 dup2(m_originalStderr, 2);
12164 m_stdoutDest += m_stdoutFile.getContents();
12165 m_stderrDest += m_stderrFile.getContents();
12168 #endif // CATCH_CONFIG_NEW_CAPTURE 12172 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12173 #if defined(_MSC_VER) 12186 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) 12187 bool isnan(
float f) {
12188 return std::isnan(f);
12190 bool isnan(
double d) {
12191 return std::isnan(d);
12195 bool isnan(
float f) {
12196 return std::_isnan(f);
12198 bool isnan(
double d) {
12199 return std::_isnan(d);
12211 #if defined(_MSC_VER) 12212 #pragma warning(push) 12213 #pragma warning(disable:4146) // we negate uint32 during the rotate 12216 uint32_t rotate_right(uint32_t val, uint32_t count) {
12217 const uint32_t mask = 31;
12219 return (val >> count) | (val << (-count & mask));
12222 #if defined(_MSC_VER) 12223 #pragma warning(pop) 12242 for (uint64_t
s = 0;
s < skip; ++
s) {
12243 static_cast<void>((*this)());
12249 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12250 const auto output = rotate_right(xorshifted, m_state >> 59u);
12253 m_state = m_state * 6364136223846793005ULL + s_inc;
12273 #include <algorithm> 12281 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases );
12286 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12288 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
12293 virtual ~TestRegistry() =
default;
12295 virtual void registerTest(
TestCase const& testCase );
12297 std::vector<TestCase>
const& getAllTests()
const override;
12298 std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const override;
12301 std::vector<TestCase> m_functions;
12303 mutable std::vector<TestCase> m_sortedFunctions;
12304 std::size_t m_unnamedCount = 0;
12305 std::ios_base::Init m_ostreamInit;
12311 void(*m_testAsFunction)();
12313 TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept;
12315 void invoke()
const override;
12318 std::string extractClassName(
StringRef const& classOrQualifiedMethodName );
12331 class ReporterRegistry :
public IReporterRegistry {
12335 ~ReporterRegistry()
override;
12337 IStreamingReporterPtr create( std::string
const& name,
IConfigPtr const& config )
const override;
12342 FactoryMap
const& getFactories()
const override;
12343 Listeners
const& getListeners()
const override;
12346 FactoryMap m_factories;
12347 Listeners m_listeners;
12374 class TagAliasRegistry :
public ITagAliasRegistry {
12376 ~TagAliasRegistry()
override;
12377 TagAlias
const* find( std::string
const& alias )
const override;
12378 std::string expandAliases( std::string
const& unexpandedTestSpec )
const override;
12379 void add( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo );
12382 std::map<std::string, TagAlias> m_registry;
12391 #include <exception> 12395 class StartupExceptionRegistry {
12396 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 12398 void add(std::exception_ptr
const& exception) noexcept;
12399 std::vector<std::exception_ptr>
const& getExceptions()
const noexcept;
12401 std::vector<std::exception_ptr> m_exceptions;
12412 struct ISingleton {
12413 virtual ~ISingleton();
12416 void addSingleton( ISingleton* singleton );
12417 void cleanupSingletons();
12419 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12420 class Singleton : SingletonImplT,
public ISingleton {
12422 static auto getInternal() -> Singleton* {
12423 static Singleton* s_instance =
nullptr;
12424 if( !s_instance ) {
12425 s_instance =
new Singleton;
12426 addSingleton( s_instance );
12432 static auto get() -> InterfaceT
const& {
12433 return *getInternal();
12435 static auto getMutable() -> MutableInterfaceT& {
12436 return *getInternal();
12451 RegistryHub() =
default;
12452 IReporterRegistry
const& getReporterRegistry()
const override {
12453 return m_reporterRegistry;
12456 return m_testCaseRegistry;
12459 return m_exceptionTranslatorRegistry;
12461 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
12462 return m_tagAliasRegistry;
12464 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12465 return m_exceptionRegistry;
12469 void registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory )
override {
12470 m_reporterRegistry.registerReporter( name, factory );
12473 m_reporterRegistry.registerListener( factory );
12475 void registerTest(
TestCase const& testInfo )
override {
12476 m_testCaseRegistry.registerTest( testInfo );
12479 m_exceptionTranslatorRegistry.registerTranslator( translator );
12481 void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo )
override {
12482 m_tagAliasRegistry.add( alias, tag, lineInfo );
12484 void registerStartupException() noexcept
override {
12485 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 12486 m_exceptionRegistry.add(std::current_exception());
12488 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12492 return m_enumValuesRegistry;
12496 TestRegistry m_testCaseRegistry;
12497 ReporterRegistry m_reporterRegistry;
12498 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12499 TagAliasRegistry m_tagAliasRegistry;
12500 StartupExceptionRegistry m_exceptionRegistry;
12501 Detail::EnumValuesRegistry m_enumValuesRegistry;
12505 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12508 return RegistryHubSingleton::get();
12511 return RegistryHubSingleton::getMutable();
12514 cleanupSingletons();
12527 ReporterRegistry::~ReporterRegistry() =
default;
12529 IStreamingReporterPtr ReporterRegistry::create( std::string
const& name,
IConfigPtr const& config )
const {
12530 auto it = m_factories.find( name );
12531 if( it == m_factories.end() )
12533 return it->second->create( ReporterConfig( config ) );
12536 void ReporterRegistry::registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory ) {
12537 m_factories.emplace(name, factory);
12540 m_listeners.push_back( factory );
12543 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12544 return m_factories;
12546 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12547 return m_listeners;
12575 #include <algorithm> 12580 namespace Generators {
12584 GeneratorTracker( TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12585 : TrackerBase( nameAndLocation, ctx, parent )
12587 ~GeneratorTracker();
12589 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation
const& nameAndLocation ) {
12590 std::shared_ptr<GeneratorTracker> tracker;
12592 ITracker& currentTracker = ctx.currentTracker();
12604 if (currentTracker.nameAndLocation() == nameAndLocation) {
12605 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12606 assert(thisTracker);
12607 assert(thisTracker->isGeneratorTracker());
12608 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12609 }
else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12610 assert( childTracker );
12611 assert( childTracker->isGeneratorTracker() );
12612 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12614 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12615 currentTracker.addChild( tracker );
12618 if( !tracker->isComplete() ) {
12626 bool isGeneratorTracker()
const override {
return true; }
12627 auto hasGenerator()
const ->
bool override {
12628 return !!m_generator;
12630 void close()
override {
12631 TrackerBase::close();
12639 const bool should_wait_for_child = [&]() {
12641 if ( m_children.empty() ) {
12646 m_children.begin(),
12648 []( TestCaseTracking::ITrackerPtr tracker ) {
12649 return tracker->hasStarted();
12650 } ) != m_children.end() ) {
12657 auto* parent = m_parent;
12660 while ( !parent->isSectionTracker() ) {
12661 parent = &( parent->parent() );
12664 "Missing root (test case) level section" );
12666 auto const& parentSection =
12667 static_cast<SectionTracker&
>( *parent );
12668 auto const& filters = parentSection.getFilters();
12670 if ( filters.empty() ) {
12674 for (
auto const& child : m_children ) {
12675 if ( child->isSectionTracker() &&
12676 std::find( filters.begin(),
12678 static_cast<SectionTracker&
>( *child )
12679 .trimmedName() ) !=
12691 if ( should_wait_for_child ||
12692 ( m_runState == CompletedSuccessfully &&
12693 m_generator->next() ) ) {
12694 m_children.clear();
12695 m_runState = Executing;
12701 return m_generator;
12704 m_generator = std::move( generator );
12707 GeneratorTracker::~GeneratorTracker() {}
12710 RunContext::RunContext(
IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12711 : m_runInfo(_config->name()),
12714 m_reporter(std::move(reporter)),
12716 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12718 m_context.setRunner(
this);
12719 m_context.setConfig(m_config);
12720 m_context.setResultCapture(
this);
12721 m_reporter->testRunStarting(m_runInfo);
12724 RunContext::~RunContext() {
12725 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12728 void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12729 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12732 void RunContext::testGroupEnded(std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12733 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12737 Totals prevTotals = m_totals;
12739 std::string redirectedCout;
12740 std::string redirectedCerr;
12744 m_reporter->testCaseStarting(testInfo);
12746 m_activeTestCase = &testCase;
12748 ITracker& rootTracker = m_trackerContext.startRun();
12749 assert(rootTracker.isSectionTracker());
12750 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12752 m_trackerContext.startCycle();
12753 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12754 runCurrentTest(redirectedCout, redirectedCerr);
12755 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12763 m_totals.testCases += deltaTotals.
testCases;
12764 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12770 m_activeTestCase =
nullptr;
12771 m_testCaseTracker =
nullptr;
12773 return deltaTotals;
12780 IStreamingReporter& RunContext::reporter()
const {
12781 return *m_reporter;
12784 void RunContext::assertionEnded(AssertionResult
const & result) {
12787 m_lastAssertionPassed =
true;
12788 }
else if (!result.isOk()) {
12789 m_lastAssertionPassed =
false;
12790 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12791 m_totals.assertions.failedButOk++;
12793 m_totals.assertions.failed++;
12796 m_lastAssertionPassed =
true;
12801 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12804 m_messageScopes.clear();
12807 resetAssertionInfo();
12808 m_lastResult = result;
12810 void RunContext::resetAssertionInfo() {
12811 m_lastAssertionInfo.macroName =
StringRef();
12812 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12815 bool RunContext::sectionStarted(
SectionInfo const & sectionInfo,
Counts & assertions) {
12816 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.
name, sectionInfo.
lineInfo));
12817 if (!sectionTracker.isOpen())
12819 m_activeSections.push_back(§ionTracker);
12821 m_lastAssertionInfo.lineInfo = sectionInfo.
lineInfo;
12823 m_reporter->sectionStarting(sectionInfo);
12825 assertions = m_totals.assertions;
12830 using namespace Generators;
12831 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12832 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12833 m_lastAssertionInfo.lineInfo = lineInfo;
12837 bool RunContext::testForMissingAssertions(
Counts& assertions) {
12838 if (assertions.
total() != 0)
12840 if (!m_config->warnAboutMissingAssertions())
12842 if (m_trackerContext.currentTracker().hasChildren())
12844 m_totals.assertions.failed++;
12851 bool missingAssertions = testForMissingAssertions(assertions);
12853 if (!m_activeSections.empty()) {
12854 m_activeSections.back()->close();
12855 m_activeSections.pop_back();
12859 m_messages.clear();
12860 m_messageScopes.clear();
12863 void RunContext::sectionEndedEarly(
SectionEndInfo const & endInfo) {
12864 if (m_unfinishedSections.empty())
12865 m_activeSections.back()->fail();
12867 m_activeSections.back()->close();
12868 m_activeSections.pop_back();
12870 m_unfinishedSections.push_back(endInfo);
12873 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 12874 void RunContext::benchmarkPreparing(std::string
const& name) {
12875 m_reporter->benchmarkPreparing(name);
12877 void RunContext::benchmarkStarting( BenchmarkInfo
const& info ) {
12878 m_reporter->benchmarkStarting( info );
12880 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12881 m_reporter->benchmarkEnded( stats );
12883 void RunContext::benchmarkFailed(std::string
const & error) {
12884 m_reporter->benchmarkFailed(error);
12886 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 12888 void RunContext::pushScopedMessage(
MessageInfo const & message) {
12889 m_messages.push_back(message);
12892 void RunContext::popScopedMessage(
MessageInfo const & message) {
12893 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12896 void RunContext::emplaceUnscopedMessage(
MessageBuilder const& builder ) {
12897 m_messageScopes.emplace_back( builder );
12900 std::string RunContext::getCurrentTestName()
const {
12901 return m_activeTestCase
12902 ? m_activeTestCase->getTestCaseInfo().name
12906 const AssertionResult * RunContext::getLastResult()
const {
12907 return &(*m_lastResult);
12910 void RunContext::exceptionEarlyReported() {
12911 m_shouldReportUnexpected =
false;
12914 void RunContext::handleFatalErrorCondition(
StringRef message ) {
12916 m_reporter->fatalErrorEncountered(message);
12921 tempResult.message =
static_cast<std::string
>(message);
12922 AssertionResult result(m_lastAssertionInfo, tempResult);
12924 assertionEnded(result);
12926 handleUnfinishedSections();
12929 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12930 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12934 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12935 m_reporter->sectionEnded(testCaseSectionStats);
12937 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12942 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12947 m_totals.testCases.failed++;
12948 testGroupEnded(std::string(), m_totals, 1, 1);
12949 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12952 bool RunContext::lastAssertionPassed() {
12953 return m_lastAssertionPassed;
12956 void RunContext::assertionPassed() {
12957 m_lastAssertionPassed =
true;
12958 ++m_totals.assertions.passed;
12959 resetAssertionInfo();
12960 m_messageScopes.clear();
12963 bool RunContext::aborting()
const {
12964 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12967 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12968 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12969 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12970 m_reporter->sectionStarting(testCaseSection);
12971 Counts prevAssertions = m_totals.assertions;
12972 double duration = 0;
12973 m_shouldReportUnexpected =
true;
12976 seedRng(*m_config);
12980 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12981 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 12982 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12985 invokeActiveTestCase();
12987 OutputRedirect r(redirectedCout, redirectedCerr);
12989 invokeActiveTestCase();
12993 invokeActiveTestCase();
13001 if( m_shouldReportUnexpected ) {
13006 Counts assertions = m_totals.assertions - prevAssertions;
13007 bool missingAssertions = testForMissingAssertions(assertions);
13009 m_testCaseTracker->close();
13010 handleUnfinishedSections();
13011 m_messages.clear();
13012 m_messageScopes.clear();
13014 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13015 m_reporter->sectionEnded(testCaseSectionStats);
13018 void RunContext::invokeActiveTestCase() {
13019 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13020 m_activeTestCase->invoke();
13023 void RunContext::handleUnfinishedSections() {
13026 for (
auto it = m_unfinishedSections.rbegin(),
13027 itEnd = m_unfinishedSections.rend();
13031 m_unfinishedSections.clear();
13034 void RunContext::handleExpr(
13039 m_reporter->assertionStarting( info );
13042 bool result = expr.
getResult() != negated;
13045 if (!m_includeSuccessfulResults) {
13054 populateReaction( reaction );
13057 void RunContext::reportExpr(
13063 m_lastAssertionInfo = info;
13064 AssertionResultData data( resultType,
LazyExpression( negated ) );
13066 AssertionResult assertionResult{ info, data };
13067 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13069 assertionEnded( assertionResult );
13072 void RunContext::handleMessage(
13078 m_reporter->assertionStarting( info );
13080 m_lastAssertionInfo = info;
13082 AssertionResultData data( resultType,
LazyExpression(
false ) );
13083 data.message =
static_cast<std::string
>(message);
13084 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13085 assertionEnded( assertionResult );
13086 if( !assertionResult.isOk() )
13087 populateReaction( reaction );
13089 void RunContext::handleUnexpectedExceptionNotThrown(
13096 void RunContext::handleUnexpectedInflightException(
13098 std::string
const& message,
13101 m_lastAssertionInfo = info;
13104 data.message = message;
13105 AssertionResult assertionResult{ info, data };
13106 assertionEnded( assertionResult );
13107 populateReaction( reaction );
13115 void RunContext::handleIncomplete(
13118 m_lastAssertionInfo = info;
13121 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13122 AssertionResult assertionResult{ info, data };
13123 assertionEnded( assertionResult );
13125 void RunContext::handleNonExpr(
13130 m_lastAssertionInfo = info;
13132 AssertionResultData data( resultType,
LazyExpression(
false ) );
13133 AssertionResult assertionResult{ info, data };
13134 assertionEnded( assertionResult );
13136 if( !assertionResult.isOk() )
13137 populateReaction( reaction );
13147 void seedRng(
IConfig const& config) {
13149 std::srand(config.
rngSeed());
13166 m_sectionIncluded(
getResultCapture().sectionStarted( m_info, m_assertions ) )
13172 if( m_sectionIncluded ) {
13173 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13174 if( uncaught_exceptions() )
13182 Section::operator bool()
const {
13183 return m_sectionIncluded;
13194 std::string
const& _name )
13196 lineInfo( _lineInfo )
13213 ~Session()
override;
13215 void showHelp()
const;
13216 void libIdentify();
13218 int applyCommandLine(
int argc,
char const *
const * argv );
13219 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13220 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13223 void useConfigData( ConfigData
const& configData );
13225 template<
typename CharT>
13226 int run(
int argc, CharT
const *
const argv[]) {
13227 if (m_startupExceptions)
13229 int returnCode = applyCommandLine(argc, argv);
13230 if (returnCode == 0)
13231 returnCode = run();
13237 clara::Parser
const& cli()
const;
13238 void cli( clara::Parser
const& newParser );
13239 ConfigData& configData();
13244 clara::Parser m_cli;
13245 ConfigData m_configData;
13246 std::shared_ptr<Config> m_config;
13247 bool m_startupExceptions =
false;
13261 Version( Version
const& ) =
delete;
13262 Version& operator=( Version
const& ) =
delete;
13263 Version(
unsigned int _majorVersion,
13264 unsigned int _minorVersion,
13265 unsigned int _patchNumber,
13266 char const *
const _branchName,
13267 unsigned int _buildNumber );
13269 unsigned int const majorVersion;
13270 unsigned int const minorVersion;
13271 unsigned int const patchNumber;
13274 char const *
const branchName;
13275 unsigned int const buildNumber;
13277 friend std::ostream&
operator << ( std::ostream& os, Version
const& version );
13280 Version
const& libraryVersion();
13287 #include <iterator> 13292 const int MaxExitCode = 255;
13294 IStreamingReporterPtr createReporter(std::string
const& reporterName,
IConfigPtr const& config) {
13296 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13301 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13303 return createReporter(config->getReporterName(), config);
13311 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13312 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13314 for (
auto const& listener : listeners) {
13315 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13317 multi.addReporter(createReporter(config->getReporterName(), config));
13323 explicit TestGroup(std::shared_ptr<Config>
const& config)
13325 , m_context{config, makeReporter(config)}
13328 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13329 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13331 if (m_matches.empty() && invalidArgs.empty()) {
13332 for (
auto const& test : allTestCases)
13333 if (!test.isHidden())
13334 m_tests.emplace(&test);
13336 for (
auto const& match : m_matches)
13337 m_tests.insert(match.tests.begin(), match.tests.end());
13342 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13344 m_context.testGroupStarting(m_config->name(), 1, 1);
13345 for (
auto const& testCase : m_tests) {
13346 if (!m_context.aborting())
13347 totals += m_context.runTest(*testCase);
13349 m_context.reporter().skipTest(*testCase);
13352 for (
auto const& match : m_matches) {
13353 if (match.tests.empty()) {
13354 m_context.reporter().noMatchingTestCases(match.name);
13359 if (!invalidArgs.empty()) {
13360 for (
auto const& invalidArg: invalidArgs)
13361 m_context.reporter().reportInvalidArguments(invalidArg);
13364 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13369 using Tests = std::set<TestCase const*>;
13371 std::shared_ptr<Config> m_config;
13372 RunContext m_context;
13379 for (
auto& testCase : tests) {
13380 auto tags = testCase.tags;
13382 std::string filename = testCase.lineInfo.file;
13383 auto lastSlash = filename.find_last_of(
"\\/");
13384 if (lastSlash != std::string::npos) {
13385 filename.erase(0, lastSlash);
13389 auto lastDot = filename.find_last_of(
'.');
13390 if (lastDot != std::string::npos) {
13391 filename.erase(lastDot);
13394 tags.push_back(std::move(filename));
13395 setTags(testCase, tags);
13401 Session::Session() {
13402 static bool alreadyInstantiated =
false;
13403 if( alreadyInstantiated ) {
13409 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13411 if ( !exceptions.empty() ) {
13415 m_startupExceptions =
true;
13416 Colour colourGuard( Colour::Red );
13417 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13419 for (
const auto& ex_ptr : exceptions ) {
13421 std::rethrow_exception(ex_ptr);
13422 }
catch ( std::exception
const& ex ) {
13423 Catch::cerr() << Column( ex.what() ).indent(2) <<
'\n';
13429 alreadyInstantiated =
true;
13430 m_cli = makeCommandLineParser( m_configData );
13432 Session::~Session() {
13436 void Session::showHelp()
const {
13438 <<
"\nCatch v" << libraryVersion() <<
"\n" 13439 << m_cli << std::endl
13440 <<
"For more detailed usage please see the project docs\n" << std::endl;
13442 void Session::libIdentify() {
13444 << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n" 13445 << std::left << std::setw(16) <<
"category: " <<
"testframework\n" 13446 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n" 13447 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13450 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13451 if( m_startupExceptions )
13454 auto result = m_cli.parse( clara::Args( argc, argv ) );
13459 << Colour( Colour::Red )
13460 <<
"\nError(s) in input:\n" 13461 << Column( result.errorMessage() ).indent( 2 )
13463 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13464 return MaxExitCode;
13467 if( m_configData.showHelp )
13469 if( m_configData.libIdentify )
13475 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13476 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13478 char **utf8Argv =
new char *[ argc ];
13480 for (
int i = 0; i < argc; ++i ) {
13481 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr );
13483 utf8Argv[ i ] =
new char[ bufSize ];
13485 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13488 int returnCode = applyCommandLine( argc, utf8Argv );
13490 for (
int i = 0; i < argc; ++i )
13491 delete [] utf8Argv[ i ];
13493 delete [] utf8Argv;
13499 void Session::useConfigData( ConfigData
const& configData ) {
13500 m_configData = configData;
13504 int Session::run() {
13506 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13507 static_cast<void>(std::getchar());
13509 int exitCode = runInternal();
13511 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13512 static_cast<void>(std::getchar());
13517 clara::Parser
const& Session::cli()
const {
13520 void Session::cli( clara::Parser
const& newParser ) {
13523 ConfigData& Session::configData() {
13524 return m_configData;
13526 Config& Session::config() {
13528 m_config = std::make_shared<Config>( m_configData );
13532 int Session::runInternal() {
13533 if( m_startupExceptions )
13536 if (m_configData.showHelp || m_configData.libIdentify) {
13543 seedRng( *m_config );
13545 if( m_configData.filenamesAsTags )
13546 applyFilenamesAsTags( *m_config );
13550 return static_cast<int>( *listed );
13552 TestGroup tests { m_config };
13553 auto const totals = tests.execute();
13555 if( m_config->warnAboutNoTests() && totals.error == -1 )
13561 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13563 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13564 catch( std::exception& ex ) {
13566 return MaxExitCode;
13580 static auto getSingletons() -> std::vector<ISingleton*>*& {
13581 static std::vector<ISingleton*>* g_singletons =
nullptr;
13582 if( !g_singletons )
13583 g_singletons =
new std::vector<ISingleton*>();
13584 return g_singletons;
13588 ISingleton::~ISingleton() {}
13590 void addSingleton(ISingleton* singleton ) {
13591 getSingletons()->push_back( singleton );
13593 void cleanupSingletons() {
13594 auto& singletons = getSingletons();
13595 for(
auto singleton : *singletons )
13598 singletons =
nullptr;
13605 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13607 void StartupExceptionRegistry::add( std::exception_ptr
const& exception ) noexcept {
13609 m_exceptions.push_back(exception);
13616 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions()
const noexcept {
13617 return m_exceptions;
13626 #include <iostream> 13636 namespace Detail {
namespace {
13637 template<
typename WriterF, std::
size_t bufferSize=256>
13638 class StreamBufImpl :
public std::streambuf {
13639 char data[bufferSize];
13644 setp( data, data +
sizeof(data) );
13647 ~StreamBufImpl() noexcept {
13648 StreamBufImpl::sync();
13652 int overflow(
int c )
override {
13656 if( pbase() == epptr() )
13657 m_writer( std::string( 1, static_cast<char>( c ) ) );
13659 sputc( static_cast<char>( c ) );
13664 int sync()
override {
13665 if( pbase() != pptr() ) {
13666 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13667 setp( pbase(), epptr() );
13675 struct OutputDebugWriter {
13677 void operator()( std::string
const&str ) {
13678 writeToDebugConsole( str );
13684 class FileStream :
public IStream {
13685 mutable std::ofstream m_ofs;
13688 m_ofs.open( filename.
c_str() );
13689 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13691 ~FileStream()
override =
default;
13693 std::ostream& stream()
const override {
13700 class CoutStream :
public IStream {
13701 mutable std::ostream m_os;
13706 ~CoutStream()
override =
default;
13709 std::ostream& stream()
const override {
return m_os; }
13714 class DebugOutStream :
public IStream {
13715 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13716 mutable std::ostream m_os;
13719 : m_streamBuf(
new StreamBufImpl<OutputDebugWriter>() ),
13720 m_os( m_streamBuf.get() )
13723 ~DebugOutStream()
override =
default;
13726 std::ostream& stream()
const override {
return m_os; }
13734 if( filename.
empty() )
13735 return new Detail::CoutStream();
13736 else if( filename[0] ==
'%' ) {
13737 if( filename ==
"%debug" )
13738 return new Detail::DebugOutStream();
13740 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13743 return new Detail::FileStream( filename );
13747 struct StringStreams {
13748 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13749 std::vector<std::size_t> m_unused;
13750 std::ostringstream m_referenceStream;
13752 auto add() -> std::size_t {
13753 if( m_unused.empty() ) {
13754 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13755 return m_streams.size()-1;
13758 auto index = m_unused.back();
13759 m_unused.pop_back();
13764 void release( std::size_t index ) {
13765 m_streams[index]->copyfmt( m_referenceStream );
13766 m_unused.push_back(index);
13771 : m_index( Singleton<StringStreams>::getMutable().add() ),
13772 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].
get() )
13776 static_cast<std::ostringstream*
>( m_oss )->str(
"");
13778 Singleton<StringStreams>::getMutable().release( m_index );
13782 return static_cast<std::ostringstream*
>( m_oss )->str();
13787 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions 13796 #include <algorithm> 13805 char toLowerCh(
char c) {
13806 return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13810 bool startsWith( std::string
const&
s, std::string
const& prefix ) {
13811 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13813 bool startsWith( std::string
const& s,
char prefix ) {
13814 return !s.empty() && s[0] == prefix;
13816 bool endsWith( std::string
const& s, std::string
const& suffix ) {
13817 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13819 bool endsWith( std::string
const& s,
char suffix ) {
13820 return !s.empty() && s[s.size()-1] == suffix;
13822 bool contains( std::string
const& s, std::string
const& infix ) {
13823 return s.find( infix ) != std::string::npos;
13826 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13828 std::string
toLower( std::string
const& s ) {
13829 std::string lc = s;
13833 std::string
trim( std::string
const& str ) {
13834 static char const* whitespaceChars =
"\n\r\t ";
13835 std::string::size_type
start = str.find_first_not_of( whitespaceChars );
13836 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13838 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13842 const auto is_ws = [](
char c) {
13843 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r';
13845 size_t real_begin = 0;
13846 while (real_begin < ref.
size() && is_ws(ref[real_begin])) { ++real_begin; }
13847 size_t real_end = ref.
size();
13848 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13850 return ref.
substr(real_begin, real_end - real_begin);
13853 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
13854 bool replaced =
false;
13855 std::size_t i = str.find( replaceThis );
13856 while( i != std::string::npos ) {
13858 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13859 if( i < str.size()-withThis.size() )
13860 i = str.find( replaceThis, i+withThis.size() );
13862 i = std::string::npos;
13868 std::vector<StringRef> subStrings;
13869 std::size_t
start = 0;
13870 for(std::size_t pos = 0; pos < str.
size(); ++pos ) {
13871 if( str[pos] == delimiter ) {
13872 if( pos - start > 1 )
13873 subStrings.push_back( str.
substr( start, pos-start ) );
13877 if( start < str.
size() )
13878 subStrings.push_back( str.
substr( start, str.
size()-start ) );
13883 : m_count( count ),
13889 if( pluraliser.
m_count != 1 )
13898 #include <algorithm> 13905 :
StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13909 CATCH_ENFORCE(isNullTerminated(),
"Called StringRef::c_str() on a non-null-terminated instance");
13917 if (start < m_size) {
13918 return StringRef(m_start + start, (std::min)(m_size - start, size));
13924 return m_size == other.
m_size 13925 && (std::memcmp( m_start, other.
m_start, m_size ) == 0);
13929 return os.write(str.
data(), str.
size());
13933 lhs.append(rhs.
data(), rhs.
size());
13942 TagAlias::TagAlias(std::string
const & _tag,
SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13966 TagAliasRegistry::~TagAliasRegistry() {}
13968 TagAlias
const* TagAliasRegistry::find( std::string
const& alias )
const {
13969 auto it = m_registry.find( alias );
13970 if( it != m_registry.end() )
13971 return &(it->second);
13976 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
13977 std::string expandedTestSpec = unexpandedTestSpec;
13978 for(
auto const& registryKvp : m_registry ) {
13979 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13980 if( pos != std::string::npos ) {
13981 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13982 registryKvp.second.tag +
13983 expandedTestSpec.substr( pos + registryKvp.first.size() );
13986 return expandedTestSpec;
13989 void TagAliasRegistry::add( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) {
13991 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
13993 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13994 "error: tag alias, '" << alias <<
"' already registered.\n" 13995 <<
"\tFirst seen at: " << find(alias)->lineInfo <<
"\n" 13996 <<
"\tRedefined at: " << lineInfo );
13999 ITagAliasRegistry::~ITagAliasRegistry() {}
14001 ITagAliasRegistry
const& ITagAliasRegistry::get() {
14010 #include <exception> 14011 #include <algorithm> 14021 else if( tag ==
"!throws" )
14023 else if( tag ==
"!shouldfail" )
14025 else if( tag ==
"!mayfail" )
14027 else if( tag ==
"!nonportable" )
14029 else if( tag ==
"!benchmark" )
14034 bool isReservedTag( std::string
const& tag ) {
14035 return parseSpecialTag( tag ) ==
TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
14037 void enforceNotReservedTag( std::string
const& tag,
SourceLineInfo const& _lineInfo ) {
14039 "Tag name: [" << tag <<
"] is not allowed.\n" 14040 <<
"Tag names starting with non alphanumeric characters are reserved\n" 14046 std::string
const& _className,
14050 bool isHidden =
false;
14053 std::vector<std::string> tags;
14054 std::string desc, tag;
14055 bool inTag =
false;
14056 for (
char c : nameAndTags.
tags) {
14069 enforceNotReservedTag( tag, _lineInfo );
14074 if (
startsWith(tag,
'.') && tag.size() > 1) {
14077 tags.push_back( tag );
14087 tags.insert( tags.end(), {
".",
"!hide" } );
14090 TestCaseInfo info( static_cast<std::string>(nameAndTags.
name), _className, desc, tags, _lineInfo );
14091 return TestCase( _testCase, std::move(info) );
14094 void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14095 std::sort(begin(tags), end(tags));
14096 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14099 for(
auto const& tag : tags ) {
14100 std::string lcaseTag =
toLower( tag );
14102 testCaseInfo.
lcaseTags.push_back( lcaseTag );
14104 testCaseInfo.
tags = std::move(tags);
14108 std::string
const& _className,
14109 std::string
const& _description,
14110 std::vector<std::string>
const& _tags,
14113 className( _className ),
14114 description( _description ),
14115 lineInfo( _lineInfo ),
14118 setTags( *
this, _tags );
14122 return ( properties & IsHidden ) != 0;
14125 return ( properties & Throws ) != 0;
14128 return ( properties & (ShouldFail | MayFail ) ) != 0;
14131 return ( properties & (ShouldFail ) ) != 0;
14137 std::size_t full_size = 2 * tags.size();
14138 for (
const auto& tag : tags) {
14139 full_size += tag.size();
14141 ret.reserve(full_size);
14142 for (
const auto& tag : tags) {
14143 ret.push_back(
'[');
14145 ret.push_back(
']');
14155 other.
name = _newName;
14164 return test.get() == other.
test.get() &&
14165 name == other.
name &&
14170 return name < other.
name;
14182 #include <algorithm> 14188 struct TestHasher {
14189 using hash_t = uint64_t;
14191 explicit TestHasher( hash_t hashSuffix ):
14192 m_hashSuffix{ hashSuffix } {}
14194 uint32_t operator()(
TestCase const& t )
const {
14196 const hash_t prime = 1099511628211u;
14197 hash_t hash = 14695981039346656037u;
14198 for (
const char c : t.
name ) {
14202 hash ^= m_hashSuffix;
14204 const uint32_t low{
static_cast<uint32_t
>( hash ) };
14205 const uint32_t high{
static_cast<uint32_t
>( hash >> 32 ) };
14210 hash_t m_hashSuffix;
14214 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases ) {
14221 std::vector<TestCase> sorted = unsortedTestCases;
14222 std::sort( sorted.begin(), sorted.end() );
14228 TestHasher h{ config.
rngSeed() };
14230 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14231 std::vector<hashedTest> indexed_tests;
14232 indexed_tests.reserve( unsortedTestCases.size() );
14234 for (
auto const& testCase : unsortedTestCases) {
14235 indexed_tests.emplace_back(h(testCase), &testCase);
14238 std::sort(indexed_tests.begin(), indexed_tests.end(),
14239 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14240 if (lhs.first == rhs.first) {
14241 return lhs.second->name < rhs.second->name;
14243 return lhs.first < rhs.first;
14246 std::vector<TestCase> sorted;
14247 sorted.reserve( indexed_tests.size() );
14249 for (
auto const& hashed : indexed_tests) {
14250 sorted.emplace_back(*hashed.second);
14256 return unsortedTestCases;
14264 return testSpec.matches( testCase ) &&
isThrowSafe( testCase, config );
14267 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14268 std::set<TestCase> seenFunctions;
14269 for(
auto const&
function : functions ) {
14270 auto prev = seenFunctions.insert(
function );
14272 "error: TEST_CASE( \"" <<
function.name <<
"\" ) already defined.\n" 14273 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n" 14274 <<
"\tRedefined at " <<
function.getTestCaseInfo().lineInfo );
14278 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config ) {
14279 std::vector<TestCase> filtered;
14280 filtered.reserve( testCases.size() );
14281 for (
auto const& testCase : testCases) {
14282 if ((!testSpec.hasFilters() && !testCase.
isHidden()) ||
14283 (testSpec.hasFilters() &&
matchTest(testCase, testSpec, config))) {
14284 filtered.push_back(testCase);
14293 void TestRegistry::registerTest(
TestCase const& testCase ) {
14295 if( name.empty() ) {
14297 rss <<
"Anonymous test case " << ++m_unnamedCount;
14298 return registerTest( testCase.
withName( rss.
str() ) );
14300 m_functions.push_back( testCase );
14303 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14304 return m_functions;
14306 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted(
IConfig const& config )
const {
14307 if( m_sortedFunctions.empty() )
14308 enforceNoDuplicateTestCases( m_functions );
14310 if( m_currentSortOrder != config.
runOrder() || m_sortedFunctions.empty() ) {
14311 m_sortedFunctions = sortTests( config, m_functions );
14312 m_currentSortOrder = config.
runOrder();
14314 return m_sortedFunctions;
14318 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14320 void TestInvokerAsFunction::invoke()
const {
14321 m_testAsFunction();
14324 std::string extractClassName(
StringRef const& classOrQualifiedMethodName ) {
14325 std::string className(classOrQualifiedMethodName);
14328 std::size_t lastColons = className.rfind(
"::" );
14329 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14330 if( penultimateColons == std::string::npos )
14331 penultimateColons = 1;
14332 className = className.substr( penultimateColons, lastColons-penultimateColons );
14341 #include <algorithm> 14343 #include <stdexcept> 14347 #if defined(__clang__) 14348 # pragma clang diagnostic push 14349 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14353 namespace TestCaseTracking {
14355 NameAndLocation::NameAndLocation( std::string
const& _name,
SourceLineInfo const& _location )
14357 location( _location )
14360 ITracker::~ITracker() =
default;
14362 ITracker& TrackerContext::startRun() {
14363 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}",
CATCH_INTERNAL_LINEINFO ), *
this, nullptr );
14364 m_currentTracker =
nullptr;
14365 m_runState = Executing;
14366 return *m_rootTracker;
14369 void TrackerContext::endRun() {
14370 m_rootTracker.reset();
14371 m_currentTracker =
nullptr;
14372 m_runState = NotStarted;
14375 void TrackerContext::startCycle() {
14376 m_currentTracker = m_rootTracker.get();
14377 m_runState = Executing;
14379 void TrackerContext::completeCycle() {
14380 m_runState = CompletedCycle;
14383 bool TrackerContext::completedCycle()
const {
14384 return m_runState == CompletedCycle;
14386 ITracker& TrackerContext::currentTracker() {
14387 return *m_currentTracker;
14389 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14390 m_currentTracker = tracker;
14393 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14394 ITracker(nameAndLocation),
14399 bool TrackerBase::isComplete()
const {
14400 return m_runState == CompletedSuccessfully || m_runState == Failed;
14402 bool TrackerBase::isSuccessfullyCompleted()
const {
14403 return m_runState == CompletedSuccessfully;
14405 bool TrackerBase::isOpen()
const {
14406 return m_runState != NotStarted && !isComplete();
14408 bool TrackerBase::hasChildren()
const {
14409 return !m_children.empty();
14412 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14413 m_children.push_back( child );
14416 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14417 auto it = std::find_if( m_children.begin(), m_children.end(),
14418 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14420 tracker->nameAndLocation().location == nameAndLocation.location &&
14421 tracker->nameAndLocation().name == nameAndLocation.name;
14423 return( it != m_children.end() )
14427 ITracker& TrackerBase::parent() {
14428 assert( m_parent );
14432 void TrackerBase::openChild() {
14433 if( m_runState != ExecutingChildren ) {
14434 m_runState = ExecutingChildren;
14436 m_parent->openChild();
14440 bool TrackerBase::isSectionTracker()
const {
return false; }
14441 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14443 void TrackerBase::open() {
14444 m_runState = Executing;
14447 m_parent->openChild();
14450 void TrackerBase::close() {
14453 while( &m_ctx.currentTracker() != this )
14454 m_ctx.currentTracker().close();
14456 switch( m_runState ) {
14457 case NeedsAnotherRun:
14461 m_runState = CompletedSuccessfully;
14463 case ExecutingChildren:
14464 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const& t){
return t->isComplete(); }) )
14465 m_runState = CompletedSuccessfully;
14469 case CompletedSuccessfully:
14477 m_ctx.completeCycle();
14479 void TrackerBase::fail() {
14480 m_runState = Failed;
14482 m_parent->markAsNeedingAnotherRun();
14484 m_ctx.completeCycle();
14486 void TrackerBase::markAsNeedingAnotherRun() {
14487 m_runState = NeedsAnotherRun;
14490 void TrackerBase::moveToParent() {
14491 assert( m_parent );
14492 m_ctx.setCurrentTracker( m_parent );
14494 void TrackerBase::moveToThis() {
14495 m_ctx.setCurrentTracker(
this );
14498 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14499 : TrackerBase( nameAndLocation, ctx, parent ),
14500 m_trimmed_name(
trim(nameAndLocation.name))
14503 while( !parent->isSectionTracker() )
14504 parent = &parent->parent();
14506 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14507 addNextFilters( parentSection.m_filters );
14511 bool SectionTracker::isComplete()
const {
14512 bool complete =
true;
14514 if (m_filters.empty()
14515 || m_filters[0] ==
"" 14516 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14517 complete = TrackerBase::isComplete();
14522 bool SectionTracker::isSectionTracker()
const {
return true; }
14524 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14525 std::shared_ptr<SectionTracker> section;
14527 ITracker& currentTracker = ctx.currentTracker();
14528 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14529 assert( childTracker );
14530 assert( childTracker->isSectionTracker() );
14531 section = std::static_pointer_cast<SectionTracker>( childTracker );
14534 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14535 currentTracker.addChild( section );
14537 if( !ctx.completedCycle() )
14538 section->tryOpen();
14542 void SectionTracker::tryOpen() {
14543 if( !isComplete() )
14547 void SectionTracker::addInitialFilters( std::vector<std::string>
const& filters ) {
14548 if( !filters.empty() ) {
14549 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14550 m_filters.emplace_back(
"");
14551 m_filters.emplace_back(
"");
14552 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14555 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14556 if( filters.size() > 1 )
14557 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14560 std::vector<std::string>
const& SectionTracker::getFilters()
const {
14564 std::string
const& SectionTracker::trimmedName()
const {
14565 return m_trimmed_name;
14570 using TestCaseTracking::ITracker;
14571 using TestCaseTracking::TrackerContext;
14572 using TestCaseTracking::SectionTracker;
14576 #if defined(__clang__) 14577 # pragma clang diagnostic pop 14585 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14596 extractClassName( classOrMethod ),
14610 #include <algorithm> 14617 TestSpec::Pattern::Pattern( std::string
const& name )
14621 TestSpec::Pattern::~Pattern() =
default;
14623 std::string
const& TestSpec::Pattern::name()
const {
14627 TestSpec::NamePattern::NamePattern( std::string
const& name, std::string
const& filterString )
14628 : Pattern( filterString )
14632 bool TestSpec::NamePattern::matches(
TestCaseInfo const& testCase )
const {
14633 return m_wildcardPattern.matches( testCase.
name );
14636 TestSpec::TagPattern::TagPattern( std::string
const& tag, std::string
const& filterString )
14637 : Pattern( filterString )
14641 bool TestSpec::TagPattern::matches(
TestCaseInfo const& testCase )
const {
14642 return std::find(begin(testCase.
lcaseTags),
14647 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14648 : Pattern( underlyingPattern->name() )
14649 , m_underlyingPattern( underlyingPattern )
14652 bool TestSpec::ExcludedPattern::matches(
TestCaseInfo const& testCase )
const {
14653 return !m_underlyingPattern->matches( testCase );
14656 bool TestSpec::Filter::matches(
TestCaseInfo const& testCase )
const {
14657 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const& p ){
return p->matches( testCase ); } );
14660 std::string TestSpec::Filter::name()
const {
14662 for(
auto const& p : m_patterns )
14667 bool TestSpec::hasFilters()
const {
14668 return !m_filters.empty();
14671 bool TestSpec::matches(
TestCaseInfo const& testCase )
const {
14672 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const&
f ){
return f.matches( testCase ); } );
14675 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const 14677 Matches matches( m_filters.size() );
14678 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter
const&
filter ){
14679 std::vector<TestCase const*> currentMatches;
14680 for(
auto const& test : testCases )
14682 currentMatches.emplace_back( &test );
14683 return FilterMatch{
filter.name(), currentMatches };
14688 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14689 return (m_invalidArgs);
14698 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14700 TestSpecParser& TestSpecParser::parse( std::string
const& arg ) {
14702 m_exclusion =
false;
14703 m_arg = m_tagAliases->expandAliases( arg );
14704 m_escapeChars.clear();
14705 m_substring.reserve(m_arg.size());
14706 m_patternName.reserve(m_arg.size());
14707 m_realPatternPos = 0;
14709 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14711 if( !visitChar( m_arg[m_pos] ) ){
14712 m_testSpec.m_invalidArgs.push_back(arg);
14718 TestSpec TestSpecParser::testSpec() {
14722 bool TestSpecParser::visitChar(
char c ) {
14723 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14725 addCharToPattern(c);
14727 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14733 if( processNoneChar( c ) )
14737 processNameChar( c );
14741 addCharToPattern(c);
14746 if( processOtherChar( c ) )
14752 if( !isControlChar( c ) ) {
14753 m_patternName += c;
14754 m_realPatternPos++;
14760 bool TestSpecParser::processNoneChar(
char c ) {
14765 m_exclusion =
true;
14768 startNewMode( Tag );
14771 startNewMode( QuotedName );
14774 startNewMode( Name );
14778 void TestSpecParser::processNameChar(
char c ) {
14780 if( m_substring ==
"exclude:" )
14781 m_exclusion =
true;
14784 startNewMode( Tag );
14787 bool TestSpecParser::processOtherChar(
char c ) {
14788 if( !isControlChar( c ) )
14794 void TestSpecParser::startNewMode( Mode mode ) {
14797 void TestSpecParser::endMode() {
14801 return addNamePattern();
14803 return addTagPattern();
14805 revertBackToLastMode();
14809 return startNewMode( None );
14812 void TestSpecParser::escape() {
14814 m_mode = EscapedName;
14815 m_escapeChars.push_back(m_realPatternPos);
14817 bool TestSpecParser::isControlChar(
char c )
const {
14830 return c ==
'[' || c ==
']';
14834 void TestSpecParser::addFilter() {
14835 if( !m_currentFilter.m_patterns.empty() ) {
14836 m_testSpec.m_filters.push_back( m_currentFilter );
14837 m_currentFilter = TestSpec::Filter();
14841 void TestSpecParser::saveLastMode() {
14845 void TestSpecParser::revertBackToLastMode() {
14849 bool TestSpecParser::separate() {
14850 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14853 m_pos = m_arg.size();
14854 m_substring.clear();
14855 m_patternName.clear();
14856 m_realPatternPos = 0;
14864 std::string TestSpecParser::preprocessPattern() {
14865 std::string token = m_patternName;
14866 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14867 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14868 m_escapeChars.clear();
14870 m_exclusion =
true;
14871 token = token.substr(8);
14874 m_patternName.clear();
14875 m_realPatternPos = 0;
14880 void TestSpecParser::addNamePattern() {
14881 auto token = preprocessPattern();
14883 if (!token.empty()) {
14884 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14886 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14887 m_currentFilter.m_patterns.push_back(pattern);
14889 m_substring.clear();
14890 m_exclusion =
false;
14894 void TestSpecParser::addTagPattern() {
14895 auto token = preprocessPattern();
14897 if (!token.empty()) {
14900 if (token.size() > 1 && token[0] ==
'.') {
14901 token.erase(token.begin());
14902 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14904 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14906 m_currentFilter.m_patterns.push_back(pattern);
14909 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14912 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14914 m_currentFilter.m_patterns.push_back(pattern);
14916 m_substring.clear();
14917 m_exclusion =
false;
14921 TestSpec parseTestSpec( std::string
const& arg ) {
14922 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14931 static const uint64_t nanosecondsInSecond = 1000000000;
14936 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14940 auto estimateClockResolution() -> uint64_t {
14942 static const uint64_t iterations = 1000000;
14946 for( std::size_t i = 0; i < iterations; ++i ) {
14952 }
while( ticks == baseTicks );
14954 auto delta = ticks - baseTicks;
14960 if (ticks > startTime + 3 * nanosecondsInSecond) {
14961 return sum / ( i + 1u );
14967 return sum/iterations;
14971 static auto s_resolution = estimateClockResolution();
14972 return s_resolution;
14982 return getElapsedNanoseconds()/1000;
14985 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14988 return getElapsedMicroseconds()/1000000.0;
14995 #if defined(__clang__) 14996 # pragma clang diagnostic push 14997 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14998 # pragma clang diagnostic ignored "-Wglobal-constructors" 15002 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 15003 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 15013 const std::string unprintableString =
"{?}";
15016 const int hexThreshold = 255;
15018 struct Endianness {
15019 enum Arch { Big, Little };
15021 static Arch which() {
15025 auto value = *
reinterpret_cast<char*
>(&one);
15026 return value ? Little : Big;
15033 int i = 0, end =
static_cast<int>( size ), inc = 1;
15034 if( Endianness::which() == Endianness::Little ) {
15039 unsigned char const *bytes =
static_cast<unsigned char const *
>(object);
15041 rss <<
"0x" << std::setfill(
'0') << std::hex;
15042 for( ; i != end; i += inc )
15043 rss << std::setw(2) <<
static_cast<unsigned>(bytes[i]);
15048 template<
typename T>
15049 std::string fpToString( T
value,
int precision ) {
15050 if (Catch::isnan(value)) {
15055 rss << std::setprecision( precision )
15058 std::string
d = rss.
str();
15059 std::size_t i = d.find_last_not_of(
'0' );
15060 if( i != std::string::npos && i != d.size()-1 ) {
15063 d = d.substr( 0, i+1 );
15076 return '"' + str +
'"';
15079 std::string
s(
"\"");
15080 for (
char c : str) {
15097 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 15107 return{
"{null string}" };
15114 return{
"{null string}" };
15118 #ifdef CATCH_CONFIG_WCHAR 15121 s.reserve(wstr.size());
15122 for (
auto c : wstr) {
15123 s += (c <= 0xff) ? static_cast<char>(c) :
'?';
15128 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 15138 return{
"{null string}" };
15145 return{
"{null string}" };
15150 #if defined(CATCH_CONFIG_CPP17_BYTE) 15155 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 15166 if (value > Detail::hexThreshold) {
15167 rss <<
" (0x" << std::hex << value <<
')';
15181 if (value > Detail::hexThreshold) {
15182 rss <<
" (0x" << std::hex << value <<
')';
15188 return b ?
"true" :
"false";
15192 if (value ==
'\r') {
15194 }
else if (value ==
'\f') {
15196 }
else if (value ==
'\n') {
15198 }
else if (value ==
'\t') {
15200 }
else if (
'\0' <= value && value <
' ') {
15203 char chstr[] =
"' '";
15222 return fpToString(value, precision) +
'f';
15228 return fpToString(value, precision);
15231 std::string ratio_string<std::atto>::symbol() {
return "a"; }
15232 std::string ratio_string<std::femto>::symbol() {
return "f"; }
15233 std::string ratio_string<std::pico>::symbol() {
return "p"; }
15234 std::string ratio_string<std::nano>::symbol() {
return "n"; }
15235 std::string ratio_string<std::micro>::symbol() {
return "u"; }
15236 std::string ratio_string<std::milli>::symbol() {
return "m"; }
15240 #if defined(__clang__) 15241 # pragma clang diagnostic pop 15265 return passed + failed + failedButOk;
15268 return failed == 0 && failedButOk == 0;
15271 return failed == 0;
15288 Totals diff = *
this - prevTotals;
15311 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP 15312 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP 15314 #if defined(_MSC_VER) 15315 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer 15316 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 15320 #include <exception> 15322 #if defined(__cpp_lib_uncaught_exceptions) \ 15323 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15325 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 15326 #endif // __cpp_lib_uncaught_exceptions 15328 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \ 15329 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \ 15330 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15332 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 15335 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP 15337 #include <exception> 15340 bool uncaught_exceptions() {
15341 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 15343 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15344 return std::uncaught_exceptions() > 0;
15346 return std::uncaught_exception();
15358 (
unsigned int _majorVersion,
15359 unsigned int _minorVersion,
15360 unsigned int _patchNumber,
15361 char const *
const _branchName,
15362 unsigned int _buildNumber )
15363 : majorVersion( _majorVersion ),
15364 minorVersion( _minorVersion ),
15365 patchNumber( _patchNumber ),
15366 branchName( _branchName ),
15367 buildNumber( _buildNumber )
15370 std::ostream&
operator << ( std::ostream& os, Version
const& version ) {
15371 os << version.majorVersion <<
'.' 15372 << version.minorVersion <<
'.' 15373 << version.patchNumber;
15375 if (version.branchName[0]) {
15376 os <<
'-' << version.branchName
15377 <<
'.' << version.buildNumber;
15382 Version
const& libraryVersion() {
15383 static Version version( 2, 13, 7,
"", 0 );
15393 WildcardPattern::WildcardPattern( std::string
const& pattern,
15395 : m_caseSensitivity( caseSensitivity ),
15396 m_pattern( normaliseString( pattern ) )
15399 m_pattern = m_pattern.substr( 1 );
15400 m_wildcard = WildcardAtStart;
15402 if(
endsWith( m_pattern,
'*' ) ) {
15403 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15404 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15408 bool WildcardPattern::matches( std::string
const& str )
const {
15409 switch( m_wildcard ) {
15411 return m_pattern == normaliseString( str );
15412 case WildcardAtStart:
15413 return endsWith( normaliseString( str ), m_pattern );
15414 case WildcardAtEnd:
15415 return startsWith( normaliseString( str ), m_pattern );
15416 case WildcardAtBothEnds:
15417 return contains( normaliseString( str ), m_pattern );
15423 std::string WildcardPattern::normaliseString( std::string
const& str )
const {
15431 #include <type_traits> 15437 size_t trailingBytes(
unsigned char c) {
15438 if ((c & 0xE0) == 0xC0) {
15441 if ((c & 0xF0) == 0xE0) {
15444 if ((c & 0xF8) == 0xF0) {
15450 uint32_t headerValue(
unsigned char c) {
15451 if ((c & 0xE0) == 0xC0) {
15454 if ((c & 0xF0) == 0xE0) {
15457 if ((c & 0xF8) == 0xF0) {
15463 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15464 std::ios_base::fmtflags
f(os.flags());
15466 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15467 <<
static_cast<int>(c);
15471 bool shouldNewline(XmlFormatting fmt) {
15472 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15475 bool shouldIndent(XmlFormatting fmt) {
15476 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15481 XmlFormatting
operator | (XmlFormatting lhs, XmlFormatting rhs) {
15482 return static_cast<XmlFormatting
>(
15483 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15484 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15488 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15489 return static_cast<XmlFormatting
>(
15490 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15491 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15495 XmlEncode::XmlEncode( std::string
const& str, ForWhat forWhat )
15497 m_forWhat( forWhat )
15500 void XmlEncode::encodeTo( std::ostream& os )
const {
15504 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15505 unsigned char c = m_str[idx];
15507 case '<': os <<
"<";
break;
15508 case '&': os <<
"&";
break;
15512 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15519 if (m_forWhat == ForAttributes)
15530 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15531 hexEscapeChar(os, c);
15549 hexEscapeChar(os, c);
15553 auto encBytes = trailingBytes(c);
15555 if (idx + encBytes - 1 >= m_str.size()) {
15556 hexEscapeChar(os, c);
15563 uint32_t
value = headerValue(c);
15564 for (std::size_t n = 1; n < encBytes; ++n) {
15565 unsigned char nc = m_str[idx + n];
15566 valid &= ((nc & 0xC0) == 0x80);
15567 value = (value << 6) | (nc & 0x3F);
15575 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15576 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15578 (value >= 0x110000)
15580 hexEscapeChar(os, c);
15585 for (std::size_t n = 0; n < encBytes; ++n) {
15586 os << m_str[idx + n];
15588 idx += encBytes - 1;
15594 std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15595 xmlEncode.encodeTo( os );
15599 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15600 : m_writer( writer ),
15604 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15605 : m_writer( other.m_writer ),
15608 other.m_writer =
nullptr;
15609 other.m_fmt = XmlFormatting::None;
15611 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15613 m_writer->endElement();
15615 m_writer = other.m_writer;
15616 other.m_writer =
nullptr;
15617 m_fmt = other.m_fmt;
15618 other.m_fmt = XmlFormatting::None;
15622 XmlWriter::ScopedElement::~ScopedElement() {
15624 m_writer->endElement(m_fmt);
15628 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string
const& text, XmlFormatting fmt ) {
15629 m_writer->writeText( text, fmt );
15633 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15635 writeDeclaration();
15638 XmlWriter::~XmlWriter() {
15639 while (!m_tags.empty()) {
15642 newlineIfNecessary();
15645 XmlWriter& XmlWriter::startElement( std::string
const& name, XmlFormatting fmt ) {
15647 newlineIfNecessary();
15648 if (shouldIndent(fmt)) {
15652 m_os <<
'<' << name;
15653 m_tags.push_back( name );
15654 m_tagIsOpen =
true;
15655 applyFormatting(fmt);
15659 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string
const& name, XmlFormatting fmt ) {
15660 ScopedElement scoped(
this, fmt );
15661 startElement( name, fmt );
15665 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15666 m_indent = m_indent.substr(0, m_indent.size() - 2);
15668 if( m_tagIsOpen ) {
15670 m_tagIsOpen =
false;
15672 newlineIfNecessary();
15673 if (shouldIndent(fmt)) {
15676 m_os <<
"</" << m_tags.back() <<
">";
15678 m_os << std::flush;
15679 applyFormatting(fmt);
15684 XmlWriter& XmlWriter::writeAttribute( std::string
const& name, std::string
const& attribute ) {
15685 if( !name.empty() && !attribute.empty() )
15686 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15690 XmlWriter& XmlWriter::writeAttribute( std::string
const& name,
bool attribute ) {
15691 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15695 XmlWriter& XmlWriter::writeText( std::string
const& text, XmlFormatting fmt) {
15696 if( !text.empty() ){
15697 bool tagWasOpen = m_tagIsOpen;
15699 if (tagWasOpen && shouldIndent(fmt)) {
15702 m_os << XmlEncode( text );
15703 applyFormatting(fmt);
15708 XmlWriter& XmlWriter::writeComment( std::string
const& text, XmlFormatting fmt) {
15710 if (shouldIndent(fmt)) {
15713 m_os <<
"<!--" << text <<
"-->";
15714 applyFormatting(fmt);
15718 void XmlWriter::writeStylesheetRef( std::string
const& url ) {
15719 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15722 XmlWriter& XmlWriter::writeBlankLine() {
15728 void XmlWriter::ensureTagClosed() {
15729 if( m_tagIsOpen ) {
15730 m_os << '>
' << std::flush; 15731 newlineIfNecessary(); 15732 m_tagIsOpen = false; 15736 void XmlWriter::applyFormatting(XmlFormatting fmt) { 15737 m_needsNewline = shouldNewline(fmt); 15740 void XmlWriter::writeDeclaration() { 15741 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; 15744 void XmlWriter::newlineIfNecessary() { 15745 if( m_needsNewline ) { 15747 m_needsNewline = false; 15751 // end catch_xmlwriter.cpp 15752 // start catch_reporter_bases.cpp 15761 void prepareExpandedExpression(AssertionResult& result) { 15762 result.getExpandedExpression(); 15765 // Because formatting using c++ streams is stateful, drop down to C is required 15766 // Alternatively we could use stringstream, but its performance is... not good. 15767 std::string getFormattedDuration( double duration ) { 15768 // Max exponent + 1 is required to represent the whole part 15769 // + 1 for decimal point 15770 // + 3 for the 3 decimal places 15771 // + 1 for null terminator 15772 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; 15773 char buffer[maxDoubleSize]; 15775 // Save previous errno, to prevent sprintf from overwriting it 15778 sprintf_s(buffer, "%.3f", duration); 15780 std::sprintf(buffer, "%.3f", duration); 15782 return std::string(buffer); 15785 bool shouldShowDuration( IConfig const& config, double duration ) { 15786 if ( config.showDurations() == ShowDurations::Always ) { 15789 if ( config.showDurations() == ShowDurations::Never ) { 15792 const double min = config.minDuration(); 15793 return min >= 0 && duration >= min; 15796 std::string serializeFilters( std::vector<std::string> const& container ) { 15797 ReusableStringStream oss; 15799 for (auto&& filter : container) 15811 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) 15812 :StreamingReporterBase(_config) {} 15814 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() { 15815 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; 15818 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} 15820 bool TestEventListenerBase::assertionEnded(AssertionStats const &) { 15824 } // end namespace Catch 15825 // end catch_reporter_bases.cpp 15826 // start catch_reporter_compact.cpp 15830 #ifdef CATCH_PLATFORM_MAC 15831 const char* failedString() { return "FAILED"; } 15832 const char* passedString() { return "PASSED"; } 15834 const char* failedString() { return "failed"; } 15835 const char* passedString() { return "passed"; } 15838 // Colour::LightGrey 15839 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } 15841 std::string bothOrAll( std::size_t count ) { 15842 return count == 1 ? std::string() : 15843 count == 2 ? "both " : "all " ; 15846 } // anon namespace 15850 // Colour, message variants: 15851 // - white: No tests ran. 15852 // - red: Failed [both/all] N test cases, failed [both/all] M assertions. 15853 // - white: Passed [both/all] N test cases (no assertions). 15854 // - red: Failed N tests cases, failed M assertions. 15855 // - green: Passed [both/all] N tests cases with M assertions. 15856 void printTotals(std::ostream& out, const Totals& totals) { 15857 if (totals.testCases.total() == 0) { 15858 out << "No tests ran."; 15859 } else if (totals.testCases.failed == totals.testCases.total()) { 15860 Colour colour(Colour::ResultError); 15861 const std::string qualify_assertions_failed = 15862 totals.assertions.failed == totals.assertions.total() ? 15863 bothOrAll(totals.assertions.failed) : std::string(); 15865 "Failed " << bothOrAll(totals.testCases.failed) 15866 << pluralise(totals.testCases.failed, "test case") << ", " 15867 "failed " << qualify_assertions_failed << 15868 pluralise(totals.assertions.failed, "assertion") << '.
'; 15869 } else if (totals.assertions.total() == 0) { 15871 "Passed " << bothOrAll(totals.testCases.total()) 15872 << pluralise(totals.testCases.total(), "test case") 15873 << " (no assertions)."; 15874 } else if (totals.assertions.failed) { 15875 Colour colour(Colour::ResultError); 15877 "Failed " << pluralise(totals.testCases.failed, "test case") << ", " 15878 "failed " << pluralise(totals.assertions.failed, "assertion") << '.
'; 15880 Colour colour(Colour::ResultSuccess); 15882 "Passed " << bothOrAll(totals.testCases.passed) 15883 << pluralise(totals.testCases.passed, "test case") << 15884 " with " << pluralise(totals.assertions.passed, "assertion") << '.
'; 15888 // Implementation of CompactReporter formatting 15889 class AssertionPrinter { 15891 AssertionPrinter& operator= (AssertionPrinter const&) = delete; 15892 AssertionPrinter(AssertionPrinter const&) = delete; 15893 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) 15895 , result(_stats.assertionResult) 15896 , messages(_stats.infoMessages) 15897 , itMessage(_stats.infoMessages.begin()) 15898 , printInfoMessages(_printInfoMessages) {} 15903 itMessage = messages.begin(); 15905 switch (result.getResultType()) { 15906 case ResultWas::Ok: 15907 printResultType(Colour::ResultSuccess, passedString()); 15908 printOriginalExpression(); 15909 printReconstructedExpression(); 15910 if (!result.hasExpression()) 15911 printRemainingMessages(Colour::None); 15913 printRemainingMessages(); 15915 case ResultWas::ExpressionFailed: 15917 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); 15919 printResultType(Colour::Error, failedString()); 15920 printOriginalExpression(); 15921 printReconstructedExpression(); 15922 printRemainingMessages(); 15924 case ResultWas::ThrewException: 15925 printResultType(Colour::Error, failedString()); 15926 printIssue("unexpected exception with message:"); 15928 printExpressionWas(); 15929 printRemainingMessages(); 15931 case ResultWas::FatalErrorCondition: 15932 printResultType(Colour::Error, failedString()); 15933 printIssue("fatal error condition with message:"); 15935 printExpressionWas(); 15936 printRemainingMessages(); 15938 case ResultWas::DidntThrowException: 15939 printResultType(Colour::Error, failedString()); 15940 printIssue("expected exception, got none"); 15941 printExpressionWas(); 15942 printRemainingMessages(); 15944 case ResultWas::Info: 15945 printResultType(Colour::None, "info"); 15947 printRemainingMessages(); 15949 case ResultWas::Warning: 15950 printResultType(Colour::None, "warning"); 15952 printRemainingMessages(); 15954 case ResultWas::ExplicitFailure: 15955 printResultType(Colour::Error, failedString()); 15956 printIssue("explicitly"); 15957 printRemainingMessages(Colour::None); 15959 // These cases are here to prevent compiler warnings 15960 case ResultWas::Unknown: 15961 case ResultWas::FailureBit: 15962 case ResultWas::Exception: 15963 printResultType(Colour::Error, "** internal error **"); 15969 void printSourceInfo() const { 15970 Colour colourGuard(Colour::FileName); 15971 stream << result.getSourceInfo() << ':
'; 15974 void printResultType(Colour::Code colour, std::string const& passOrFail) const { 15975 if (!passOrFail.empty()) { 15977 Colour colourGuard(colour); 15978 stream << ' ' << passOrFail; 15984 void printIssue(std::string const& issue) const { 15985 stream << ' ' << issue; 15988 void printExpressionWas() { 15989 if (result.hasExpression()) { 15992 Colour colour(dimColour()); 15993 stream << " expression was:"; 15995 printOriginalExpression(); 15999 void printOriginalExpression() const { 16000 if (result.hasExpression()) { 16001 stream << ' ' << result.getExpression(); 16005 void printReconstructedExpression() const { 16006 if (result.hasExpandedExpression()) { 16008 Colour colour(dimColour()); 16009 stream << " for: "; 16011 stream << result.getExpandedExpression(); 16015 void printMessage() { 16016 if (itMessage != messages.end()) { 16017 stream << " '" << itMessage->message << '\''; 16022 void printRemainingMessages(Colour::Code colour = dimColour()) { 16023 if (itMessage == messages.end()) 16026 const auto itEnd = messages.cend(); 16027 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd)); 16030 Colour colourGuard(colour); 16031 stream << " with
" << pluralise(N, "message
") << ':'; 16034 while (itMessage != itEnd) { 16035 // If this assertion is a warning ignore any INFO messages 16036 if (printInfoMessages || itMessage->type != ResultWas::Info) { 16038 if (itMessage != itEnd) { 16039 Colour colourGuard(dimColour()); 16049 std::ostream& stream; 16050 AssertionResult const& result; 16051 std::vector<MessageInfo> messages; 16052 std::vector<MessageInfo>::const_iterator itMessage; 16053 bool printInfoMessages; 16056 } // anon namespace 16058 std::string CompactReporter::getDescription() { 16059 return "Reports test results on a single line, suitable
for IDEs
"; 16062 void CompactReporter::noMatchingTestCases( std::string const& spec ) { 16063 stream << "No test cases matched
'" << spec << '\
'' << std::endl;
16066 void CompactReporter::assertionStarting(
AssertionInfo const& ) {}
16068 bool CompactReporter::assertionEnded( AssertionStats
const& _assertionStats ) {
16069 AssertionResult
const& result = _assertionStats.assertionResult;
16071 bool printInfoMessages =
true;
16074 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16077 printInfoMessages =
false;
16080 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16083 stream << std::endl;
16087 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
16088 double dur = _sectionStats.durationInSeconds;
16089 if ( shouldShowDuration( *m_config, dur ) ) {
16090 stream << getFormattedDuration( dur ) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16094 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
16095 printTotals( stream, _testRunStats.totals );
16096 stream <<
'\n' << std::endl;
16097 StreamingReporterBase::testRunEnded( _testRunStats );
16100 CompactReporter::~CompactReporter() {}
16102 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
16111 #if defined(_MSC_VER) 16112 #pragma warning(push) 16113 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 16117 #if defined(__clang__) 16118 # pragma clang diagnostic push 16120 # pragma clang diagnostic ignored "-Wunused-function" 16128 class ConsoleAssertionPrinter {
16130 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter
const&) =
delete;
16131 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
16132 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
16135 result(_stats.assertionResult),
16136 colour(Colour::None),
16137 message(result.getMessage()),
16138 messages(_stats.infoMessages),
16139 printInfoMessages(_printInfoMessages) {
16140 switch (result.getResultType()) {
16142 colour = Colour::Success;
16143 passOrFail =
"PASSED";
16145 if (_stats.infoMessages.size() == 1)
16146 messageLabel =
"with message";
16147 if (_stats.infoMessages.size() > 1)
16148 messageLabel =
"with messages";
16151 if (result.isOk()) {
16152 colour = Colour::Success;
16153 passOrFail =
"FAILED - but was ok";
16155 colour = Colour::Error;
16156 passOrFail =
"FAILED";
16158 if (_stats.infoMessages.size() == 1)
16159 messageLabel =
"with message";
16160 if (_stats.infoMessages.size() > 1)
16161 messageLabel =
"with messages";
16164 colour = Colour::Error;
16165 passOrFail =
"FAILED";
16166 messageLabel =
"due to unexpected exception with ";
16167 if (_stats.infoMessages.size() == 1)
16168 messageLabel +=
"message";
16169 if (_stats.infoMessages.size() > 1)
16170 messageLabel +=
"messages";
16173 colour = Colour::Error;
16174 passOrFail =
"FAILED";
16175 messageLabel =
"due to a fatal error condition";
16178 colour = Colour::Error;
16179 passOrFail =
"FAILED";
16180 messageLabel =
"because no exception was thrown where one was expected";
16183 messageLabel =
"info";
16186 messageLabel =
"warning";
16189 passOrFail =
"FAILED";
16190 colour = Colour::Error;
16191 if (_stats.infoMessages.size() == 1)
16192 messageLabel =
"explicitly with message";
16193 if (_stats.infoMessages.size() > 1)
16194 messageLabel =
"explicitly with messages";
16200 passOrFail =
"** internal error **";
16201 colour = Colour::Error;
16206 void print()
const {
16208 if (stats.totals.assertions.total() > 0) {
16210 printOriginalExpression();
16211 printReconstructedExpression();
16219 void printResultType()
const {
16220 if (!passOrFail.empty()) {
16221 Colour colourGuard(colour);
16222 stream << passOrFail <<
":\n";
16225 void printOriginalExpression()
const {
16226 if (result.hasExpression()) {
16227 Colour colourGuard(Colour::OriginalExpression);
16229 stream << result.getExpressionInMacro();
16233 void printReconstructedExpression()
const {
16234 if (result.hasExpandedExpression()) {
16235 stream <<
"with expansion:\n";
16236 Colour colourGuard(Colour::ReconstructedExpression);
16237 stream << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16240 void printMessage()
const {
16241 if (!messageLabel.empty())
16242 stream << messageLabel <<
':' <<
'\n';
16243 for (
auto const& msg : messages) {
16246 stream << Column(msg.message).indent(2) <<
'\n';
16249 void printSourceInfo()
const {
16250 Colour colourGuard(Colour::FileName);
16251 stream << result.getSourceInfo() <<
": ";
16254 std::ostream& stream;
16255 AssertionStats
const& stats;
16256 AssertionResult
const& result;
16257 Colour::Code colour;
16258 std::string passOrFail;
16259 std::string messageLabel;
16260 std::string message;
16261 std::vector<MessageInfo> messages;
16262 bool printInfoMessages;
16265 std::size_t makeRatio(std::size_t number, std::size_t total) {
16266 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16267 return (ratio == 0 && number > 0) ? 1 : ratio;
16270 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16271 if (i > j && i > k)
16279 struct ColumnInfo {
16280 enum Justification { Left, Right };
16283 Justification justification;
16285 struct ColumnBreak {};
16286 struct RowBreak {};
16297 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16298 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16299 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16300 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16302 double m_inNanoseconds;
16306 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16307 : m_inNanoseconds(inNanoseconds),
16309 if (m_units == Unit::Auto) {
16310 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16311 m_units = Unit::Nanoseconds;
16312 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16313 m_units = Unit::Microseconds;
16314 else if (m_inNanoseconds < s_nanosecondsInASecond)
16315 m_units = Unit::Milliseconds;
16316 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16317 m_units = Unit::Seconds;
16319 m_units = Unit::Minutes;
16324 auto value()
const ->
double {
16326 case Unit::Microseconds:
16327 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16328 case Unit::Milliseconds:
16329 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16330 case Unit::Seconds:
16331 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16332 case Unit::Minutes:
16333 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16335 return m_inNanoseconds;
16338 auto unitsAsString()
const -> std::string {
16340 case Unit::Nanoseconds:
16342 case Unit::Microseconds:
16344 case Unit::Milliseconds:
16346 case Unit::Seconds:
16348 case Unit::Minutes:
16351 return "** internal error **";
16355 friend auto operator << (std::ostream& os, Duration
const& duration) -> std::ostream& {
16356 return os << duration.value() <<
' ' << duration.unitsAsString();
16361 class TablePrinter {
16362 std::ostream& m_os;
16363 std::vector<ColumnInfo> m_columnInfos;
16364 std::ostringstream m_oss;
16365 int m_currentColumn = -1;
16366 bool m_isOpen =
false;
16369 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16371 m_columnInfos( std::move( columnInfos ) ) {}
16373 auto columnInfos()
const -> std::vector<ColumnInfo>
const& {
16374 return m_columnInfos;
16380 *
this << RowBreak();
16382 Columns headerCols;
16384 for (
auto const& info : m_columnInfos) {
16385 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16386 headerCols += spacer;
16388 m_os << headerCols <<
'\n';
16390 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16395 *
this << RowBreak();
16401 template<
typename T>
16407 friend TablePrinter&
operator << (TablePrinter& tp, ColumnBreak) {
16408 auto colStr = tp.m_oss.str();
16409 const auto strSize = colStr.size();
16412 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16413 tp.m_currentColumn = -1;
16416 tp.m_currentColumn++;
16418 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16419 auto padding = (strSize + 1 <
static_cast<std::size_t
>(colInfo.width))
16420 ? std::string(colInfo.width - (strSize + 1),
' ')
16422 if (colInfo.justification == ColumnInfo::Left)
16423 tp.m_os << colStr << padding <<
' ';
16425 tp.m_os << padding << colStr <<
' ';
16429 friend TablePrinter&
operator << (TablePrinter& tp, RowBreak) {
16430 if (tp.m_currentColumn > 0) {
16432 tp.m_currentColumn = -1;
16438 ConsoleReporter::ConsoleReporter(ReporterConfig
const& config)
16439 : StreamingReporterBase(config),
16440 m_tablePrinter(
new TablePrinter(config.stream(),
16441 [&config]() -> std::vector<ColumnInfo> {
16442 if (config.fullConfig()->benchmarkNoAnalysis())
16445 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16446 {
" samples", 14, ColumnInfo::Right },
16447 {
" iterations", 14, ColumnInfo::Right },
16448 {
" mean", 14, ColumnInfo::Right }
16454 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16455 {
"samples mean std dev", 14, ColumnInfo::Right },
16456 {
"iterations low mean low std dev", 14, ColumnInfo::Right },
16457 {
"estimated high mean high std dev", 14, ColumnInfo::Right }
16461 ConsoleReporter::~ConsoleReporter() =
default;
16463 std::string ConsoleReporter::getDescription() {
16464 return "Reports test results as plain lines of text";
16467 void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16468 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16471 void ConsoleReporter::reportInvalidArguments(std::string
const&arg){
16472 stream <<
"Invalid Filter: " << arg << std::endl;
16475 void ConsoleReporter::assertionStarting(
AssertionInfo const&) {}
16477 bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16478 AssertionResult
const& result = _assertionStats.assertionResult;
16480 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16488 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16490 stream << std::endl;
16494 void ConsoleReporter::sectionStarting(
SectionInfo const& _sectionInfo) {
16495 m_tablePrinter->close();
16496 m_headerPrinted =
false;
16497 StreamingReporterBase::sectionStarting(_sectionInfo);
16499 void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16500 m_tablePrinter->close();
16501 if (_sectionStats.missingAssertions) {
16503 Colour colour(Colour::ResultError);
16504 if (m_sectionStack.size() > 1)
16505 stream <<
"\nNo assertions in section";
16507 stream <<
"\nNo assertions in test case";
16508 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16510 double dur = _sectionStats.durationInSeconds;
16511 if (shouldShowDuration(*m_config, dur)) {
16512 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16514 if (m_headerPrinted) {
16515 m_headerPrinted =
false;
16517 StreamingReporterBase::sectionEnded(_sectionStats);
16520 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 16521 void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16522 lazyPrintWithoutClosingBenchmarkTable();
16524 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16526 bool firstLine =
true;
16527 for (
auto line : nameCol) {
16529 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16533 (*m_tablePrinter) << line << ColumnBreak();
16537 void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16538 (*m_tablePrinter) << info.samples << ColumnBreak()
16539 << info.iterations << ColumnBreak();
16540 if (!m_config->benchmarkNoAnalysis())
16541 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16543 void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16544 if (m_config->benchmarkNoAnalysis())
16546 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16550 (*m_tablePrinter) << ColumnBreak()
16551 << Duration(stats.mean.point.count()) << ColumnBreak()
16552 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16553 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16554 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16555 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16556 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16560 void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16561 Colour colour(Colour::Red);
16563 <<
"Benchmark failed (" << error <<
')' 16564 << ColumnBreak() << RowBreak();
16566 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 16568 void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16569 m_tablePrinter->close();
16570 StreamingReporterBase::testCaseEnded(_testCaseStats);
16571 m_headerPrinted =
false;
16573 void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16574 if (currentGroupInfo.used) {
16575 printSummaryDivider();
16576 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16577 printTotals(_testGroupStats.totals);
16578 stream <<
'\n' << std::endl;
16580 StreamingReporterBase::testGroupEnded(_testGroupStats);
16582 void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16583 printTotalsDivider(_testRunStats.totals);
16584 printTotals(_testRunStats.totals);
16585 stream << std::endl;
16586 StreamingReporterBase::testRunEnded(_testRunStats);
16588 void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16589 StreamingReporterBase::testRunStarting(_testInfo);
16590 printTestFilters();
16593 void ConsoleReporter::lazyPrint() {
16595 m_tablePrinter->close();
16596 lazyPrintWithoutClosingBenchmarkTable();
16599 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16601 if (!currentTestRunInfo.used)
16602 lazyPrintRunInfo();
16603 if (!currentGroupInfo.used)
16604 lazyPrintGroupInfo();
16606 if (!m_headerPrinted) {
16607 printTestCaseAndSectionHeader();
16608 m_headerPrinted =
true;
16611 void ConsoleReporter::lazyPrintRunInfo() {
16612 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16613 Colour colour(Colour::SecondaryText);
16614 stream << currentTestRunInfo->name
16615 <<
" is a Catch v" << libraryVersion() <<
" host application.\n" 16616 <<
"Run with -? for options\n\n";
16618 if (m_config->rngSeed() != 0)
16619 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16621 currentTestRunInfo.used =
true;
16623 void ConsoleReporter::lazyPrintGroupInfo() {
16624 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16625 printClosedHeader(
"Group: " + currentGroupInfo->name);
16626 currentGroupInfo.used =
true;
16629 void ConsoleReporter::printTestCaseAndSectionHeader() {
16630 assert(!m_sectionStack.empty());
16631 printOpenHeader(currentTestCaseInfo->name);
16633 if (m_sectionStack.size() > 1) {
16634 Colour colourGuard(Colour::Headers);
16637 it = m_sectionStack.begin() + 1,
16638 itEnd = m_sectionStack.end();
16639 for (; it != itEnd; ++it)
16640 printHeaderString(it->name, 2);
16645 stream << getLineOfChars<
'-'>() <<
'\n';
16646 Colour colourGuard(Colour::FileName);
16647 stream << lineInfo <<
'\n';
16648 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16651 void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16652 printOpenHeader(_name);
16653 stream << getLineOfChars<
'.'>() <<
'\n';
16655 void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16656 stream << getLineOfChars<
'-'>() <<
'\n';
16658 Colour colourGuard(Colour::Headers);
16659 printHeaderString(_name);
16665 void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16666 std::size_t i = _string.find(
": ");
16667 if (i != std::string::npos)
16671 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16674 struct SummaryColumn {
16676 SummaryColumn( std::string _label, Colour::Code _colour )
16677 : label( std::move( _label ) ),
16678 colour( _colour ) {}
16679 SummaryColumn addRow( std::size_t count ) {
16682 std::string row = rss.
str();
16683 for (
auto& oldRow : rows) {
16684 while (oldRow.size() < row.size())
16685 oldRow =
' ' + oldRow;
16686 while (oldRow.size() > row.size())
16689 rows.push_back(row);
16694 Colour::Code colour;
16695 std::vector<std::string> rows;
16699 void ConsoleReporter::printTotals(
Totals const& totals ) {
16701 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16703 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16710 std::vector<SummaryColumn> columns;
16711 columns.push_back(SummaryColumn(
"", Colour::None)
16714 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16717 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16720 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16724 printSummaryRow(
"test cases", columns, 0);
16725 printSummaryRow(
"assertions", columns, 1);
16728 void ConsoleReporter::printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row) {
16729 for (
auto col : cols) {
16730 std::string
value = col.rows[row];
16731 if (col.label.empty()) {
16732 stream << label <<
": ";
16736 stream << Colour(Colour::Warning) <<
"- none -";
16737 }
else if (value !=
"0") {
16738 stream << Colour(Colour::LightGrey) <<
" | ";
16739 stream << Colour(col.colour)
16740 << value <<
' ' << col.label;
16746 void ConsoleReporter::printTotalsDivider(
Totals const& totals) {
16751 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16752 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16753 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16754 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16756 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16757 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16759 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16761 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16763 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16767 void ConsoleReporter::printSummaryDivider() {
16768 stream << getLineOfChars<
'-'>() <<
'\n';
16771 void ConsoleReporter::printTestFilters() {
16772 if (m_config->testSpec().hasFilters()) {
16773 Colour guard(Colour::BrightYellow);
16774 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16778 CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16782 #if defined(_MSC_VER) 16783 #pragma warning(pop) 16786 #if defined(__clang__) 16787 # pragma clang diagnostic pop 16795 #include <algorithm> 16801 std::string getCurrentTimestamp() {
16805 std::time(&rawtime);
16806 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16809 std::tm timeInfo = {};
16810 gmtime_s(&timeInfo, &rawtime);
16813 timeInfo = std::gmtime(&rawtime);
16817 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16820 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16822 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16824 return std::string(timeStamp, timeStampSize-1);
16827 std::string fileNameTag(
const std::vector<std::string> &tags) {
16828 auto it = std::find_if(begin(tags),
16830 [] (std::string
const& tag) {
return tag.front() ==
'#'; });
16831 if (it != tags.end())
16832 return it->substr(1);
16833 return std::string();
16840 std::string formatDuration(
double seconds ) {
16842 rss << std::fixed << std::setprecision( 3 ) << seconds;
16848 JunitReporter::JunitReporter( ReporterConfig
const& _config )
16849 : CumulativeReporterBase( _config ),
16850 xml( _config.stream() )
16852 m_reporterPrefs.shouldRedirectStdOut =
true;
16853 m_reporterPrefs.shouldReportAllAssertions =
true;
16856 JunitReporter::~JunitReporter() {}
16858 std::string JunitReporter::getDescription() {
16859 return "Reports test results in an XML format that looks like Ant's junitreport target";
16862 void JunitReporter::noMatchingTestCases( std::string
const& ) {}
16864 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16865 CumulativeReporterBase::testRunStarting( runInfo );
16866 xml.startElement(
"testsuites" );
16869 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16870 suiteTimer.start();
16871 stdOutForSuite.clear();
16872 stdErrForSuite.clear();
16873 unexpectedExceptions = 0;
16874 CumulativeReporterBase::testGroupStarting( groupInfo );
16877 void JunitReporter::testCaseStarting(
TestCaseInfo const& testCaseInfo ) {
16878 m_okToFail = testCaseInfo.
okToFail();
16881 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16883 unexpectedExceptions++;
16884 return CumulativeReporterBase::assertionEnded( assertionStats );
16887 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16888 stdOutForSuite += testCaseStats.stdOut;
16889 stdErrForSuite += testCaseStats.stdErr;
16890 CumulativeReporterBase::testCaseEnded( testCaseStats );
16893 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16894 double suiteTime = suiteTimer.getElapsedSeconds();
16895 CumulativeReporterBase::testGroupEnded( testGroupStats );
16896 writeGroup( *m_testGroups.back(), suiteTime );
16899 void JunitReporter::testRunEndedCumulative() {
16903 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16904 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
16906 TestGroupStats
const& stats = groupNode.value;
16907 xml.writeAttribute(
"name", stats.groupInfo.name );
16908 xml.writeAttribute(
"errors", unexpectedExceptions );
16909 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16910 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16911 xml.writeAttribute(
"hostname",
"tbd" );
16913 xml.writeAttribute(
"time",
"" );
16915 xml.writeAttribute(
"time", formatDuration( suiteTime ) );
16916 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16919 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16920 auto properties = xml.scopedElement(
"properties");
16921 if (m_config->hasTestFilters()) {
16922 xml.scopedElement(
"property")
16923 .writeAttribute(
"name",
"filters")
16924 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16926 if (m_config->rngSeed() != 0) {
16927 xml.scopedElement(
"property")
16928 .writeAttribute(
"name",
"random-seed")
16929 .writeAttribute(
"value", m_config->rngSeed());
16934 for(
auto const& child : groupNode.children )
16935 writeTestCase( *child );
16937 xml.scopedElement(
"system-out" ).writeText(
trim( stdOutForSuite ), XmlFormatting::Newline );
16938 xml.scopedElement(
"system-err" ).writeText(
trim( stdErrForSuite ), XmlFormatting::Newline );
16941 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16942 TestCaseStats
const& stats = testCaseNode.value;
16946 assert( testCaseNode.children.size() == 1 );
16947 SectionNode
const& rootSection = *testCaseNode.children.front();
16949 std::string className = stats.testInfo.className;
16951 if( className.empty() ) {
16952 className = fileNameTag(stats.testInfo.tags);
16953 if ( className.empty() )
16954 className =
"global";
16957 if ( !m_config->name().empty() )
16958 className = m_config->name() +
"." + className;
16960 writeSection( className,
"", rootSection, stats.testInfo.okToFail() );
16963 void JunitReporter::writeSection( std::string
const& className,
16964 std::string
const& rootName,
16965 SectionNode
const& sectionNode,
16966 bool testOkToFail) {
16967 std::string name =
trim( sectionNode.stats.sectionInfo.name );
16968 if( !rootName.empty() )
16969 name = rootName +
'/' + name;
16971 if( !sectionNode.assertions.empty() ||
16972 !sectionNode.stdOut.empty() ||
16973 !sectionNode.stdErr.empty() ) {
16974 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
16975 if( className.empty() ) {
16976 xml.writeAttribute(
"classname", name );
16977 xml.writeAttribute(
"name",
"root" );
16980 xml.writeAttribute(
"classname", className );
16981 xml.writeAttribute(
"name", name );
16983 xml.writeAttribute(
"time", formatDuration( sectionNode.stats.durationInSeconds ) );
16988 xml.writeAttribute(
"status",
"run" );
16990 if (sectionNode.stats.assertions.failedButOk) {
16991 xml.scopedElement(
"skipped")
16992 .writeAttribute(
"message",
"TEST_CASE tagged with !mayfail");
16995 writeAssertions( sectionNode );
16997 if( !sectionNode.stdOut.empty() )
16998 xml.scopedElement(
"system-out" ).writeText(
trim( sectionNode.stdOut ), XmlFormatting::Newline );
16999 if( !sectionNode.stdErr.empty() )
17000 xml.scopedElement(
"system-err" ).writeText(
trim( sectionNode.stdErr ), XmlFormatting::Newline );
17002 for(
auto const& childNode : sectionNode.childSections )
17003 if( className.empty() )
17004 writeSection( name,
"", *childNode, testOkToFail );
17006 writeSection( className, name, *childNode, testOkToFail );
17009 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
17010 for(
auto const& assertion : sectionNode.assertions )
17011 writeAssertion( assertion );
17014 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
17015 AssertionResult
const& result = stats.assertionResult;
17016 if( !result.isOk() ) {
17017 std::string elementName;
17018 switch( result.getResultType() ) {
17021 elementName =
"error";
17026 elementName =
"failure";
17036 elementName =
"internalError";
17040 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17042 xml.writeAttribute(
"message", result.getExpression() );
17043 xml.writeAttribute(
"type", result.getTestMacroName() );
17046 if (stats.totals.assertions.total() > 0) {
17047 rss <<
"FAILED" <<
":\n";
17048 if (result.hasExpression()) {
17050 rss << result.getExpressionInMacro();
17053 if (result.hasExpandedExpression()) {
17054 rss <<
"with expansion:\n";
17055 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
17061 if( !result.getMessage().empty() )
17062 rss << result.getMessage() <<
'\n';
17063 for(
auto const& msg : stats.infoMessages )
17065 rss << msg.message <<
'\n';
17067 rss <<
"at " << result.getSourceInfo();
17068 xml.writeText( rss.
str(), XmlFormatting::Newline );
17072 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
17082 ListeningReporter::ListeningReporter() {
17084 m_preferences.shouldReportAllAssertions =
true;
17087 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17088 m_listeners.push_back( std::move( listener ) );
17091 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17092 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
17093 m_reporter = std::move( reporter );
17094 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17097 ReporterPreferences ListeningReporter::getPreferences()
const {
17098 return m_preferences;
17101 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17102 return std::set<Verbosity>{ };
17105 void ListeningReporter::noMatchingTestCases( std::string
const& spec ) {
17106 for (
auto const& listener : m_listeners ) {
17107 listener->noMatchingTestCases( spec );
17109 m_reporter->noMatchingTestCases( spec );
17112 void ListeningReporter::reportInvalidArguments(std::string
const&arg){
17113 for (
auto const& listener : m_listeners ) {
17114 listener->reportInvalidArguments( arg );
17116 m_reporter->reportInvalidArguments( arg );
17119 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17120 void ListeningReporter::benchmarkPreparing( std::string
const& name ) {
17121 for (
auto const& listener : m_listeners) {
17122 listener->benchmarkPreparing(name);
17124 m_reporter->benchmarkPreparing(name);
17126 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
17127 for (
auto const& listener : m_listeners ) {
17128 listener->benchmarkStarting( benchmarkInfo );
17130 m_reporter->benchmarkStarting( benchmarkInfo );
17132 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
17133 for (
auto const& listener : m_listeners ) {
17134 listener->benchmarkEnded( benchmarkStats );
17136 m_reporter->benchmarkEnded( benchmarkStats );
17139 void ListeningReporter::benchmarkFailed( std::string
const& error ) {
17140 for (
auto const& listener : m_listeners) {
17141 listener->benchmarkFailed(error);
17143 m_reporter->benchmarkFailed(error);
17145 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17147 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
17148 for (
auto const& listener : m_listeners ) {
17149 listener->testRunStarting( testRunInfo );
17151 m_reporter->testRunStarting( testRunInfo );
17154 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17155 for (
auto const& listener : m_listeners ) {
17156 listener->testGroupStarting( groupInfo );
17158 m_reporter->testGroupStarting( groupInfo );
17161 void ListeningReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17162 for (
auto const& listener : m_listeners ) {
17163 listener->testCaseStarting( testInfo );
17165 m_reporter->testCaseStarting( testInfo );
17168 void ListeningReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17169 for (
auto const& listener : m_listeners ) {
17170 listener->sectionStarting( sectionInfo );
17172 m_reporter->sectionStarting( sectionInfo );
17175 void ListeningReporter::assertionStarting(
AssertionInfo const& assertionInfo ) {
17176 for (
auto const& listener : m_listeners ) {
17177 listener->assertionStarting( assertionInfo );
17179 m_reporter->assertionStarting( assertionInfo );
17183 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17184 for(
auto const& listener : m_listeners ) {
17185 static_cast<void>( listener->assertionEnded( assertionStats ) );
17187 return m_reporter->assertionEnded( assertionStats );
17190 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
17191 for (
auto const& listener : m_listeners ) {
17192 listener->sectionEnded( sectionStats );
17194 m_reporter->sectionEnded( sectionStats );
17197 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17198 for (
auto const& listener : m_listeners ) {
17199 listener->testCaseEnded( testCaseStats );
17201 m_reporter->testCaseEnded( testCaseStats );
17204 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17205 for (
auto const& listener : m_listeners ) {
17206 listener->testGroupEnded( testGroupStats );
17208 m_reporter->testGroupEnded( testGroupStats );
17211 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17212 for (
auto const& listener : m_listeners ) {
17213 listener->testRunEnded( testRunStats );
17215 m_reporter->testRunEnded( testRunStats );
17218 void ListeningReporter::skipTest(
TestCaseInfo const& testInfo ) {
17219 for (
auto const& listener : m_listeners ) {
17220 listener->skipTest( testInfo );
17222 m_reporter->skipTest( testInfo );
17225 bool ListeningReporter::isMulti()
const {
17233 #if defined(_MSC_VER) 17234 #pragma warning(push) 17235 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 17241 XmlReporter::XmlReporter( ReporterConfig
const& _config )
17242 : StreamingReporterBase( _config ),
17243 m_xml(_config.stream())
17245 m_reporterPrefs.shouldRedirectStdOut =
true;
17246 m_reporterPrefs.shouldReportAllAssertions =
true;
17249 XmlReporter::~XmlReporter() =
default;
17251 std::string XmlReporter::getDescription() {
17252 return "Reports test results as an XML document";
17255 std::string XmlReporter::getStylesheetRef()
const {
17256 return std::string();
17259 void XmlReporter::writeSourceInfo(
SourceLineInfo const& sourceInfo ) {
17261 .writeAttribute(
"filename", sourceInfo.
file )
17262 .writeAttribute(
"line", sourceInfo.
line );
17265 void XmlReporter::noMatchingTestCases( std::string
const&
s ) {
17266 StreamingReporterBase::noMatchingTestCases( s );
17269 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17270 StreamingReporterBase::testRunStarting( testInfo );
17271 std::string stylesheetRef = getStylesheetRef();
17272 if( !stylesheetRef.empty() )
17273 m_xml.writeStylesheetRef( stylesheetRef );
17274 m_xml.startElement(
"Catch" );
17275 if( !m_config->name().empty() )
17276 m_xml.writeAttribute(
"name", m_config->name() );
17277 if (m_config->testSpec().hasFilters())
17278 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17279 if( m_config->rngSeed() != 0 )
17280 m_xml.scopedElement(
"Randomness" )
17281 .writeAttribute(
"seed", m_config->rngSeed() );
17284 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17285 StreamingReporterBase::testGroupStarting( groupInfo );
17286 m_xml.startElement(
"Group" )
17287 .writeAttribute(
"name", groupInfo.name );
17290 void XmlReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17291 StreamingReporterBase::testCaseStarting(testInfo);
17292 m_xml.startElement(
"TestCase" )
17293 .writeAttribute(
"name",
trim( testInfo.
name ) )
17294 .writeAttribute(
"description", testInfo.
description )
17297 writeSourceInfo( testInfo.
lineInfo );
17300 m_testCaseTimer.start();
17301 m_xml.ensureTagClosed();
17304 void XmlReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17305 StreamingReporterBase::sectionStarting( sectionInfo );
17306 if( m_sectionDepth++ > 0 ) {
17307 m_xml.startElement(
"Section" )
17308 .writeAttribute(
"name",
trim( sectionInfo.
name ) );
17309 writeSourceInfo( sectionInfo.
lineInfo );
17310 m_xml.ensureTagClosed();
17314 void XmlReporter::assertionStarting(
AssertionInfo const& ) { }
17316 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17318 AssertionResult
const& result = assertionStats.assertionResult;
17320 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17324 for(
auto const& msg : assertionStats.infoMessages ) {
17326 m_xml.scopedElement(
"Info" )
17327 .writeText( msg.message );
17329 m_xml.scopedElement(
"Warning" )
17330 .writeText( msg.message );
17340 if( result.hasExpression() ) {
17341 m_xml.startElement(
"Expression" )
17342 .writeAttribute(
"success", result.succeeded() )
17343 .writeAttribute(
"type", result.getTestMacroName() );
17345 writeSourceInfo( result.getSourceInfo() );
17347 m_xml.scopedElement(
"Original" )
17348 .writeText( result.getExpression() );
17349 m_xml.scopedElement(
"Expanded" )
17350 .writeText( result.getExpandedExpression() );
17354 switch( result.getResultType() ) {
17356 m_xml.startElement(
"Exception" );
17357 writeSourceInfo( result.getSourceInfo() );
17358 m_xml.writeText( result.getMessage() );
17359 m_xml.endElement();
17362 m_xml.startElement(
"FatalErrorCondition" );
17363 writeSourceInfo( result.getSourceInfo() );
17364 m_xml.writeText( result.getMessage() );
17365 m_xml.endElement();
17368 m_xml.scopedElement(
"Info" )
17369 .writeText( result.getMessage() );
17375 m_xml.startElement(
"Failure" );
17376 writeSourceInfo( result.getSourceInfo() );
17377 m_xml.writeText( result.getMessage() );
17378 m_xml.endElement();
17384 if( result.hasExpression() )
17385 m_xml.endElement();
17390 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17391 StreamingReporterBase::sectionEnded( sectionStats );
17392 if( --m_sectionDepth > 0 ) {
17393 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
17394 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17395 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17396 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17399 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17401 m_xml.endElement();
17405 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17406 StreamingReporterBase::testCaseEnded( testCaseStats );
17407 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
17408 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17411 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17413 if( !testCaseStats.stdOut.empty() )
17414 m_xml.scopedElement(
"StdOut" ).writeText(
trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17415 if( !testCaseStats.stdErr.empty() )
17416 m_xml.scopedElement(
"StdErr" ).writeText(
trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17418 m_xml.endElement();
17421 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17422 StreamingReporterBase::testGroupEnded( testGroupStats );
17424 m_xml.scopedElement(
"OverallResults" )
17425 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17426 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17427 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17428 m_xml.scopedElement(
"OverallResultsCases")
17429 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed )
17430 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed )
17431 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk );
17432 m_xml.endElement();
17435 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17436 StreamingReporterBase::testRunEnded( testRunStats );
17437 m_xml.scopedElement(
"OverallResults" )
17438 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17439 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17440 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17441 m_xml.scopedElement(
"OverallResultsCases")
17442 .writeAttribute(
"successes", testRunStats.totals.testCases.passed )
17443 .writeAttribute(
"failures", testRunStats.totals.testCases.failed )
17444 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk );
17445 m_xml.endElement();
17448 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17449 void XmlReporter::benchmarkPreparing(std::string
const& name) {
17450 m_xml.startElement(
"BenchmarkResults")
17451 .writeAttribute(
"name", name);
17454 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &info) {
17455 m_xml.writeAttribute(
"samples", info.samples)
17456 .writeAttribute(
"resamples", info.resamples)
17457 .writeAttribute(
"iterations", info.iterations)
17458 .writeAttribute(
"clockResolution", info.clockResolution)
17459 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17460 .writeComment(
"All values in nano seconds");
17463 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17464 m_xml.startElement(
"mean")
17465 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17466 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17467 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17468 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17469 m_xml.endElement();
17470 m_xml.startElement(
"standardDeviation")
17471 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17472 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17473 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17474 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17475 m_xml.endElement();
17476 m_xml.startElement(
"outliers")
17477 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17478 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17479 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17480 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17481 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17482 m_xml.endElement();
17483 m_xml.endElement();
17486 void XmlReporter::benchmarkFailed(std::string
const &error) {
17487 m_xml.scopedElement(
"failed").
17488 writeAttribute(
"message", error);
17489 m_xml.endElement();
17491 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17493 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17497 #if defined(_MSC_VER) 17498 #pragma warning(pop) 17503 LeakDetector leakDetector;
17507 #pragma clang diagnostic pop 17513 #ifdef CATCH_CONFIG_MAIN 17518 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) 17520 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17523 int main (
int argc,
char * argv[]) {
17526 return Catch::Session().run( argc, argv );
17532 int main (
int argc,
char *
const argv[]) {
17533 #if !CATCH_ARC_ENABLED 17534 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17537 Catch::registerTestMethods();
17538 int result = Catch::Session().run( argc, (
char**)argv );
17540 #if !CATCH_ARC_ENABLED 17552 #if !defined(CATCH_CONFIG_IMPL_ONLY) 17554 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED 17555 # undef CLARA_CONFIG_MAIN 17558 #if !defined(CATCH_CONFIG_DISABLE) 17561 #ifdef CATCH_CONFIG_PREFIX_ALL 17563 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17564 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17566 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17567 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17568 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17569 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17570 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17571 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17572 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17574 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17575 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17576 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17577 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17578 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17580 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17581 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17582 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17583 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17584 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17585 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17586 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17588 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17589 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17591 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17592 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17594 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) 17595 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg ) 17596 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17597 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) 17599 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17600 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17601 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17602 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17603 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17604 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17605 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17606 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17607 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17609 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17611 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17612 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17613 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17614 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17615 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17616 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17617 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17618 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17619 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17621 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17622 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17623 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17624 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17625 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17626 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17627 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17628 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17631 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17632 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) 17633 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) 17635 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) 17636 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) 17640 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) 17641 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17642 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17643 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17644 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17645 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17646 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17647 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17649 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17650 #define CATCH_BENCHMARK(...) \ 17651 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__,,)) 17652 #define CATCH_BENCHMARK_ADVANCED(name) \ 17653 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) 17654 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17659 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17660 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17662 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17663 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17664 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17665 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17666 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17667 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17668 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17670 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17671 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17672 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17673 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17674 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17676 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17677 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17678 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17679 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17680 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17681 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17682 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17684 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17685 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17687 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17688 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17690 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) 17691 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) 17692 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17693 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) 17695 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17696 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17697 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17698 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17699 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17700 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17701 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17702 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17703 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17704 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17706 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17707 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17708 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17709 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17710 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17711 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17712 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17713 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17714 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17715 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) 17716 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17718 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17719 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17720 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17721 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17722 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17723 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17724 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17725 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17726 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) 17727 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17730 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17731 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) 17732 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) 17734 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) 17735 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) 17740 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) 17743 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) 17744 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17746 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17747 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17748 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17749 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17750 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17751 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17753 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17754 #define BENCHMARK(...) \ 17755 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__,,)) 17756 #define BENCHMARK_ADVANCED(name) \ 17757 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) 17758 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17762 #else // CATCH_CONFIG_DISABLE 17766 #ifdef CATCH_CONFIG_PREFIX_ALL 17768 #define CATCH_REQUIRE( ... ) (void)(0) 17769 #define CATCH_REQUIRE_FALSE( ... ) (void)(0) 17771 #define CATCH_REQUIRE_THROWS( ... ) (void)(0) 17772 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17773 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17774 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17775 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17776 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17777 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) 17779 #define CATCH_CHECK( ... ) (void)(0) 17780 #define CATCH_CHECK_FALSE( ... ) (void)(0) 17781 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) 17782 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17783 #define CATCH_CHECK_NOFAIL( ... ) (void)(0) 17785 #define CATCH_CHECK_THROWS( ... ) (void)(0) 17786 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17787 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17788 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17789 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17790 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17791 #define CATCH_CHECK_NOTHROW( ... ) (void)(0) 17793 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17794 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0) 17796 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) 17797 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17799 #define CATCH_INFO( msg ) (void)(0) 17800 #define CATCH_UNSCOPED_INFO( msg ) (void)(0) 17801 #define CATCH_WARN( msg ) (void)(0) 17802 #define CATCH_CAPTURE( msg ) (void)(0) 17804 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17805 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17806 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) 17807 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) 17808 #define CATCH_SECTION( ... ) 17809 #define CATCH_DYNAMIC_SECTION( ... ) 17810 #define CATCH_FAIL( ... ) (void)(0) 17811 #define CATCH_FAIL_CHECK( ... ) (void)(0) 17812 #define CATCH_SUCCEED( ... ) (void)(0) 17814 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17816 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17817 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17818 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17819 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17820 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17821 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17822 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17823 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17824 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17826 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17827 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17828 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17829 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17830 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17831 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17832 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17833 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17837 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17838 #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 ) 17839 #define CATCH_GIVEN( desc ) 17840 #define CATCH_AND_GIVEN( desc ) 17841 #define CATCH_WHEN( desc ) 17842 #define CATCH_AND_WHEN( desc ) 17843 #define CATCH_THEN( desc ) 17844 #define CATCH_AND_THEN( desc ) 17846 #define CATCH_STATIC_REQUIRE( ... ) (void)(0) 17847 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) 17852 #define REQUIRE( ... ) (void)(0) 17853 #define REQUIRE_FALSE( ... ) (void)(0) 17855 #define REQUIRE_THROWS( ... ) (void)(0) 17856 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17857 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17858 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17859 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17860 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17861 #define REQUIRE_NOTHROW( ... ) (void)(0) 17863 #define CHECK( ... ) (void)(0) 17864 #define CHECK_FALSE( ... ) (void)(0) 17865 #define CHECKED_IF( ... ) if (__VA_ARGS__) 17866 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17867 #define CHECK_NOFAIL( ... ) (void)(0) 17869 #define CHECK_THROWS( ... ) (void)(0) 17870 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17871 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17872 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17873 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17874 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17875 #define CHECK_NOTHROW( ... ) (void)(0) 17877 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17878 #define CHECK_THAT( arg, matcher ) (void)(0) 17880 #define REQUIRE_THAT( arg, matcher ) (void)(0) 17881 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17883 #define INFO( msg ) (void)(0) 17884 #define UNSCOPED_INFO( msg ) (void)(0) 17885 #define WARN( msg ) (void)(0) 17886 #define CAPTURE( msg ) (void)(0) 17888 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17889 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17890 #define METHOD_AS_TEST_CASE( method, ... ) 17891 #define REGISTER_TEST_CASE( Function, ... ) (void)(0) 17892 #define SECTION( ... ) 17893 #define DYNAMIC_SECTION( ... ) 17894 #define FAIL( ... ) (void)(0) 17895 #define FAIL_CHECK( ... ) (void)(0) 17896 #define SUCCEED( ... ) (void)(0) 17897 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17899 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17900 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17901 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17902 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17903 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17904 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17905 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17906 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17907 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17909 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17910 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17911 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17912 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17913 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17914 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17915 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17916 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17919 #define STATIC_REQUIRE( ... ) (void)(0) 17920 #define STATIC_REQUIRE_FALSE( ... ) (void)(0) 17924 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 17927 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) 17928 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) 17930 #define GIVEN( desc ) 17931 #define AND_GIVEN( desc ) 17932 #define WHEN( desc ) 17933 #define AND_WHEN( desc ) 17934 #define THEN( desc ) 17935 #define AND_THEN( desc ) 17941 #endif // ! CATCH_CONFIG_IMPL_ONLY 17947 # ifdef __ICC // icpc defines the __clang__ macro 17948 # pragma warning(pop) 17950 # pragma clang diagnostic pop 17952 #elif defined __GNUC__ 17953 # pragma GCC diagnostic pop 17958 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define CATCH_INTERNAL_ERROR(...)
virtual T const & get() const =0
const char * const_iterator
virtual void setGenerator(Generators::GeneratorBasePtr &&generator)=0
virtual ~IGeneratorTracker()
T valueOr(T const &defaultValue) const
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 operator==(StringRef const &other) const noexcept -> bool
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
std::string rawMemoryToString(const T &object)
std::unique_ptr< GeneratorUntypedBase > GeneratorBasePtr
FixedValuesGenerator(std::initializer_list< T > values)
const char * what() const noexcept override final
CaseSensitive::Choice m_caseSensitivity
bool isFalseTest(int flags)
IteratorGenerator(InputIterator first, InputSentinel last)
ExceptionTranslatorRegistrar(std::string(*translateFunction)(T &))
TestCase(ITestInvoker *testCase, TestCaseInfo &&info)
std::string m_description
EqualsMatcher(std::vector< T, AllocComp > const &comparator)
static std::enable_if<!::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
virtual void registerTest(TestCase const &testInfo)=0
Option & operator=(Option const &_other)
void toLowerInPlace(std::string &s)
virtual StartupExceptionRegistry const & getStartupExceptionRegistry() const =0
std::vector< std::unique_ptr< IExceptionTranslator const > > ExceptionTranslators
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)
constexpr const_iterator begin() const
void throw_runtime_error(std::string const &msg)
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)
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
PredicateMatcher(std::function< bool(T const &)> const &elem, std::string const &descr)
auto makeUnaryExpr() const -> UnaryExpr< LhsT >
std::string describe() const override
int main(int argc, char **argv)
std::vector< StringRef > splitStringRef(StringRef str, char delimiter)
GeneratorWrapper< T > m_generator
virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory)=0
ros::Time * timeStamp(M &m)
virtual IConfigPtr const & getConfig() const =0
auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool
std::vector< std::pair< int, StringRef > > m_values
auto getCurrentNanosecondsSinceEpoch() -> uint64_t
T const & operator+(T const &value, StreamEndStop)
auto getEstimatedClockResolution() -> uint64_t
std::string describe() const override
#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
SpecialProperties properties
bool match(ArgT const &arg) const override
GeneratorWrapper(std::unique_ptr< IGenerator< T >> generator)
GeneratorWrapper< U > m_generator
std::string toString() const
Detail::EnumInfo const & registerEnum(StringRef enumName, StringRef allEnums, std::initializer_list< E > values)
auto makeGenerators(as< T >, U &&val, Gs &&... moreGenerators) -> Generators< T >
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(*)() exceptionTranslateFunction
Approx & epsilon(T const &newEpsilon)
bool call(const std::string &service_name, MReq &req, MRes &res)
Capturer(StringRef macroName, SourceLineInfo const &lineInfo, ResultWas::OfType resultType, StringRef names)
static std::string convert(T const(&arr)[SZ])
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)
virtual auto hasGenerator() const -> bool=0
SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name)
virtual RunTests::InWhatOrder runOrder() const =0
bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis)
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)
bool operator==(const in6_addr a, const in6_addr b)
virtual void handleFatalErrorCondition(StringRef message)=0
GeneratorWrapper< T > m_generator
std::enable_if< std::is_floating_point< T >::value, GeneratorWrapper< T > >::type random(T a, T b)
ROSCPP_DECL bool validate(const std::string &name, std::string &error)
std::uniform_int_distribution< Integer > m_dist
virtual auto getGenerator() const -> Generators::GeneratorBasePtr const &=0
StringRef(std::string const &stdString) noexcept
std::vector< std::string > tags
auto substr(size_type start, size_type length) const noexcept -> StringRef
std::string operator+() const
static std::string convert(signed char const *str)
IMutableRegistryHub & getMutableRegistryHub()
Counts & operator+=(Counts const &other)
#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)
constexpr auto empty() const noexcept -> bool
StdString::EqualsMatcher Equals(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
virtual auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const &lineInfo) -> IGeneratorTracker &=0
virtual ~IMutableEnumValuesRegistry()
static std::string convert(U *p)
virtual void registerStartupException() noexcept=0
auto generate(StringRef generatorName, SourceLineInfo const &lineInfo, L const &generatorExpression) -> decltype(std::declval< decltype(generatorExpression())>().get())
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)
ROSCONSOLE_DECL void print(FilterBase *filter, void *logger, Level level, const char *file, int line, const char *function, const char *fmt,...) ROSCONSOLE_PRINTF_ATTRIBUTE(7
ResultDisposition::Flags resultDisposition
std::vector< TestCase > const & getAllTestCasesSorted(IConfig const &config)
ExceptionTranslator(std::string(*translateFunction)(T &))
void streamReconstructedExpression(std::ostream &os) const override
auto data() const noexcept -> char const *
bool shouldContinueOnFailure(int flags)
bool expectedToFail() const
auto str() const -> std::string
UnorderedEqualsMatcher(std::vector< T, AllocComp > const &target)
std::unique_ptr< T > make_unique(Args &&... args)
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
static std::string convert(R const &range)
GeneratorWrapper< T > range(T const &start, T const &end)
std::string tagsAsString() const
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
TestCase withName(std::string const &_newName) const
Vector::ContainsMatcher< T, AllocComp, AllocMatch > Contains(std::vector< T, AllocComp > const &comparator)
std::uniform_real_distribution< Float > m_dist
AssertionInfo m_assertionInfo
void populate(U &&valueOrGenerator, Gs &&... moreGenerators)
T const & operator*() const
ApproxMatcher & margin(T const &newMargin)
void handleUnexpectedInflightException()
Floating::WithinAbsMatcher WithinAbs(double target, double margin)
Approx & scale(T const &newScale)
void populate(GeneratorWrapper< T > &&generator)
static std::string convert(R C::*p)
StringRef m_matcherString
BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
auto makeTestInvoker(void(*testAsFunction)()) noexcept -> ITestInvoker *
AssertionHandler(StringRef const ¯oName, SourceLineInfo const &lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition)
StringRef capturedExpression
bool shouldSuppressFailure(int flags)
std::shared_ptr< IReporterFactory > IReporterFactoryPtr
StdString::EndsWithMatcher EndsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::string describe() const override
virtual ~IExceptionTranslatorRegistry()
ContainsMatcher(std::vector< T, AllocComp > const &comparator)
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
XMLRPCPP_DECL void setVerbosity(int level)
ReusableStringStream m_stream
virtual int benchmarkSamples() const =0
bool operator<(MessageInfo const &other) const
virtual ~ITransientExpression()
GeneratorWrapper< T > m_generator
TestCaseInfo const & getTestCaseInfo() const
bool operator<(SourceLineInfo const &other) const noexcept
void handleThrowingCallSkipped()
void handleExceptionThrownAsExpected()
Totals operator-(Totals const &other) const
std::unique_ptr< IGenerator< T > > m_generator
ROSCPP_DECL bool get(const std::string &key, std::string &s)
bool match(std::vector< T, AllocMatch > const &v) const override
virtual std::string translateActiveException() const =0
Catch::SimplePcg32 & m_rng
constexpr const_iterator end() const
void captureValues(size_t index, T const &value)
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
std::vector< T > m_returned
SingleValueGenerator(T &&value)
std::string toLower(std::string const &s)
void captureValues(size_t index, T const &value, Ts const &... values)
bool match(std::vector< T, AllocMatch > const &vec) const override
bool isThrowSafe(TestCase const &testCase, IConfig const &config)
std::string translateActiveException()
ROSCPP_DECL bool execute(const std::string &method, const XmlRpc::XmlRpcValue &request, XmlRpc::XmlRpcValue &response, XmlRpc::XmlRpcValue &payload, bool wait_for_master)
virtual ~IMutableContext()
virtual void streamReconstructedExpression(std::ostream &os) const =0
std::vector< T, AllocComp > const & m_comparator
Counts operator-(Counts const &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)
bool operator<(TestCase const &other) const
void discard(uint64_t skip)
std::size_t total() const
IContext & getCurrentContext()
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 &
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)
virtual double benchmarkConfidenceInterval() const =0
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
constexpr auto size() const noexcept -> size_type
ApproxMatcher & epsilon(T const &newEpsilon)
auto getElapsedNanoseconds() const -> uint64_t
virtual void registerListener(IReporterFactoryPtr const &factory)=0
void streamReconstructedExpression(std::ostream &os) const override
std::string translate(ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd) const override
void seed(result_type seed_)
typename std::remove_reference< typename std::remove_cv< typename std::result_of< Func(U...)>::type >::type >::type FunctionReturnType
auto getElapsedMicroseconds() const -> uint64_t
MapGenerator(F2 &&function, GeneratorWrapper< U > &&generator)
bool operator==(TestCase const &other) const
const std::string unprintableString
const T * operator->() const
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)
virtual IReporterRegistry const & getReporterRegistry() const =0
std::vector< MatcherBase< ArgT > const * > m_matchers
virtual IResultCapture * getResultCapture()=0
std::string describe() const override
MatchAllOf< T > operator&&(MatcherBase const &other) const
constexpr auto isNullTerminated() const noexcept -> bool
FilterGenerator(P &&pred, GeneratorWrapper< T > &&generator)
virtual unsigned int rngSeed() const =0
Totals delta(Totals const &prevTotals) const
auto makeMatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString) -> MatchExpr< ArgT, MatcherT >
RandomIntegerGenerator(Integer a, Integer b)
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)
ExceptionMessageMatcher(std::string const &message)
std::string describe() const override
RepeatGenerator(size_t repeats, GeneratorWrapper< T > &&generator)
MatchNotOf< T > operator!() const
std::function< bool(T const &)> m_predicate
virtual void sectionEnded(SectionEndInfo const &endInfo)=0
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff)
void throw_domain_error(std::string const &msg)
void handleExceptionMatchExpr(AssertionHandler &handler, std::string const &str, StringRef const &matcherString)
Catch::SimplePcg32 & m_rng
MatcherBase< ArgT > const & m_underlyingMatcher
auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const &lineInfo) -> IGeneratorTracker &
#define CATCH_RUNTIME_ERROR(...)
static IMutableContext * currentContext
virtual IExceptionTranslatorRegistry const & getExceptionTranslatorRegistry() const =0
IMutableContext & getCurrentMutableContext()
void streamReconstructedExpression(std::ostream &os) const override
IRegistryHub const & getRegistryHub()
virtual ~IExceptionTranslator()
std::uint32_t result_type
Generic::PredicateMatcher< T > Predicate(std::function< bool(T const &)> const &predicate, std::string const &description="")
void handleUnexpectedExceptionNotThrown()
virtual bool benchmarkNoAnalysis() const =0
MatchAnyOf< T > operator||(MatcherBase const &other) const
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()
Generators(Gs &&... moreGenerators)
std::string describe() const override
MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
RandomFloatingGenerator(Float a, Float b)
virtual void setConfig(IConfigPtr const &config)=0
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)
bool equalityComparisonImpl(double other) const
auto makeStream(StringRef const &filename) -> IStream const *
static std::string convert(unsigned char const *str)
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
auto get() -> std::ostream &
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)
RangeGenerator(T const &start, T const &end)
bool operator==(MessageInfo const &other) const
auto getElapsedMilliseconds() const -> unsigned int