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 0 21 # pragma clang system_header 22 #elif defined __GNUC__ 23 # pragma GCC system_header 29 # ifdef __ICC // icpc defines the __clang__ macro 30 # pragma warning(push) 31 # pragma warning(disable: 161 1682) 33 # pragma clang diagnostic push 34 # pragma clang diagnostic ignored "-Wpadded" 35 # pragma clang diagnostic ignored "-Wswitch-enum" 36 # pragma clang diagnostic ignored "-Wcovered-switch-default" 38 #elif defined __GNUC__ 42 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details 44 # pragma GCC diagnostic push 45 # pragma GCC diagnostic ignored "-Wunused-variable" 46 # pragma GCC diagnostic ignored "-Wpadded" 49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) 51 # define CATCH_CONFIG_ALL_PARTS 56 #if defined(CATCH_CONFIG_ALL_PARTS) 57 # define CATCH_CONFIG_EXTERNAL_INTERFACES 58 # if defined(CATCH_CONFIG_DISABLE_MATCHERS) 59 # undef CATCH_CONFIG_DISABLE_MATCHERS 61 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 62 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 66 #if !defined(CATCH_CONFIG_IMPL_ONLY) 70 # include <TargetConditionals.h> 71 # if TARGET_OS_OSX == 1 72 # define CATCH_PLATFORM_MAC 73 # elif TARGET_OS_IPHONE == 1 74 # define CATCH_PLATFORM_IPHONE 77 #elif defined(linux) || defined(__linux) || defined(__linux__) 78 # define CATCH_PLATFORM_LINUX 80 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) 81 # define CATCH_PLATFORM_WINDOWS 87 # ifndef CLARA_CONFIG_MAIN 88 # define CLARA_CONFIG_MAIN_NOT_DEFINED 89 # define CLARA_CONFIG_MAIN 125 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) 126 # define CATCH_CPP14_OR_GREATER 129 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) 130 # define CATCH_CPP17_OR_GREATER 135 #if defined(__cpp_lib_uncaught_exceptions) 136 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 141 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) 142 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) 143 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) 145 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) 149 #if defined(__clang__) 151 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) 152 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) 165 # if !defined(__ibmxl__) 166 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) 169 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 170 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ 171 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") 173 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 174 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) 176 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 177 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) 179 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 180 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) 182 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 183 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) 189 #if !defined(CATCH_PLATFORM_WINDOWS) 190 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS 195 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) 196 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS 200 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS 201 # define CATCH_CONFIG_COLOUR_NONE 206 #if defined(__ANDROID__) 207 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING 208 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE 213 #if defined(__MINGW32__) 214 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH 219 #if defined(__ORBIS__) 220 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE 232 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ 233 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) 235 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING 242 #if defined(_MSC_VER) 244 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) 245 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) 247 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer 248 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 253 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) 254 # define CATCH_CONFIG_COLOUR_NONE 256 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH 262 # if !defined(__clang__) // Handle Clang masquerading for msvc 263 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) 264 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 265 # endif // MSVC_TRADITIONAL 270 #if defined(_REENTRANT) || defined(_MSC_VER) 272 # define CATCH_INTERNAL_CONFIG_USE_ASYNC 277 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) 278 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED 284 # define CATCH_INTERNAL_CONFIG_NO_WCHAR 289 #if defined(__BORLANDC__) 290 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN 300 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) 301 #define CATCH_INTERNAL_CONFIG_COUNTER 309 #if defined(UNDER_RTSS) || defined(RTX64_BUILD) 310 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH 311 #define CATCH_INTERNAL_CONFIG_NO_ASYNC 312 #define CATCH_CONFIG_COLOUR_NONE 315 #if !defined(_GLIBCXX_USE_C99_MATH_TR1) 316 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER 320 #if defined(__has_include) 322 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) 323 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW 327 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 328 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL 329 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 332 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 333 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE 334 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 337 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) 338 # if defined(__clang__) && (__clang_major__ < 8) 342 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) 343 # define CATCH_CONFIG_NO_CPP17_VARIANT 345 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT 346 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) 348 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT 349 # endif // defined(__clang__) && (__clang_major__ < 8) 350 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER) 351 #endif // defined(__has_include) 353 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) 354 # define CATCH_CONFIG_COUNTER 356 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) 357 # define CATCH_CONFIG_WINDOWS_SEH 360 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) 361 # define CATCH_CONFIG_POSIX_SIGNALS 364 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) 365 # define CATCH_CONFIG_WCHAR 368 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) 369 # define CATCH_CONFIG_CPP11_TO_STRING 372 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) 373 # define CATCH_CONFIG_CPP17_OPTIONAL 376 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 377 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 380 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) 381 # define CATCH_CONFIG_CPP17_STRING_VIEW 384 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) 385 # define CATCH_CONFIG_CPP17_VARIANT 388 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) 389 # define CATCH_CONFIG_CPP17_BYTE 392 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 393 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE 396 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) 397 # define CATCH_CONFIG_NEW_CAPTURE 400 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 401 # define CATCH_CONFIG_DISABLE_EXCEPTIONS 404 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) 405 # define CATCH_CONFIG_POLYFILL_ISNAN 408 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) 409 # define CATCH_CONFIG_USE_ASYNC 412 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) 413 # define CATCH_CONFIG_ANDROID_LOGWRITE 416 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 417 # define CATCH_CONFIG_GLOBAL_NEXTAFTER 422 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) 423 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION 425 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) 426 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 428 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) 429 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS 431 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) 432 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS 434 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) 435 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS 437 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) 438 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS 443 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) 444 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) 447 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) 448 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 449 #elif defined(__clang__) && (__clang_major__ < 5) 450 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 453 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) 454 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 457 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 458 #define CATCH_TRY if ((true)) 459 #define CATCH_CATCH_ALL if ((false)) 460 #define CATCH_CATCH_ANON(type) if ((false)) 462 #define CATCH_TRY try 463 #define CATCH_CATCH_ALL catch (...) 464 #define CATCH_CATCH_ANON(type) catch (type) 467 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) 468 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 472 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line 473 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) 474 #ifdef CATCH_CONFIG_COUNTER 475 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) 477 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) 519 bool empty() const noexcept {
return file[0] ==
'\0'; }
547 #define CATCH_INTERNAL_LINEINFO \ 548 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) 559 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ 560 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 561 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 562 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ 563 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 577 virtual void invoke ()
const = 0;
586 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
587 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const = 0;
592 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
616 static constexpr
char const*
const s_empty =
"";
618 char const* m_start = s_empty;
622 constexpr
StringRef() noexcept = default;
624 StringRef(
char const* rawChars ) noexcept;
627 : m_start( rawChars ),
632 : m_start( stdString.c_str() ),
633 m_size( stdString.size() )
636 explicit operator std::string()
const {
637 return std::string(m_start, m_size);
643 return !(*
this == other);
646 auto operator[] (
size_type index )
const noexcept ->
char {
647 assert(index < m_size);
648 return m_start[index];
652 constexpr
auto empty() const noexcept ->
bool {
661 auto c_str()
const ->
char const*;
670 auto data()
const noexcept ->
char const*;
673 return m_start[m_size] ==
'\0';
684 constexpr
auto operator "" _sr(
char const* rawChars, std::size_t size ) noexcept ->
StringRef {
689 constexpr
auto operator "" _catch_sr(
char const* rawChars, std::size_t size ) noexcept ->
Catch::StringRef {
697 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ 698 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) 699 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) 700 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) 701 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) 702 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) 704 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 705 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ 707 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) 708 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) 710 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) 713 #define CATCH_REC_END(...) 714 #define CATCH_REC_OUT 716 #define CATCH_EMPTY() 717 #define CATCH_DEFER(id) id CATCH_EMPTY() 719 #define CATCH_REC_GET_END2() 0, CATCH_REC_END 720 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 721 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 722 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT 723 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) 724 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) 726 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 727 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) 728 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 730 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) 731 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) 732 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) 737 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 739 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 741 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) 742 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ 743 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ 744 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF 745 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) 746 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 747 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ 748 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) 751 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) 752 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ 753 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) 756 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ 757 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) 759 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) 761 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 762 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) 763 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) 765 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())) 766 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) 769 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ 770 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) 772 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) 773 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) 774 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) 775 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) 776 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) 777 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) 778 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) 779 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) 780 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) 781 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) 782 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) 784 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N 786 #define INTERNAL_CATCH_TYPE_GEN\ 787 template<typename...> struct TypeList {};\ 788 template<typename...Ts>\ 789 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\ 790 template<template<typename...> class...> struct TemplateTypeList{};\ 791 template<template<typename...> class...Cs>\ 792 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\ 793 template<typename...>\ 795 template<typename...>\ 797 template<template<typename...> class, typename...>\ 799 template<template<typename...> class, typename>\ 802 template<typename T> \ 803 struct append<T> { using type = T; };\ 804 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\ 805 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\ 806 template< template<typename...> class L1, typename...E1, typename...Rest>\ 807 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\ 809 template< template<typename...> class Container, template<typename...> class List, typename...elems>\ 810 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\ 811 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\ 812 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\ 814 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\ 815 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\ 816 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\ 817 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; }; 819 #define INTERNAL_CATCH_NTTP_1(signature, ...)\ 820 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\ 821 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 822 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \ 823 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\ 824 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\ 825 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \ 827 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 828 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\ 829 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\ 830 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\ 831 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\ 832 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; }; 834 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName) 835 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\ 836 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 837 static void TestName() 838 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\ 839 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 840 static void TestName() 842 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName) 843 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\ 844 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 845 static void TestName() 846 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\ 847 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 848 static void TestName() 850 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\ 851 template<typename Type>\ 852 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\ 854 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 857 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\ 858 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 859 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\ 861 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 864 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\ 865 template<typename Type>\ 866 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 868 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 871 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\ 872 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 873 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 875 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 878 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName) 879 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\ 880 template<typename TestType> \ 881 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ 885 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\ 886 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 887 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ 891 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName) 892 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\ 893 template<typename TestType> \ 894 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test() 895 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\ 896 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 897 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test() 899 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 900 #define INTERNAL_CATCH_NTTP_0 901 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0) 902 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__) 903 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__) 904 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__) 905 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__) 906 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__) 907 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__) 908 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__) 910 #define INTERNAL_CATCH_NTTP_0(signature) 911 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__)) 912 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)) 913 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)) 914 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)) 915 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)) 916 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)) 917 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)) 918 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)) 925 #include <type_traits> 933 template <
typename Fun,
typename... Args>
935 template <
typename...>
936 std::false_type
static test(...);
939 template <
typename T>
942 template <
typename Fun,
typename... Args>
943 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
945 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 948 template <
typename Func,
typename... U>
949 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
952 template <
typename Func,
typename... U>
953 using FunctionReturnType =
typename std::remove_reference<
typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
967 void (C::*m_testAsMethod)();
973 (obj.*m_testAsMethod)();
997 #if defined(CATCH_CONFIG_DISABLE) 998 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ 999 static void TestName() 1000 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ 1002 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1006 void TestName::test() 1007 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \ 1008 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1009 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1011 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1012 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1015 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1017 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1018 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1019 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) 1021 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1022 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) 1025 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1026 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1027 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) 1029 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1030 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) 1033 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1034 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1035 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) 1037 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1038 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) 1041 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1042 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1043 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) 1045 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1046 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) 1051 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ 1052 static void TestName(); \ 1053 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1054 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1055 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1056 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1057 static void TestName() 1058 #define INTERNAL_CATCH_TESTCASE( ... ) \ 1059 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) 1062 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ 1063 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1064 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1065 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1066 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1069 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ 1070 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1071 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1073 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1076 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \ 1078 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1079 void TestName::test() 1080 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ 1081 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) 1084 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ 1085 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1086 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1087 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \ 1088 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1091 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\ 1092 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1093 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1094 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1095 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1096 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1098 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1099 INTERNAL_CATCH_TYPE_GEN\ 1100 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1101 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1102 template<typename...Types> \ 1106 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1107 using expander = int[];\ 1108 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... }; \ 1111 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1112 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1117 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1118 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1120 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1121 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1122 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) 1124 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1125 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) ) 1128 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1129 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1130 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) 1132 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1133 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) 1136 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ 1137 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1138 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1139 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1140 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1141 template<typename TestType> static void TestFuncName(); \ 1143 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1144 INTERNAL_CATCH_TYPE_GEN \ 1145 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ 1146 template<typename... Types> \ 1148 void reg_tests() { \ 1150 using expander = int[]; \ 1151 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1152 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1153 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1154 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };\ 1157 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1158 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \ 1165 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1166 template<typename TestType> \ 1167 static void TestFuncName() 1169 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1170 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1171 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__) 1173 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1174 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) ) 1177 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1178 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1179 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__) 1181 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1182 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) ) 1185 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ 1186 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1187 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1188 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1189 template<typename TestType> static void TestFunc(); \ 1191 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1192 INTERNAL_CATCH_TYPE_GEN\ 1193 template<typename... Types> \ 1195 void reg_tests() { \ 1197 using expander = int[]; \ 1198 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };\ 1201 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1202 using TestInit = typename convert<TestName, TmplList>::type; \ 1208 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1209 template<typename TestType> \ 1210 static void TestFunc() 1212 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ 1213 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList ) 1215 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1216 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1217 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1218 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1219 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1221 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1222 INTERNAL_CATCH_TYPE_GEN\ 1223 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1224 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1225 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1226 template<typename...Types> \ 1227 struct TestNameClass{\ 1230 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1231 using expander = int[];\ 1232 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... }; \ 1235 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1236 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1241 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1242 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1244 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1245 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1246 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) 1248 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1249 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) ) 1252 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1253 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1254 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) 1256 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1257 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) ) 1260 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ 1261 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1262 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1263 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1264 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1265 template<typename TestType> \ 1266 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1270 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\ 1271 INTERNAL_CATCH_TYPE_GEN \ 1272 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1273 template<typename...Types>\ 1274 struct TestNameClass{\ 1277 using expander = int[];\ 1278 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1279 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1280 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1281 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... }; \ 1284 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1285 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\ 1292 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1293 template<typename TestType> \ 1294 void TestName<TestType>::test() 1296 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1297 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1298 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ ) 1300 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1301 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) ) 1304 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1305 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1306 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ ) 1308 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1309 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) ) 1312 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ 1313 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1314 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1315 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1316 template<typename TestType> \ 1317 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1321 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1322 INTERNAL_CATCH_TYPE_GEN\ 1323 template<typename...Types>\ 1324 struct TestNameClass{\ 1327 using expander = int[];\ 1328 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... }; \ 1331 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1332 using TestInit = typename convert<TestNameClass, TmplList>::type;\ 1338 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1339 template<typename TestType> \ 1340 void TestName<TestType>::test() 1342 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ 1343 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList ) 1365 ExpressionFailed = FailureBit | 1,
1366 ExplicitFailure = FailureBit | 2,
1373 FatalErrorCondition = 0x200 | FailureBit
1384 ContinueOnFailure = 0x02,
1421 #include <type_traits> 1431 std::ostream&
cout();
1432 std::ostream&
cerr();
1433 std::ostream&
clog();
1439 virtual std::ostream& stream()
const = 0;
1445 std::size_t m_index;
1446 std::ostream* m_oss;
1451 auto str()
const -> std::string;
1453 template<
typename T>
1458 auto get() -> std::ostream& {
return *m_oss; }
1485 template<
typename E>
1487 static_assert(
sizeof(
int) >=
sizeof(E),
"Cannot serialize enum to int");
1488 std::vector<int> intValues;
1489 intValues.reserve( values.size() );
1490 for(
auto enumValue : values )
1491 intValues.push_back( static_cast<int>( enumValue ) );
1492 return registerEnum( enumName, allEnums, intValues );
1500 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1501 #include <string_view> 1507 #import <Foundation/Foundation.h> 1509 #ifdef __has_feature 1510 #define CATCH_ARC_ENABLED __has_feature(objc_arc) 1512 #define CATCH_ARC_ENABLED 0 1515 void arcSafeRelease( NSObject* obj );
1516 id performOptionalSelector(
id obj,
SEL sel );
1518 #if !CATCH_ARC_ENABLED 1519 inline void arcSafeRelease( NSObject* obj ) {
1522 inline id performOptionalSelector(
id obj,
SEL sel ) {
1523 if( [obj respondsToSelector: sel] )
1524 return [obj performSelector: sel];
1527 #define CATCH_UNSAFE_UNRETAINED 1528 #define CATCH_ARC_STRONG 1530 inline void arcSafeRelease( NSObject* ){}
1531 inline id performOptionalSelector(
id obj,
SEL sel ) {
1533 #pragma clang diagnostic push 1534 #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 1536 if( [obj respondsToSelector: sel] )
1537 return [obj performSelector: sel];
1539 #pragma clang diagnostic pop 1543 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained 1544 #define CATCH_ARC_STRONG __strong 1551 #pragma warning(push) 1552 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless 1562 template<
typename T>
1567 template<
typename T>
1569 template<
typename Stream,
typename U>
1570 static auto test(
int)
1571 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1573 template<
typename,
typename>
1574 static auto test(...)->std::false_type;
1577 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1580 template<
typename E>
1583 template<
typename T>
1584 typename std::enable_if<
1589 template<
typename T>
1590 typename std::enable_if<
1596 template<
typename T>
1597 typename std::enable_if<
1603 #if defined(_MANAGED) 1604 template<
typename T>
1606 std::string clrReferenceToString( T^ ref ) {
1608 return std::string(
"null");
1609 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1610 cli::pin_ptr<System::Byte> p = &bytes[0];
1611 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1618 template <
typename T,
typename =
void>
1620 template <
typename Fake = T>
1627 rss.operator<<(
value);
1631 template <
typename Fake = T>
1635 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) 1638 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1647 template <
typename T>
1649 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1652 template<
typename E>
1657 #if defined(_MANAGED) 1658 template <
typename T>
1660 return ::Catch::StringMaker<T^>::convert(e);
1670 static std::string convert(
const std::string&
str);
1673 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1676 static std::string convert(std::string_view
str);
1682 static std::string convert(
char const *
str);
1686 static std::string convert(
char *
str);
1689 #ifdef CATCH_CONFIG_WCHAR 1692 static std::string convert(
const std::wstring& wstr);
1695 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1698 static std::string convert(std::wstring_view
str);
1704 static std::string convert(
wchar_t const *
str);
1708 static std::string convert(
wchar_t *
str);
1733 #if defined(CATCH_CONFIG_CPP17_BYTE) 1736 static std::string convert(std::byte value);
1738 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 1741 static std::string convert(
int value);
1745 static std::string convert(
long value);
1749 static std::string convert(
long long value);
1753 static std::string convert(
unsigned int value);
1757 static std::string convert(
unsigned long value);
1761 static std::string convert(
unsigned long long value);
1766 static std::string convert(
bool b);
1771 static std::string convert(
char c);
1775 static std::string convert(
signed char c);
1779 static std::string convert(
unsigned char c);
1784 static std::string convert(std::nullptr_t);
1789 static std::string convert(
float value);
1795 static std::string convert(
double value);
1799 template <
typename T>
1801 template <
typename U>
1811 template <
typename R,
typename C>
1822 #if defined(_MANAGED) 1823 template <
typename T>
1825 static std::string convert( T^ ref ) {
1826 return ::Catch::Detail::clrReferenceToString(ref);
1832 template<
typename InputIterator>
1836 if (first != last) {
1838 for (++first; first !=
last; ++first)
1849 static std::string convert(NSString * nsstring) {
1852 return std::string(
"@") + [nsstring UTF8String];
1857 static std::string convert(NSObject* nsObject) {
1863 inline std::string
stringify( NSString* nsstring ) {
1876 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) 1877 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1878 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1879 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1880 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 1881 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1885 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) 1888 template<
typename T1,
typename T2>
1890 static std::string convert(
const std::pair<T1, T2>& pair) {
1901 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1903 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) 1906 template<
typename T>
1908 static std::string convert(
const std::optional<T>& optional) {
1910 if (optional.has_value()) {
1919 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1922 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) 1931 struct TupleElementPrinter {
1932 static void print(
const Tuple& tuple, std::ostream& os) {
1933 os << (N ?
", " :
" ")
1935 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1943 struct TupleElementPrinter<Tuple, N, false> {
1944 static void print(
const Tuple&, std::ostream&) {}
1949 template<
typename ...Types>
1951 static std::string convert(
const std::tuple<Types...>& tuple) {
1954 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.
get());
1960 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1962 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) 1967 static std::string convert(
const std::monostate&) {
1972 template<
typename... Elements>
1974 static std::string convert(
const std::variant<Elements...>& variant) {
1975 if (variant.valueless_by_exception()) {
1976 return "{valueless variant}";
1979 [](
const auto&
value) {
1988 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1996 template <
typename...>
2001 template <
typename T,
typename =
void>
2005 template <
typename T>
2010 template <
typename T>
2014 #if defined(_MANAGED) // Managed types are never ranges 2015 template <
typename T>
2017 static const bool value =
false;
2021 template<
typename Range>
2027 template<
typename Allocator>
2043 template<
typename R>
2050 template <
typename T,
int SZ>
2060 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 2067 template <
class Ratio>
2068 struct ratio_string {
2069 static std::string symbol();
2072 template <
class Ratio>
2073 std::string ratio_string<Ratio>::symbol() {
2075 rss <<
'[' << Ratio::num <<
'/' 2076 << Ratio::den <<
']';
2080 struct ratio_string<std::atto> {
2081 static std::string symbol();
2084 struct ratio_string<std::femto> {
2085 static std::string symbol();
2088 struct ratio_string<std::pico> {
2089 static std::string symbol();
2092 struct ratio_string<std::nano> {
2093 static std::string symbol();
2096 struct ratio_string<std::micro> {
2097 static std::string symbol();
2100 struct ratio_string<std::milli> {
2101 static std::string symbol();
2106 template<
typename Value,
typename Ratio>
2107 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2108 static std::string convert(std::chrono::duration<Value, Ratio>
const& duration) {
2110 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2114 template<
typename Value>
2115 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2116 static std::string convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2118 rss << duration.count() <<
" s";
2122 template<
typename Value>
2123 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2124 static std::string convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2126 rss << duration.count() <<
" m";
2130 template<
typename Value>
2131 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2132 static std::string convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2134 rss << duration.count() <<
" h";
2142 template<
typename Clock,
typename Duration>
2144 static std::string convert(std::chrono::time_point<Clock, Duration>
const&
time_point) {
2149 template<
typename Duration>
2151 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const&
time_point) {
2152 auto converted = std::chrono::system_clock::to_time_t(time_point);
2155 std::tm timeInfo = {};
2156 gmtime_s(&timeInfo, &converted);
2158 std::tm* timeInfo = std::gmtime(&converted);
2161 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2162 char timeStamp[timeStampSize];
2163 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2166 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2168 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2170 return std::string(timeStamp);
2174 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 2176 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ 2178 template<> struct StringMaker<enumName> { \ 2179 static std::string convert( enumName value ) { \ 2180 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ 2181 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \ 2186 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) 2189 #pragma warning(pop) 2196 #pragma warning(push) 2197 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch 2198 #pragma warning(disable:4018) // more "signed/unsigned mismatch" 2199 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) 2200 #pragma warning(disable:4180) // qualifier applied to function type has no meaning 2201 #pragma warning(disable:4800) // Forcing result to true or false 2209 virtual void streamReconstructedExpression( std::ostream &os )
const = 0;
2212 : m_isBinaryExpression( isBinaryExpression ),
2227 template<
typename LhsT,
typename RhsT>
2233 void streamReconstructedExpression( std::ostream &os )
const override {
2246 template<
typename T>
2249 "chained comparisons are not supported inside assertions, " 2250 "wrap the expression inside parentheses, or decompose it");
2253 template<
typename T>
2256 "chained comparisons are not supported inside assertions, " 2257 "wrap the expression inside parentheses, or decompose it");
2260 template<
typename T>
2263 "chained comparisons are not supported inside assertions, " 2264 "wrap the expression inside parentheses, or decompose it");
2267 template<
typename T>
2270 "chained comparisons are not supported inside assertions, " 2271 "wrap the expression inside parentheses, or decompose it");
2274 template<
typename T>
2277 "chained comparisons are not supported inside assertions, " 2278 "wrap the expression inside parentheses, or decompose it");
2281 template<
typename T>
2284 "chained comparisons are not supported inside assertions, " 2285 "wrap the expression inside parentheses, or decompose it");
2288 template<
typename T>
2291 "chained comparisons are not supported inside assertions, " 2292 "wrap the expression inside parentheses, or decompose it");
2295 template<
typename T>
2298 "chained comparisons are not supported inside assertions, " 2299 "wrap the expression inside parentheses, or decompose it");
2303 template<
typename LhsT>
2307 void streamReconstructedExpression( std::ostream &os )
const override {
2319 template<
typename LhsT,
typename RhsT>
2320 auto compareEqual( LhsT
const& lhs, RhsT
const& rhs ) ->
bool {
return static_cast<bool>(lhs == rhs); }
2321 template<
typename T>
2322 auto compareEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2323 template<
typename T>
2324 auto compareEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2325 template<
typename T>
2326 auto compareEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2327 template<
typename T>
2328 auto compareEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2330 template<
typename LhsT,
typename RhsT>
2331 auto compareNotEqual( LhsT
const& lhs, RhsT&& rhs ) ->
bool {
return static_cast<bool>(lhs != rhs); }
2332 template<
typename T>
2333 auto compareNotEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2334 template<
typename T>
2335 auto compareNotEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2336 template<
typename T>
2337 auto compareNotEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2338 template<
typename T>
2339 auto compareNotEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2341 template<
typename LhsT>
2347 template<
typename RhsT>
2349 return {
compareEqual( m_lhs, rhs ), m_lhs,
"==", rhs };
2352 return { m_lhs == rhs, m_lhs,
"==", rhs };
2355 template<
typename RhsT>
2360 return { m_lhs != rhs, m_lhs,
"!=", rhs };
2363 template<
typename RhsT>
2365 return {
static_cast<bool>(m_lhs > rhs), m_lhs,
">", rhs };
2367 template<
typename RhsT>
2369 return {
static_cast<bool>(m_lhs < rhs), m_lhs,
"<", rhs };
2371 template<
typename RhsT>
2373 return {
static_cast<bool>(m_lhs >= rhs), m_lhs,
">=", rhs };
2375 template<
typename RhsT>
2377 return {
static_cast<bool>(m_lhs <= rhs), m_lhs,
"<=", rhs };
2379 template <
typename RhsT>
2381 return {
static_cast<bool>(m_lhs | rhs), m_lhs,
"|", rhs };
2383 template <
typename RhsT>
2385 return {
static_cast<bool>(m_lhs & rhs), m_lhs,
"&", rhs };
2387 template <
typename RhsT>
2389 return {
static_cast<bool>(m_lhs ^ rhs), m_lhs,
"^", rhs };
2392 template<
typename RhsT>
2395 "operator&& is not supported inside assertions, " 2396 "wrap the expression inside parentheses, or decompose it");
2399 template<
typename RhsT>
2402 "operator|| is not supported inside assertions, " 2403 "wrap the expression inside parentheses, or decompose it");
2413 template<
typename T>
2419 template<
typename T>
2432 #pragma warning(pop) 2443 class AssertionResult;
2456 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2457 struct BenchmarkInfo;
2458 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2459 struct BenchmarkStats;
2460 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2466 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
2467 Counts& assertions ) = 0;
2469 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo ) = 0;
2473 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2474 virtual void benchmarkPreparing( std::string
const& name ) = 0;
2475 virtual void benchmarkStarting( BenchmarkInfo
const& info ) = 0;
2476 virtual void benchmarkEnded( BenchmarkStats<>
const& stats ) = 0;
2477 virtual void benchmarkFailed( std::string
const& error ) = 0;
2478 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2480 virtual void pushScopedMessage(
MessageInfo const& message ) = 0;
2481 virtual void popScopedMessage(
MessageInfo const& message ) = 0;
2483 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder ) = 0;
2485 virtual void handleFatalErrorCondition(
StringRef message ) = 0;
2487 virtual void handleExpr
2491 virtual void handleMessage
2496 virtual void handleUnexpectedExceptionNotThrown
2499 virtual void handleUnexpectedInflightException
2501 std::string
const& message,
2503 virtual void handleIncomplete
2505 virtual void handleNonExpr
2510 virtual bool lastAssertionPassed() = 0;
2511 virtual void assertionPassed() = 0;
2514 virtual std::string getCurrentTestName()
const = 0;
2515 virtual const AssertionResult* getLastResult()
const = 0;
2516 virtual void exceptionEarlyReported() = 0;
2526 struct AssertionResultData;
2532 friend struct AssertionStats;
2533 friend class RunContext;
2542 explicit operator bool()
const;
2548 bool shouldDebugBreak =
false;
2549 bool shouldThrow =
false;
2555 bool m_completed =
false;
2565 if ( !m_completed ) {
2570 template<
typename T>
2578 void handleExceptionThrownAsExpected();
2579 void handleUnexpectedExceptionNotThrown();
2580 void handleExceptionNotThrownAsExpected();
2581 void handleThrowingCallSkipped();
2582 void handleUnexpectedInflightException();
2585 void setCompleted();
2588 auto allowThrows()
const -> bool;
2617 static unsigned int globalCount;
2622 template<
typename T>
2636 template<
typename T>
2657 std::vector<MessageInfo> m_messages;
2659 size_t m_captured = 0;
2664 void captureValue(
size_t index, std::string
const&
value );
2666 template<
typename T>
2671 template<
typename T,
typename... Ts>
2674 captureValues( index+1, values... );
2681 #if !defined(CATCH_CONFIG_DISABLE) 2683 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) 2684 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ 2686 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" 2689 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 2694 #define INTERNAL_CATCH_TRY 2695 #define INTERNAL_CATCH_CATCH( capturer ) 2697 #else // CATCH_CONFIG_FAST_COMPILE 2699 #define INTERNAL_CATCH_TRY try 2700 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } 2704 #define INTERNAL_CATCH_REACT( handler ) handler.complete(); 2707 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ 2709 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ 2710 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2711 INTERNAL_CATCH_TRY { \ 2712 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2713 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 2714 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ 2715 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 2716 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 2717 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2718 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) 2721 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ 2722 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2723 if( Catch::getResultCapture().lastAssertionPassed() ) 2726 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ 2727 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2728 if( !Catch::getResultCapture().lastAssertionPassed() ) 2731 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ 2733 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2735 static_cast<void>(__VA_ARGS__); \ 2736 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ 2739 catchAssertionHandler.handleUnexpectedInflightException(); \ 2741 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2745 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ 2747 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ 2748 if( catchAssertionHandler.allowThrows() ) \ 2750 static_cast<void>(__VA_ARGS__); \ 2751 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2754 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2757 catchAssertionHandler.handleThrowingCallSkipped(); \ 2758 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2762 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ 2764 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ 2765 if( catchAssertionHandler.allowThrows() ) \ 2767 static_cast<void>(expr); \ 2768 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2770 catch( exceptionType const& ) { \ 2771 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2774 catchAssertionHandler.handleUnexpectedInflightException(); \ 2777 catchAssertionHandler.handleThrowingCallSkipped(); \ 2778 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2782 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ 2784 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ 2785 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ 2786 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2790 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ 2791 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ 2792 varName.captureValues( 0, __VA_ARGS__ ) 2795 #define INTERNAL_CATCH_INFO( macroName, log ) \ 2796 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); 2799 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ 2800 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) 2804 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ 2806 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 2807 if( catchAssertionHandler.allowThrows() ) \ 2809 static_cast<void>(__VA_ARGS__); \ 2810 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2813 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ 2816 catchAssertionHandler.handleThrowingCallSkipped(); \ 2817 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2820 #endif // CATCH_CONFIG_DISABLE 2837 std::size_t total()
const;
2838 bool allPassed()
const;
2841 std::size_t passed = 0;
2842 std::size_t failed = 0;
2843 std::size_t failedButOk = 0;
2867 std::string
const& _name );
2872 std::string
const& _name,
2873 std::string
const& ) :
SectionInfo( _lineInfo, _name ) {}
2899 uint64_t m_nanoseconds = 0;
2902 auto getElapsedNanoseconds()
const -> uint64_t;
2903 auto getElapsedMicroseconds()
const -> uint64_t;
2904 auto getElapsedMilliseconds()
const ->
unsigned int;
2905 auto getElapsedSeconds()
const -> double;
2921 explicit operator bool()
const;
2928 bool m_sectionIncluded;
2934 #define INTERNAL_CATCH_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, __VA_ARGS__ ) ) \ 2938 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2940 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ 2941 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2942 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2943 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ 2944 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2957 struct ITestCaseRegistry;
2958 struct IExceptionTranslatorRegistry;
2959 struct IExceptionTranslator;
2960 struct IReporterRegistry;
2961 struct IReporterFactory;
2962 struct ITagAliasRegistry;
2963 struct IMutableEnumValuesRegistry;
2965 class StartupExceptionRegistry;
2972 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2974 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2977 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
2982 virtual void registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory ) = 0;
2984 virtual void registerTest(
TestCase const& testInfo ) = 0;
2986 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) = 0;
2987 virtual void registerStartupException() noexcept = 0;
2999 #if defined(CATCH_CONFIG_DISABLE) 3000 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ 3001 static std::string translatorName( signature ) 3004 #include <exception> 3016 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3026 template<
typename T>
3030 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3031 : m_translateFunction( translateFunction )
3034 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const override {
3035 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3040 std::rethrow_exception(std::current_exception());
3042 return (*it)->translate( it+1, itEnd );
3045 return m_translateFunction( ex );
3051 std::string(*m_translateFunction)( T& );
3055 template<
typename T>
3058 (
new ExceptionTranslator<T>( translateFunction ) );
3064 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ 3065 static std::string translatorName( signature ); \ 3066 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 3067 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 3068 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ 3069 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 3070 static std::string translatorName( signature ) 3072 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 3077 #include <type_traits> 3084 bool equalityComparisonImpl(
double other)
const;
3087 void setMargin(
double margin);
3090 void setEpsilon(
double epsilon);
3101 Approx approx( static_cast<double>(value) );
3102 approx.m_epsilon = m_epsilon;
3103 approx.m_margin = m_margin;
3104 approx.m_scale = m_scale;
3114 auto lhs_v =
static_cast<double>(lhs);
3115 return rhs.equalityComparisonImpl(lhs_v);
3135 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3140 return lhs.m_value <
static_cast<double>(rhs) || lhs == rhs;
3145 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3150 return lhs.m_value >
static_cast<double>(rhs) || lhs == rhs;
3155 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3156 setEpsilon(epsilonAsDouble);
3162 double marginAsDouble =
static_cast<double>(newMargin);
3163 setMargin(marginAsDouble);
3169 m_scale =
static_cast<double>(newScale);
3173 std::string toString()
const;
3183 namespace literals {
3204 bool startsWith( std::string
const& s, std::string
const& prefix );
3205 bool startsWith( std::string
const& s,
char prefix );
3206 bool endsWith( std::string
const& s, std::string
const& suffix );
3207 bool endsWith( std::string
const& s,
char suffix );
3208 bool contains( std::string
const& s, std::string
const& infix );
3210 std::string
toLower( std::string
const& s );
3212 std::string
trim( std::string
const&
str );
3218 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
3221 pluralise( std::size_t count, std::string
const& label );
3231 #ifndef CATCH_CONFIG_DISABLE_MATCHERS 3240 namespace Matchers {
3252 std::string toString()
const;
3256 virtual std::string describe()
const = 0;
3261 # pragma clang diagnostic push 3262 # pragma clang diagnostic ignored "-Wnon-virtual-dtor" 3265 template<
typename ObjectT>
3267 virtual bool match( ObjectT
const& arg )
const = 0;
3270 #if defined(__OBJC__) 3275 virtual bool match( NSString* arg )
const = 0;
3280 # pragma clang diagnostic pop 3283 template<
typename T>
3291 template<
typename ArgT>
3293 bool match( ArgT
const& arg )
const override {
3294 for(
auto matcher : m_matchers ) {
3295 if (!matcher->match(arg))
3301 std::string description;
3302 description.reserve( 4 + m_matchers.size()*32 );
3303 description +=
"( ";
3305 for(
auto matcher : m_matchers ) {
3309 description +=
" and ";
3310 description += matcher->toString();
3312 description +=
" )";
3318 copy.m_matchers.push_back( &other );
3324 template<
typename ArgT>
3327 bool match( ArgT
const& arg )
const override {
3328 for(
auto matcher : m_matchers ) {
3329 if (matcher->match(arg))
3335 std::string description;
3336 description.reserve( 4 + m_matchers.size()*32 );
3337 description +=
"( ";
3339 for(
auto matcher : m_matchers ) {
3343 description +=
" or ";
3344 description += matcher->toString();
3346 description +=
" )";
3352 copy.m_matchers.push_back( &other );
3359 template<
typename ArgT>
3364 bool match( ArgT
const& arg )
const override {
3365 return !m_underlyingMatcher.match( arg );
3369 return "not " + m_underlyingMatcher.toString();
3374 template<
typename T>
3378 template<
typename T>
3382 template<
typename T>
3391 using namespace Matchers;
3400 namespace Matchers {
3404 std::string m_message;
3411 bool match(std::exception
const& ex)
const override;
3413 std::string describe()
const override;
3427 namespace Matchers {
3429 namespace Floating {
3431 enum class FloatingPointKind : uint8_t;
3435 bool match(
double const& matchee)
const override;
3436 std::string describe()
const override;
3444 bool match(
double const& matchee)
const override;
3445 std::string describe()
const override;
3449 FloatingPointKind m_type;
3460 bool match(
double const& matchee)
const override;
3461 std::string describe()
const override;
3487 #include <functional> 3491 namespace Matchers {
3498 template <
typename T>
3500 std::function<bool(T const&)> m_predicate;
3501 std::string m_description;
3505 :m_predicate(
std::move(elem)),
3509 bool match( T
const& item )
const override {
3510 return m_predicate(item);
3514 return m_description;
3524 template<
typename T>
3538 namespace Matchers {
3540 namespace StdString {
3545 std::string adjustString( std::string
const& str )
const;
3546 std::string caseSensitivitySuffix()
const;
3554 std::string describe()
const override;
3562 bool match( std::string
const& source )
const override;
3566 bool match( std::string
const& source )
const override;
3570 bool match( std::string
const& source )
const override;
3574 bool match( std::string
const& source )
const override;
3579 bool match( std::string
const& matchee )
const override;
3580 std::string describe()
const override;
3583 std::string m_regex;
3604 #include <algorithm> 3607 namespace Matchers {
3610 template<
typename T,
typename Alloc>
3615 bool match(std::vector<T, Alloc>
const &v)
const override {
3616 for (
auto const& el : v) {
3617 if (el == m_comparator) {
3631 template<
typename T,
typename AllocComp,
typename AllocMatch>
3634 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3636 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3638 if (m_comparator.size() > v.size())
3640 for (
auto const& comparator : m_comparator) {
3641 auto present =
false;
3642 for (
const auto& el : v) {
3643 if (el == comparator) {
3661 template<
typename T,
typename AllocComp,
typename AllocMatch>
3664 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3666 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3671 if (m_comparator.size() != v.size())
3673 for (std::size_t i = 0; i < v.size(); ++i)
3674 if (m_comparator[i] != v[i])
3684 template<
typename T,
typename AllocComp,
typename AllocMatch>
3687 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3689 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3690 if (m_comparator.size() != v.size())
3692 for (std::size_t i = 0; i < v.size(); ++i)
3693 if (m_comparator[i] != approx(v[i]))
3707 approx.
margin(newMargin);
3712 approx.
scale(newScale);
3720 template<
typename T,
typename AllocComp,
typename AllocMatch>
3723 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3724 if (m_target.size() != vec.size()) {
3727 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3734 std::vector<T, AllocComp>
const& m_target;
3742 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3747 template<
typename T,
typename Alloc = std::allocator<T>>
3752 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3757 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3762 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3773 template<
typename ArgT,
typename MatcherT>
3782 m_matcher( matcher ),
3783 m_matcherString( matcherString )
3787 auto matcherAsString = m_matcher.toString();
3790 os << m_matcherString;
3792 os << matcherAsString;
3800 template<
typename ArgT,
typename MatcherT>
3808 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ 3810 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3811 INTERNAL_CATCH_TRY { \ 3812 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ 3813 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 3814 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3818 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ 3820 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3821 if( catchAssertionHandler.allowThrows() ) \ 3823 static_cast<void>(__VA_ARGS__ ); \ 3824 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 3826 catch( exceptionType const& ex ) { \ 3827 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ 3830 catchAssertionHandler.handleUnexpectedInflightException(); \ 3833 catchAssertionHandler.handleThrowingCallSkipped(); \ 3834 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3857 virtual bool next() = 0;
3865 virtual auto hasGenerator()
const ->
bool = 0;
3875 #include <exception> 3878 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3879 template <
typename Ex>
3884 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 3898 #define CATCH_MAKE_MSG(...) \ 3899 (Catch::ReusableStringStream() << __VA_ARGS__).str() 3901 #define CATCH_INTERNAL_ERROR(...) \ 3902 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) 3904 #define CATCH_ERROR(...) \ 3905 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3907 #define CATCH_RUNTIME_ERROR(...) \ 3908 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3910 #define CATCH_ENFORCE( condition, ... ) \ 3911 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) 3919 #include <exception> 3924 const char*
const m_msg =
"";
3931 const char* what()
const noexcept
override final;
3934 namespace Generators {
3938 template<
typename T,
typename... Args>
3940 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
3944 template<
typename T>
3952 virtual T
const&
get()
const = 0;
3956 template<
typename T>
3962 T
const&
get()
const override {
3970 template<
typename T>
3973 "FixedValuesGenerator does not support bools because of std::vector<bool>" 3974 "specialization, use SingleValue Generator instead.");
3975 std::vector<T> m_values;
3980 T
const&
get()
const override {
3981 return m_values[m_idx];
3985 return m_idx < m_values.size();
3989 template <
typename T>
3991 std::unique_ptr<IGenerator<T>> m_generator;
3994 m_generator(
std::move(generator))
3996 T
const&
get()
const {
3997 return m_generator->get();
4000 return m_generator->next();
4004 template <
typename T>
4008 template <
typename T>
4013 template<
typename T>
4015 std::vector<GeneratorWrapper<T>> m_generators;
4016 size_t m_current = 0;
4019 m_generators.emplace_back(std::move(generator));
4021 void populate(T&& val) {
4022 m_generators.emplace_back(
value(std::forward<T>(val)));
4024 template<
typename U>
4025 void populate(U&& val) {
4026 populate(T(std::forward<U>(val)));
4028 template<
typename U,
typename... Gs>
4029 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4030 populate(std::forward<U>(valueOrGenerator));
4031 populate(std::forward<Gs>(moreGenerators)...);
4035 template <
typename... Gs>
4037 m_generators.reserve(
sizeof...(Gs));
4038 populate(std::forward<Gs>(moreGenerators)...);
4041 T
const&
get()
const override {
4042 return m_generators[m_current].get();
4046 if (m_current >= m_generators.size()) {
4049 const bool current_status = m_generators[m_current].next();
4050 if (!current_status) {
4053 return m_current < m_generators.size();
4057 template<
typename... Ts>
4058 GeneratorWrapper<std::tuple<Ts...>>
table( std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples ) {
4059 return values<std::tuple<Ts...>>( tuples );
4063 template <
typename T>
4066 template<
typename T,
typename... Gs>
4068 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4070 template<
typename T>
4074 template<
typename T,
typename... Gs>
4076 return makeGenerators(
value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4078 template<
typename T,
typename U,
typename... Gs>
4080 return makeGenerators(
value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4085 template<
typename L>
4089 auto generate(
StringRef generatorName,
SourceLineInfo const& lineInfo, L
const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().
get()) {
4090 using UnderlyingType =
typename decltype(generatorExpression())::type;
4098 return generator.
get();
4104 #define GENERATE( ... ) \ 4105 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4106 CATCH_INTERNAL_LINEINFO, \ 4107 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4108 #define GENERATE_COPY( ... ) \ 4109 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4110 CATCH_INTERNAL_LINEINFO, \ 4111 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4112 #define GENERATE_REF( ... ) \ 4113 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4114 CATCH_INTERNAL_LINEINFO, \ 4115 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4121 namespace Generators {
4123 template <
typename T>
4126 size_t m_returned = 0;
4130 m_generator(
std::move(generator)),
4133 assert(target != 0 &&
"Empty generators are not allowed");
4135 T
const&
get()
const override {
4136 return m_generator.
get();
4140 if (m_returned >= m_target) {
4144 const auto success = m_generator.
next();
4148 m_returned = m_target;
4154 template <
typename T>
4156 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4159 template <
typename T,
typename Predicate>
4164 template <
typename P = Predicate>
4166 m_generator(
std::move(generator)),
4167 m_predicate(
std::forward<P>(pred))
4169 if (!m_predicate(m_generator.
get())) {
4172 auto has_initial_value = next();
4173 if (!has_initial_value) {
4179 T
const&
get()
const override {
4180 return m_generator.
get();
4184 bool success = m_generator.
next();
4188 while (!m_predicate(m_generator.
get()) && (success = m_generator.
next()) ==
true);
4193 template <
typename T,
typename Predicate>
4195 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4198 template <
typename T>
4201 "RepeatGenerator currently does not support bools" 4202 "because of std::vector<bool> specialization");
4204 mutable std::vector<T> m_returned;
4205 size_t m_target_repeats;
4206 size_t m_current_repeat = 0;
4207 size_t m_repeat_index = 0;
4210 m_generator(
std::move(generator)),
4211 m_target_repeats(repeats)
4213 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4216 T
const&
get()
const override {
4217 if (m_current_repeat == 0) {
4218 m_returned.push_back(m_generator.
get());
4219 return m_returned.back();
4221 return m_returned[m_repeat_index];
4231 if (m_current_repeat == 0) {
4232 const auto success = m_generator.
next();
4236 return m_current_repeat < m_target_repeats;
4241 if (m_repeat_index == m_returned.size()) {
4245 return m_current_repeat < m_target_repeats;
4249 template <
typename T>
4251 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4254 template <
typename T,
typename U,
typename Func>
4262 template <
typename F2 = Func>
4264 m_generator(
std::move(generator)),
4265 m_function(
std::forward<F2>(function)),
4266 m_cache(m_function(m_generator.get()))
4269 T
const&
get()
const override {
4273 const auto success = m_generator.
next();
4275 m_cache = m_function(m_generator.
get());
4281 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4284 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4288 template <
typename T,
typename U,
typename Func>
4291 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4295 template <
typename T>
4297 std::vector<T> m_chunk;
4298 size_t m_chunk_size;
4300 bool m_used_up =
false;
4303 m_chunk_size(size), m_generator(
std::move(generator))
4305 m_chunk.reserve(m_chunk_size);
4306 if (m_chunk_size != 0) {
4307 m_chunk.push_back(m_generator.
get());
4308 for (
size_t i = 1; i < m_chunk_size; ++i) {
4309 if (!m_generator.
next()) {
4312 m_chunk.push_back(m_generator.
get());
4316 std::vector<T>
const&
get()
const override {
4321 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4322 if (!m_generator.
next()) {
4325 m_chunk.push_back(m_generator.
get());
4331 template <
typename T>
4334 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4362 virtual IRunner* getRunner() = 0;
4363 virtual IConfigPtr const& getConfig()
const = 0;
4369 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4370 virtual void setRunner(
IRunner* runner ) = 0;
4371 virtual void setConfig(
IConfigPtr const& config ) = 0;
4377 static void createContext();
4382 if( !IMutableContext::currentContext )
4383 IMutableContext::createContext();
4385 return *IMutableContext::currentContext;
4407 template<
typename T>
4412 : nullableValue( new( storage ) T( _value ) )
4415 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4423 if( &_other !=
this ) {
4426 nullableValue =
new( storage ) T( *_other );
4432 nullableValue =
new( storage ) T( _value );
4438 nullableValue->~T();
4439 nullableValue =
nullptr;
4448 return nullableValue ? *nullableValue : defaultValue;
4451 bool some()
const {
return nullableValue !=
nullptr; }
4452 bool none()
const {
return nullableValue ==
nullptr; }
4454 bool operator !()
const {
return nullableValue ==
nullptr; }
4455 explicit operator bool()
const {
4461 alignas(
alignof(T))
char storage[
sizeof(T)];
4483 NoAssertions = 0x01,
4506 BeforeStartAndExit = BeforeStart | BeforeExit
4515 virtual bool allowThrows()
const = 0;
4516 virtual std::ostream& stream()
const = 0;
4517 virtual std::string name()
const = 0;
4518 virtual bool includeSuccessfulResults()
const = 0;
4519 virtual bool shouldDebugBreak()
const = 0;
4520 virtual bool warnAboutMissingAssertions()
const = 0;
4521 virtual bool warnAboutNoTests()
const = 0;
4522 virtual int abortAfter()
const = 0;
4523 virtual bool showInvisibles()
const = 0;
4525 virtual double minDuration()
const = 0;
4526 virtual TestSpec
const& testSpec()
const = 0;
4527 virtual bool hasTestFilters()
const = 0;
4528 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4530 virtual unsigned int rngSeed()
const = 0;
4532 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4533 virtual Verbosity verbosity()
const = 0;
4535 virtual bool benchmarkNoAnalysis()
const = 0;
4536 virtual int benchmarkSamples()
const = 0;
4537 virtual double benchmarkConfidenceInterval()
const = 0;
4538 virtual unsigned int benchmarkResamples()
const = 0;
4539 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4542 using IConfigPtr = std::shared_ptr<IConfig const>;
4558 using state_type = std::uint64_t;
4574 void discard(uint64_t skip);
4585 std::uint64_t m_state;
4590 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4599 namespace Generators {
4601 template <
typename Float>
4604 std::uniform_real_distribution<Float> m_dist;
4605 Float m_current_number;
4611 static_cast<void>(next());
4615 return m_current_number;
4618 m_current_number = m_dist(m_rng);
4623 template <
typename Integer>
4626 std::uniform_int_distribution<Integer> m_dist;
4633 static_cast<void>(next());
4637 return m_current_number;
4640 m_current_number = m_dist(m_rng);
4647 template <
typename T>
4652 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4656 template <
typename T>
4661 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4665 template <
typename T>
4677 m_positive(m_step > T(0))
4679 assert(m_current != m_end &&
"Range start and end cannot be equal");
4680 assert(m_step != T(0) &&
"Step size cannot be zero");
4681 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4688 T
const&
get()
const override {
4693 m_current += m_step;
4694 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4698 template <
typename T>
4704 template <
typename T>
4710 template <
typename T>
4713 "IteratorGenerator currently does not support bools" 4714 "because of std::vector<bool> specialization");
4716 std::vector<T> m_elems;
4717 size_t m_current = 0;
4719 template <
typename InputIterator,
typename InputSentinel>
4721 if (m_elems.empty()) {
4726 T
const&
get()
const override {
4727 return m_elems[m_current];
4732 return m_current != m_elems.size();
4736 template <
typename InputIterator,
4737 typename InputSentinel,
4738 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4743 template <
typename Container,
4744 typename ResultType =
typename Container::value_type>
4763 #pragma clang diagnostic push 4764 #pragma clang diagnostic ignored "-Wpadded" 4775 ShouldFail = 1 << 2,
4778 NonPortable = 1 << 5,
4783 std::string
const& _className,
4784 std::string
const& _description,
4785 std::vector<std::string>
const& _tags,
4788 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4790 bool isHidden()
const;
4791 bool throws()
const;
4792 bool okToFail()
const;
4793 bool expectedToFail()
const;
4795 std::string tagsAsString()
const;
4811 TestCase withName( std::string
const& _newName )
const;
4813 void invoke()
const;
4821 std::shared_ptr<ITestInvoker> test;
4825 std::string
const& className,
4831 #pragma clang diagnostic pop 4841 virtual bool aborting()
const = 0;
4850 #import <objc/runtime.h> 4875 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4877 virtual void invoke()
const {
4878 id obj = [[m_cls alloc] init];
4880 performOptionalSelector( obj,
@selector(setUp) );
4881 performOptionalSelector( obj, m_sel );
4882 performOptionalSelector( obj,
@selector(tearDown) );
4884 arcSafeRelease( obj );
4887 virtual ~OcMethod() {}
4895 inline std::string getAnnotation( Class cls,
4896 std::string
const& annotationName,
4897 std::string
const& testCaseName ) {
4898 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4899 SEL sel = NSSelectorFromString( selStr );
4900 arcSafeRelease( selStr );
4901 id value = performOptionalSelector( cls, sel );
4903 return [(NSString*)value UTF8String];
4908 inline std::size_t registerTestMethods() {
4909 std::size_t noTestMethods = 0;
4910 int noClasses = objc_getClassList(
nullptr, 0 );
4912 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4913 objc_getClassList( classes, noClasses );
4915 for(
int c = 0; c < noClasses; c++ ) {
4916 Class cls = classes[c];
4919 Method* methods = class_copyMethodList( cls, &count );
4920 for( u_int m = 0; m < count ; m++ ) {
4921 SEL selector = method_getName(methods[m]);
4922 std::string methodName = sel_getName(selector);
4923 if(
startsWith( methodName,
"Catch_TestCase_" ) ) {
4924 std::string testCaseName = methodName.substr( 15 );
4925 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4926 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4927 const char* className = class_getName( cls );
4936 return noTestMethods;
4939 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 4941 namespace Matchers {
4943 namespace NSStringMatchers {
4946 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4947 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4949 arcSafeRelease( m_substr );
4952 bool match( NSString*
str )
const override {
4956 NSString* CATCH_ARC_STRONG m_substr;
4959 struct Equals : StringHolder {
4960 Equals( NSString* substr ) : StringHolder( substr ){}
4962 bool match( NSString*
str )
const override {
4963 return (str != nil || m_substr == nil ) &&
4964 [str isEqualToString:m_substr];
4967 std::string describe()
const override {
4973 Contains( NSString* substr ) : StringHolder( substr ){}
4975 bool match( NSString*
str )
const override {
4976 return (str != nil || m_substr == nil ) &&
4977 [str rangeOfString:m_substr].location != NSNotFound;
4980 std::string describe()
const override {
4986 StartsWith( NSString* substr ) : StringHolder( substr ){}
4988 bool match( NSString*
str )
const override {
4989 return (str != nil || m_substr == nil ) &&
4990 [str rangeOfString:m_substr].location == 0;
4993 std::string describe()
const override {
4998 EndsWith( NSString* substr ) : StringHolder( substr ){}
5000 bool match( NSString*
str )
const override {
5001 return (str != nil || m_substr == nil ) &&
5002 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5005 std::string describe()
const override {
5027 using namespace Matchers;
5029 #endif // CATCH_CONFIG_DISABLE_MATCHERS 5034 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix 5035 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ 5036 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ 5040 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ 5044 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) 5046 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) 5052 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5064 #pragma clang diagnostic push 5065 #pragma clang diagnostic ignored "-Wpadded" 5071 #pragma clang diagnostic push 5072 #pragma clang diagnostic ignored "-Wpadded" 5079 class WildcardPattern {
5080 enum WildcardPosition {
5082 WildcardAtStart = 1,
5084 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5090 virtual ~WildcardPattern() =
default;
5091 virtual bool matches( std::string
const&
str )
const;
5094 std::string normaliseString( std::string
const& str )
const;
5096 WildcardPosition m_wildcard = NoWildcard;
5097 std::string m_pattern;
5113 explicit Pattern( std::string
const& name );
5115 virtual bool matches(
TestCaseInfo const& testCase )
const = 0;
5116 std::string
const& name()
const;
5118 std::string
const m_name;
5120 using PatternPtr = std::shared_ptr<Pattern>;
5122 class NamePattern :
public Pattern {
5124 explicit NamePattern( std::string
const& name, std::string
const& filterString );
5125 bool matches(
TestCaseInfo const& testCase )
const override;
5127 WildcardPattern m_wildcardPattern;
5130 class TagPattern :
public Pattern {
5132 explicit TagPattern( std::string
const& tag, std::string
const& filterString );
5133 bool matches(
TestCaseInfo const& testCase )
const override;
5138 class ExcludedPattern :
public Pattern {
5140 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5141 bool matches(
TestCaseInfo const& testCase )
const override;
5143 PatternPtr m_underlyingPattern;
5147 std::vector<PatternPtr> m_patterns;
5150 std::string name()
const;
5154 struct FilterMatch {
5156 std::vector<TestCase const*> tests;
5158 using Matches = std::vector<FilterMatch>;
5159 using vectorStrings = std::vector<std::string>;
5161 bool hasFilters()
const;
5163 Matches matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const;
5164 const vectorStrings & getInvalidArgs()
const;
5167 std::vector<Filter> m_filters;
5168 std::vector<std::string> m_invalidArgs;
5169 friend class TestSpecParser;
5174 #pragma clang diagnostic pop 5186 struct ITagAliasRegistry {
5187 virtual ~ITagAliasRegistry();
5189 virtual TagAlias
const* find( std::string
const& alias )
const = 0;
5190 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
5192 static ITagAliasRegistry
const&
get();
5200 class TestSpecParser {
5201 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5203 Mode lastMode = None;
5204 bool m_exclusion =
false;
5205 std::size_t m_pos = 0;
5206 std::size_t m_realPatternPos = 0;
5208 std::string m_substring;
5209 std::string m_patternName;
5210 std::vector<std::size_t> m_escapeChars;
5211 TestSpec::Filter m_currentFilter;
5212 TestSpec m_testSpec;
5213 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5216 TestSpecParser( ITagAliasRegistry
const& tagAliases );
5218 TestSpecParser&
parse( std::string
const& arg );
5219 TestSpec testSpec();
5222 bool visitChar(
char c );
5223 void startNewMode( Mode mode );
5224 bool processNoneChar(
char c );
5225 void processNameChar(
char c );
5226 bool processOtherChar(
char c );
5229 bool isControlChar(
char c )
const;
5230 void saveLastMode();
5231 void revertBackToLastMode();
5236 std::string preprocessPattern();
5238 void addNamePattern();
5240 void addTagPattern();
5242 inline void addCharToPattern(
char c) {
5249 TestSpec parseTestSpec( std::string
const& arg );
5254 #pragma clang diagnostic pop 5264 #ifndef CATCH_CONFIG_CONSOLE_WIDTH 5265 #define CATCH_CONFIG_CONSOLE_WIDTH 80 5273 bool listTests =
false;
5274 bool listTags =
false;
5275 bool listReporters =
false;
5276 bool listTestNamesOnly =
false;
5278 bool showSuccessfulTests =
false;
5279 bool shouldDebugBreak =
false;
5280 bool noThrow =
false;
5281 bool showHelp =
false;
5282 bool showInvisibles =
false;
5283 bool filenamesAsTags =
false;
5284 bool libIdentify =
false;
5286 int abortAfter = -1;
5289 bool benchmarkNoAnalysis =
false;
5290 unsigned int benchmarkSamples = 100;
5291 double benchmarkConfidenceInterval = 0.95;
5292 unsigned int benchmarkResamples = 100000;
5293 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5298 double minDuration = -1;
5303 std::string outputFilename;
5305 std::string processName;
5306 #ifndef CATCH_CONFIG_DEFAULT_REPORTER 5307 #define CATCH_CONFIG_DEFAULT_REPORTER "console" 5309 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5310 #undef CATCH_CONFIG_DEFAULT_REPORTER 5312 std::vector<std::string> testsOrTags;
5313 std::vector<std::string> sectionsToRun;
5320 Config( ConfigData
const& data );
5321 virtual ~
Config() =
default;
5323 std::string
const& getFilename()
const;
5325 bool listTests()
const;
5326 bool listTestNamesOnly()
const;
5327 bool listTags()
const;
5328 bool listReporters()
const;
5330 std::string getProcessName()
const;
5331 std::string
const& getReporterName()
const;
5333 std::vector<std::string>
const& getTestsOrTags()
const override;
5334 std::vector<std::string>
const& getSectionsToRun()
const override;
5336 TestSpec
const& testSpec()
const override;
5337 bool hasTestFilters()
const override;
5339 bool showHelp()
const;
5342 bool allowThrows()
const override;
5343 std::ostream& stream()
const override;
5344 std::string name()
const override;
5345 bool includeSuccessfulResults()
const override;
5346 bool warnAboutMissingAssertions()
const override;
5347 bool warnAboutNoTests()
const override;
5349 double minDuration()
const override;
5351 unsigned int rngSeed()
const override;
5353 bool shouldDebugBreak()
const override;
5354 int abortAfter()
const override;
5355 bool showInvisibles()
const override;
5357 bool benchmarkNoAnalysis()
const override;
5358 int benchmarkSamples()
const override;
5359 double benchmarkConfidenceInterval()
const override;
5360 unsigned int benchmarkResamples()
const override;
5361 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5368 std::unique_ptr<IStream const> m_stream;
5369 TestSpec m_testSpec;
5370 bool m_hasTestFilters =
false;
5382 struct AssertionResultData
5384 AssertionResultData() =
delete;
5388 std::string message;
5389 mutable std::string reconstructedExpression;
5393 std::string reconstructExpression()
const;
5396 class AssertionResult {
5398 AssertionResult() =
delete;
5399 AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data );
5402 bool succeeded()
const;
5404 bool hasExpression()
const;
5405 bool hasMessage()
const;
5406 std::string getExpression()
const;
5407 std::string getExpressionInMacro()
const;
5408 bool hasExpandedExpression()
const;
5409 std::string getExpandedExpression()
const;
5410 std::string getMessage()
const;
5416 AssertionResultData m_resultData;
5422 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5429 namespace Benchmark {
5430 template <
typename Duration>
5433 Duration lower_bound;
5434 Duration upper_bound;
5435 double confidence_interval;
5437 template <
typename Duration2>
5438 operator Estimate<Duration2>()
const {
5439 return { point, lower_bound, upper_bound, confidence_interval };
5451 namespace Benchmark {
5452 struct OutlierClassification {
5453 int samples_seen = 0;
5457 int high_severe = 0;
5460 return low_severe + low_mild + high_mild + high_severe;
5467 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5474 #include <algorithm> 5478 struct ReporterConfig {
5479 explicit ReporterConfig(
IConfigPtr const& _fullConfig );
5481 ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream );
5483 std::ostream& stream()
const;
5487 std::ostream* m_stream;
5491 struct ReporterPreferences {
5492 bool shouldRedirectStdOut =
false;
5493 bool shouldReportAllAssertions =
false;
5496 template<
typename T>
5497 struct LazyStat :
Option<T> {
5498 LazyStat& operator=( T
const& _value ) {
5510 struct TestRunInfo {
5511 TestRunInfo( std::string
const& _name );
5515 GroupInfo( std::string
const& _name,
5516 std::size_t _groupIndex,
5517 std::size_t _groupsCount );
5520 std::size_t groupIndex;
5521 std::size_t groupsCounts;
5524 struct AssertionStats {
5525 AssertionStats( AssertionResult
const& _assertionResult,
5526 std::vector<MessageInfo>
const& _infoMessages,
5529 AssertionStats( AssertionStats
const& ) =
default;
5530 AssertionStats( AssertionStats && ) =
default;
5531 AssertionStats& operator = ( AssertionStats
const& ) =
delete;
5532 AssertionStats& operator = ( AssertionStats && ) =
delete;
5533 virtual ~AssertionStats();
5535 AssertionResult assertionResult;
5536 std::vector<MessageInfo> infoMessages;
5540 struct SectionStats {
5542 Counts const& _assertions,
5543 double _durationInSeconds,
5544 bool _missingAssertions );
5545 SectionStats( SectionStats
const& ) =
default;
5546 SectionStats( SectionStats && ) =
default;
5547 SectionStats& operator = ( SectionStats
const& ) =
default;
5548 SectionStats& operator = ( SectionStats && ) =
default;
5549 virtual ~SectionStats();
5553 double durationInSeconds;
5554 bool missingAssertions;
5557 struct TestCaseStats {
5560 std::string
const& _stdOut,
5561 std::string
const& _stdErr,
5564 TestCaseStats( TestCaseStats
const& ) =
default;
5565 TestCaseStats( TestCaseStats && ) =
default;
5566 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5567 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5568 virtual ~TestCaseStats();
5577 struct TestGroupStats {
5578 TestGroupStats( GroupInfo
const& _groupInfo,
5581 TestGroupStats( GroupInfo
const& _groupInfo );
5583 TestGroupStats( TestGroupStats
const& ) =
default;
5584 TestGroupStats( TestGroupStats && ) =
default;
5585 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5586 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5587 virtual ~TestGroupStats();
5589 GroupInfo groupInfo;
5594 struct TestRunStats {
5595 TestRunStats( TestRunInfo
const& _runInfo,
5599 TestRunStats( TestRunStats
const& ) =
default;
5600 TestRunStats( TestRunStats && ) =
default;
5601 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5602 TestRunStats& operator = ( TestRunStats && ) =
default;
5603 virtual ~TestRunStats();
5605 TestRunInfo runInfo;
5610 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5611 struct BenchmarkInfo {
5613 double estimatedDuration;
5616 unsigned int resamples;
5617 double clockResolution;
5621 template <
class Duration>
5622 struct BenchmarkStats {
5625 std::vector<Duration> samples;
5626 Benchmark::Estimate<Duration> mean;
5627 Benchmark::Estimate<Duration> standardDeviation;
5628 Benchmark::OutlierClassification outliers;
5629 double outlierVariance;
5631 template <
typename Duration2>
5632 operator BenchmarkStats<Duration2>()
const {
5633 std::vector<Duration2> samples2;
5634 samples2.reserve(samples.size());
5635 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) {
return Duration2(d); });
5638 std::move(samples2),
5646 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5648 struct IStreamingReporter {
5649 virtual ~IStreamingReporter() =
default;
5655 virtual ReporterPreferences getPreferences()
const = 0;
5657 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5659 virtual void reportInvalidArguments(std::string
const&) {}
5661 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5662 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5664 virtual void testCaseStarting(
TestCaseInfo const& testInfo ) = 0;
5665 virtual void sectionStarting(
SectionInfo const& sectionInfo ) = 0;
5667 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5668 virtual void benchmarkPreparing( std::string
const& ) {}
5669 virtual void benchmarkStarting( BenchmarkInfo
const& ) {}
5670 virtual void benchmarkEnded( BenchmarkStats<>
const& ) {}
5671 virtual void benchmarkFailed( std::string
const& ) {}
5672 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5674 virtual void assertionStarting(
AssertionInfo const& assertionInfo ) = 0;
5677 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5679 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5680 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5681 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5682 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5684 virtual void skipTest(
TestCaseInfo const& testInfo ) = 0;
5687 virtual void fatalErrorEncountered(
StringRef name );
5689 virtual bool isMulti()
const;
5691 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5693 struct IReporterFactory {
5694 virtual ~IReporterFactory();
5695 virtual IStreamingReporterPtr create( ReporterConfig
const& config )
const = 0;
5696 virtual std::string getDescription()
const = 0;
5700 struct IReporterRegistry {
5701 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5702 using Listeners = std::vector<IReporterFactoryPtr>;
5704 virtual ~IReporterRegistry();
5705 virtual IStreamingReporterPtr create( std::string
const& name,
IConfigPtr const& config )
const = 0;
5706 virtual FactoryMap
const& getFactories()
const = 0;
5707 virtual Listeners
const& getListeners()
const = 0;
5713 #include <algorithm> 5722 void prepareExpandedExpression(AssertionResult& result);
5725 std::string getFormattedDuration(
double duration );
5728 bool shouldShowDuration(
IConfig const& config,
double duration );
5730 std::string serializeFilters( std::vector<std::string>
const& container );
5732 template<
typename DerivedT>
5733 struct StreamingReporterBase : IStreamingReporter {
5735 StreamingReporterBase( ReporterConfig
const& _config )
5736 : m_config( _config.fullConfig() ),
5737 stream( _config.stream() )
5739 m_reporterPrefs.shouldRedirectStdOut =
false;
5740 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5741 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5744 ReporterPreferences getPreferences()
const override {
5745 return m_reporterPrefs;
5748 static std::set<Verbosity> getSupportedVerbosities() {
5752 ~StreamingReporterBase()
override =
default;
5754 void noMatchingTestCases(std::string
const&)
override {}
5756 void reportInvalidArguments(std::string
const&)
override {}
5758 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5759 currentTestRunInfo = _testRunInfo;
5762 void testGroupStarting(GroupInfo
const& _groupInfo)
override {
5763 currentGroupInfo = _groupInfo;
5766 void testCaseStarting(
TestCaseInfo const& _testInfo)
override {
5767 currentTestCaseInfo = _testInfo;
5769 void sectionStarting(
SectionInfo const& _sectionInfo)
override {
5770 m_sectionStack.push_back(_sectionInfo);
5773 void sectionEnded(SectionStats
const& )
override {
5774 m_sectionStack.pop_back();
5776 void testCaseEnded(TestCaseStats
const& )
override {
5777 currentTestCaseInfo.reset();
5779 void testGroupEnded(TestGroupStats
const& )
override {
5780 currentGroupInfo.reset();
5782 void testRunEnded(TestRunStats
const& )
override {
5783 currentTestCaseInfo.reset();
5784 currentGroupInfo.reset();
5785 currentTestRunInfo.reset();
5794 std::ostream& stream;
5796 LazyStat<TestRunInfo> currentTestRunInfo;
5797 LazyStat<GroupInfo> currentGroupInfo;
5798 LazyStat<TestCaseInfo> currentTestCaseInfo;
5800 std::vector<SectionInfo> m_sectionStack;
5801 ReporterPreferences m_reporterPrefs;
5804 template<
typename DerivedT>
5805 struct CumulativeReporterBase : IStreamingReporter {
5806 template<
typename T,
typename ChildNodeT>
5808 explicit Node( T
const& _value ) :
value( _value ) {}
5811 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5813 ChildNodes children;
5815 struct SectionNode {
5816 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5817 virtual ~SectionNode() =
default;
5819 bool operator == (SectionNode
const& other)
const {
5820 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5822 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5827 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5828 using Assertions = std::vector<AssertionStats>;
5829 ChildSections childSections;
5830 Assertions assertions;
5835 struct BySectionInfo {
5836 BySectionInfo(
SectionInfo const& other ) : m_other( other ) {}
5837 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
5838 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5839 return ((node->stats.sectionInfo.name == m_other.name) &&
5840 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5842 void operator=(BySectionInfo
const&) =
delete;
5848 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5849 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5850 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5852 CumulativeReporterBase( ReporterConfig
const& _config )
5853 : m_config( _config.fullConfig() ),
5854 stream( _config.stream() )
5856 m_reporterPrefs.shouldRedirectStdOut =
false;
5857 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5858 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5860 ~CumulativeReporterBase()
override =
default;
5862 ReporterPreferences getPreferences()
const override {
5863 return m_reporterPrefs;
5866 static std::set<Verbosity> getSupportedVerbosities() {
5870 void testRunStarting( TestRunInfo
const& )
override {}
5871 void testGroupStarting( GroupInfo
const& )
override {}
5873 void testCaseStarting(
TestCaseInfo const& )
override {}
5875 void sectionStarting(
SectionInfo const& sectionInfo )
override {
5876 SectionStats incompleteStats( sectionInfo,
Counts(), 0,
false );
5877 std::shared_ptr<SectionNode> node;
5878 if( m_sectionStack.empty() ) {
5879 if( !m_rootSection )
5880 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5881 node = m_rootSection;
5884 SectionNode& parentNode = *m_sectionStack.back();
5886 std::find_if( parentNode.childSections.begin(),
5887 parentNode.childSections.end(),
5888 BySectionInfo( sectionInfo ) );
5889 if( it == parentNode.childSections.end() ) {
5890 node = std::make_shared<SectionNode>( incompleteStats );
5891 parentNode.childSections.push_back( node );
5896 m_sectionStack.push_back( node );
5897 m_deepestSection = std::move(node);
5902 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5903 assert(!m_sectionStack.empty());
5909 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5910 SectionNode& sectionNode = *m_sectionStack.back();
5911 sectionNode.assertions.push_back(assertionStats);
5914 void sectionEnded(SectionStats
const& sectionStats)
override {
5915 assert(!m_sectionStack.empty());
5916 SectionNode& node = *m_sectionStack.back();
5917 node.stats = sectionStats;
5918 m_sectionStack.pop_back();
5920 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5921 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5922 assert(m_sectionStack.size() == 0);
5923 node->children.push_back(m_rootSection);
5924 m_testCases.push_back(node);
5925 m_rootSection.reset();
5927 assert(m_deepestSection);
5928 m_deepestSection->stdOut = testCaseStats.stdOut;
5929 m_deepestSection->stdErr = testCaseStats.stdErr;
5931 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5932 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5933 node->children.swap(m_testCases);
5934 m_testGroups.push_back(node);
5936 void testRunEnded(TestRunStats
const& testRunStats)
override {
5937 auto node = std::make_shared<TestRunNode>(testRunStats);
5938 node->children.swap(m_testGroups);
5939 m_testRuns.push_back(node);
5940 testRunEndedCumulative();
5942 virtual void testRunEndedCumulative() = 0;
5947 std::ostream& stream;
5948 std::vector<AssertionStats> m_assertions;
5949 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5950 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5951 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5953 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5955 std::shared_ptr<SectionNode> m_rootSection;
5956 std::shared_ptr<SectionNode> m_deepestSection;
5957 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5958 ReporterPreferences m_reporterPrefs;
5962 char const* getLineOfChars() {
5963 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5966 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5971 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5972 TestEventListenerBase( ReporterConfig
const& _config );
5974 static std::set<Verbosity> getSupportedVerbosities();
5977 bool assertionEnded(AssertionStats
const&)
override;
6001 BrightRed = Bright | Red,
6002 BrightGreen = Bright | Green,
6003 LightGrey = Bright | Grey,
6004 BrightWhite = Bright | White,
6005 BrightYellow = Bright | Yellow,
6008 FileName = LightGrey,
6009 Warning = BrightYellow,
6010 ResultError = BrightRed,
6011 ResultSuccess = BrightGreen,
6012 ResultExpectedFailure = Warning,
6017 OriginalExpression = Cyan,
6018 ReconstructedExpression = BrightYellow,
6020 SecondaryText = LightGrey,
6025 Colour( Code _colourCode );
6026 Colour( Colour&& other ) noexcept;
6027 Colour& operator=( Colour&& other ) noexcept;
6031 static void use( Code _colourCode );
6034 bool m_moved =
false;
6037 std::ostream&
operator << ( std::ostream& os, Colour
const& );
6047 template<
typename T>
6048 class ReporterRegistrar {
6050 class ReporterFactory :
public IReporterFactory {
6052 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6053 return std::unique_ptr<T>(
new T( config ) );
6056 std::string getDescription()
const override {
6057 return T::getDescription();
6063 explicit ReporterRegistrar( std::string
const& name ) {
6068 template<
typename T>
6069 class ListenerRegistrar {
6071 class ListenerFactory :
public IReporterFactory {
6073 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6074 return std::unique_ptr<T>(
new T( config ) );
6076 std::string getDescription()
const override {
6077 return std::string();
6083 ListenerRegistrar() {
6089 #if !defined(CATCH_CONFIG_DISABLE) 6091 #define CATCH_REGISTER_REPORTER( name, reporterType ) \ 6092 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6093 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6094 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ 6095 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6097 #define CATCH_REGISTER_LISTENER( listenerType ) \ 6098 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6099 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6100 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ 6101 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6102 #else // CATCH_CONFIG_DISABLE 6104 #define CATCH_REGISTER_REPORTER(name, reporterType) 6105 #define CATCH_REGISTER_LISTENER(listenerType) 6107 #endif // CATCH_CONFIG_DISABLE 6115 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6117 using StreamingReporterBase::StreamingReporterBase;
6119 ~CompactReporter()
override;
6121 static std::string getDescription();
6123 void noMatchingTestCases(std::string
const& spec)
override;
6127 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6129 void sectionEnded(SectionStats
const& _sectionStats)
override;
6131 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6140 #if defined(_MSC_VER) 6141 #pragma warning(push) 6142 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 6149 struct SummaryColumn;
6152 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6153 std::unique_ptr<TablePrinter> m_tablePrinter;
6155 ConsoleReporter(ReporterConfig
const& config);
6156 ~ConsoleReporter()
override;
6157 static std::string getDescription();
6159 void noMatchingTestCases(std::string
const& spec)
override;
6161 void reportInvalidArguments(std::string
const&arg)
override;
6165 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6167 void sectionStarting(
SectionInfo const& _sectionInfo)
override;
6168 void sectionEnded(SectionStats
const& _sectionStats)
override;
6170 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6171 void benchmarkPreparing(std::string
const& name)
override;
6172 void benchmarkStarting(BenchmarkInfo
const& info)
override;
6173 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6174 void benchmarkFailed(std::string
const& error)
override;
6175 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6177 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6178 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6179 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6180 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6185 void lazyPrintWithoutClosingBenchmarkTable();
6186 void lazyPrintRunInfo();
6187 void lazyPrintGroupInfo();
6188 void printTestCaseAndSectionHeader();
6190 void printClosedHeader(std::string
const& _name);
6191 void printOpenHeader(std::string
const& _name);
6195 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6197 void printTotals(
Totals const& totals);
6198 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row);
6200 void printTotalsDivider(
Totals const& totals);
6201 void printSummaryDivider();
6202 void printTestFilters();
6205 bool m_headerPrinted =
false;
6210 #if defined(_MSC_VER) 6211 #pragma warning(pop) 6222 enum class XmlFormatting {
6228 XmlFormatting
operator | (XmlFormatting lhs, XmlFormatting rhs);
6229 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6233 enum ForWhat { ForTextNodes, ForAttributes };
6235 XmlEncode( std::string
const&
str, ForWhat forWhat = ForTextNodes );
6237 void encodeTo( std::ostream& os )
const;
6239 friend std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode );
6249 class ScopedElement {
6251 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6253 ScopedElement( ScopedElement&& other ) noexcept;
6254 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6258 ScopedElement& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6260 template<
typename T>
6261 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
6262 m_writer->writeAttribute( name, attribute );
6267 mutable XmlWriter* m_writer =
nullptr;
6268 XmlFormatting m_fmt;
6274 XmlWriter( XmlWriter
const& ) =
delete;
6275 XmlWriter& operator=( XmlWriter
const& ) =
delete;
6277 XmlWriter& startElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6279 ScopedElement scopedElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6281 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6283 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute );
6285 XmlWriter& writeAttribute( std::string
const& name,
bool attribute );
6287 template<
typename T>
6288 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
6291 return writeAttribute( name, rss.
str() );
6294 XmlWriter& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6296 XmlWriter& writeComment(std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6298 void writeStylesheetRef( std::string
const& url );
6300 XmlWriter& writeBlankLine();
6302 void ensureTagClosed();
6306 void applyFormatting(XmlFormatting fmt);
6308 void writeDeclaration();
6310 void newlineIfNecessary();
6312 bool m_tagIsOpen =
false;
6313 bool m_needsNewline =
false;
6314 std::vector<std::string> m_tags;
6315 std::string m_indent;
6324 class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6326 JunitReporter(ReporterConfig
const& _config);
6328 ~JunitReporter()
override;
6330 static std::string getDescription();
6332 void noMatchingTestCases(std::string
const& )
override;
6334 void testRunStarting(TestRunInfo
const& runInfo)
override;
6336 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6338 void testCaseStarting(
TestCaseInfo const& testCaseInfo)
override;
6339 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6341 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6343 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6345 void testRunEndedCumulative()
override;
6347 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6349 void writeTestCase(TestCaseNode
const& testCaseNode);
6351 void writeSection(std::string
const& className,
6352 std::string
const& rootName,
6353 SectionNode
const& sectionNode);
6355 void writeAssertions(SectionNode
const& sectionNode);
6356 void writeAssertion(AssertionStats
const& stats);
6360 std::string stdOutForSuite;
6361 std::string stdErrForSuite;
6362 unsigned int unexpectedExceptions = 0;
6363 bool m_okToFail =
false;
6372 class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6374 XmlReporter(ReporterConfig
const& _config);
6376 ~XmlReporter()
override;
6378 static std::string getDescription();
6380 virtual std::string getStylesheetRef()
const;
6386 void noMatchingTestCases(std::string
const& s)
override;
6388 void testRunStarting(TestRunInfo
const& testInfo)
override;
6390 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6392 void testCaseStarting(
TestCaseInfo const& testInfo)
override;
6394 void sectionStarting(
SectionInfo const& sectionInfo)
override;
6398 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6400 void sectionEnded(SectionStats
const& sectionStats)
override;
6402 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6404 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6406 void testRunEnded(TestRunStats
const& testRunStats)
override;
6408 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6409 void benchmarkPreparing(std::string
const& name)
override;
6410 void benchmarkStarting(BenchmarkInfo
const&)
override;
6411 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6412 void benchmarkFailed(std::string
const&)
override;
6413 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6416 Timer m_testCaseTimer;
6418 int m_sectionDepth = 0;
6428 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6453 namespace Benchmark {
6454 template <
typename Clock>
6455 using ClockDuration =
typename Clock::duration;
6456 template <
typename Clock>
6457 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6459 template <
typename Clock>
6462 using default_clock = std::chrono::steady_clock;
6464 template <
typename Clock>
6466 TimePoint<Clock> operator()()
const {
6467 return Clock::now();
6471 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6481 #if defined(_MSC_VER) 6486 namespace Benchmark {
6487 #if defined(__GNUC__) || defined(__clang__) 6488 template <
typename T>
6489 inline void keep_memory(T* p) {
6490 asm volatile(
"" : :
"g"(p) :
"memory");
6492 inline void keep_memory() {
6493 asm volatile(
"" : : :
"memory");
6497 inline void optimizer_barrier() { keep_memory(); }
6499 #elif defined(_MSC_VER) 6501 #pragma optimize("", off) 6502 template <
typename T>
6503 inline void keep_memory(T* p) {
6505 *
reinterpret_cast<char volatile*
>(p) = *reinterpret_cast<char const volatile*>(p);
6508 #pragma optimize("", on) 6511 inline void optimizer_barrier() {
6512 std::atomic_thread_fence(std::memory_order_seq_cst);
6518 template <
typename T>
6519 inline void deoptimize_value(T&& x) {
6523 template <
typename Fn,
typename... Args>
6524 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<!std::is_same<void, decltype(fn(args...))>
::value>::type {
6525 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6528 template <
typename Fn,
typename... Args>
6529 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<std::is_same<void, decltype(fn(args...))>
::value>::type {
6530 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6541 #include <type_traits> 6545 namespace Benchmark {
6547 template <
typename T>
6548 struct CompleteType {
using type = T; };
6550 struct CompleteType<void> {
struct type {}; };
6552 template <
typename T>
6553 using CompleteType_t =
typename CompleteType<T>::type;
6555 template <
typename Result>
6556 struct CompleteInvoker {
6557 template <
typename Fun,
typename... Args>
6558 static Result invoke(Fun&& fun, Args&&... args) {
6559 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6563 struct CompleteInvoker<void> {
6564 template <
typename Fun,
typename... Args>
6565 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6566 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6572 template <
typename Fun,
typename... Args>
6573 CompleteType_t<
FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6574 return CompleteInvoker<
FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6577 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6580 template <
typename Fun>
6581 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6583 return Detail::complete_invoke(std::forward<Fun>(fun));
6594 namespace Benchmark {
6596 struct ChronometerConcept {
6597 virtual void start() = 0;
6598 virtual void finish() = 0;
6599 virtual ~ChronometerConcept() =
default;
6601 template <
typename Clock>
6602 struct ChronometerModel final :
public ChronometerConcept {
6603 void start()
override { started = Clock::now(); }
6604 void finish()
override { finished = Clock::now(); }
6606 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6608 TimePoint<Clock> started;
6609 TimePoint<Clock> finished;
6613 struct Chronometer {
6615 template <
typename Fun>
6616 void measure(Fun&& fun) { measure(std::forward<Fun>(fun),
is_callable<Fun(
int)>()); }
6618 int runs()
const {
return k; }
6620 Chronometer(Detail::ChronometerConcept& meter,
int k)
6625 template <
typename Fun>
6626 void measure(Fun&& fun, std::false_type) {
6627 measure([&fun](
int) {
return fun(); }, std::true_type());
6630 template <
typename Fun>
6631 void measure(Fun&& fun, std::true_type) {
6632 Detail::optimizer_barrier();
6634 for (
int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6636 Detail::optimizer_barrier();
6639 Detail::ChronometerConcept* impl;
6652 namespace Benchmark {
6653 template <
typename Duration>
6654 struct EnvironmentEstimate {
6656 OutlierClassification outliers;
6658 template <
typename Duration2>
6659 operator EnvironmentEstimate<Duration2>()
const {
6660 return { mean, outliers };
6663 template <
typename Clock>
6664 struct Environment {
6665 using clock_type = Clock;
6666 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6667 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6684 #include <type_traits> 6689 namespace Benchmark {
6691 template <
typename T>
6692 using Decay =
typename std::decay<T>::type;
6693 template <
typename T,
typename U>
6695 : std::is_same<Decay<T>, Decay<U>> {};
6704 struct BenchmarkFunction {
6707 virtual void call(Chronometer meter)
const = 0;
6708 virtual callable* clone()
const = 0;
6709 virtual ~callable() =
default;
6711 template <
typename Fun>
6712 struct model :
public callable {
6713 model(Fun&& fun) : fun(std::move(fun)) {}
6714 model(Fun
const& fun) : fun(fun) {}
6716 model<Fun>* clone()
const override {
return new model<Fun>(*this); }
6718 void call(Chronometer meter)
const override {
6721 void call(Chronometer meter, std::true_type)
const {
6724 void call(Chronometer meter, std::false_type)
const {
6731 struct do_nothing {
void operator()()
const {} };
6733 template <
typename T>
6734 BenchmarkFunction(model<T>* c) : f(c) {}
6738 : f(
new model<do_nothing>{ {} }) {}
6740 template <
typename Fun,
6742 BenchmarkFunction(Fun&& fun)
6743 : f(
new model<
typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6745 BenchmarkFunction(BenchmarkFunction&& that)
6746 : f(std::move(that.f)) {}
6748 BenchmarkFunction(BenchmarkFunction
const& that)
6749 : f(that.f->clone()) {}
6751 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6752 f = std::move(that.f);
6756 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6757 f.reset(that.f->clone());
6761 void operator()(Chronometer meter)
const { f->call(meter); }
6764 std::unique_ptr<callable> f;
6776 #include <type_traits> 6780 namespace Benchmark {
6782 template <
typename Fun>
6784 void operator()(
int k)
const {
6785 for (
int i = 0; i < k; ++i) {
6791 template <
typename Fun>
6792 repeater<typename std::decay<Fun>::type>
repeat(Fun&& fun) {
6793 return { std::forward<Fun>(fun) };
6816 #include <type_traits> 6819 namespace Benchmark {
6820 template <
typename Duration,
typename Result>
6826 template <
typename Clock,
typename Func,
typename... Args>
6827 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<
FunctionReturnType<Func, Args...>>>;
6835 namespace Benchmark {
6837 template <
typename Clock,
typename Fun,
typename... Args>
6838 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6839 auto start = Clock::now();
6840 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6841 auto end = Clock::now();
6842 auto delta = end - start;
6843 return { delta, std::forward<decltype(r)>(r), 1 };
6851 #include <type_traits> 6854 namespace Benchmark {
6856 template <
typename Clock,
typename Fun>
6857 TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6858 return Detail::measure<Clock>(fun, iters);
6860 template <
typename Clock,
typename Fun>
6861 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6862 Detail::ChronometerModel<Clock> meter;
6863 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6865 return { meter.elapsed(), std::move(result), iters };
6868 template <
typename Clock,
typename Fun>
6871 struct optimized_away_error : std::exception {
6872 const char* what()
const noexcept
override {
6873 return "could not measure benchmark, maybe it was optimized away";
6877 template <
typename Clock,
typename Fun>
6878 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6880 while (iters < (1 << 30)) {
6883 if (Timing.elapsed >= how_long) {
6884 return { Timing.elapsed, std::move(Timing.result), iters };
6888 throw optimized_away_error{};
6895 #include <algorithm> 6898 namespace Benchmark {
6899 template <
typename Duration>
6900 struct ExecutionPlan {
6901 int iterations_per_sample;
6902 Duration estimated_duration;
6903 Detail::BenchmarkFunction benchmark;
6904 Duration warmup_time;
6905 int warmup_iterations;
6907 template <
typename Duration2>
6908 operator ExecutionPlan<Duration2>()
const {
6909 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6912 template <
typename Clock>
6913 std::vector<FloatDuration<Clock>> run(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
6915 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
Detail::repeat(now<Clock>{}));
6917 std::vector<FloatDuration<Clock>> times;
6919 std::generate_n(std::back_inserter(times), cfg.
benchmarkSamples(), [this, env] {
6920 Detail::ChronometerModel<Clock> model;
6921 this->benchmark(Chronometer(model, iterations_per_sample));
6922 auto sample_time = model.elapsed() - env.clock_cost.mean;
6923 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6924 return sample_time / iterations_per_sample;
6943 #include <algorithm> 6944 #include <functional> 6955 namespace Benchmark {
6957 using sample = std::vector<double>;
6959 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator
last);
6961 template <
typename Iterator>
6962 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6963 std::vector<double> copy(first, last);
6965 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6966 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6968 auto los = q1 - (iqr * 3.);
6969 auto lom = q1 - (iqr * 1.5);
6970 auto him = q3 + (iqr * 1.5);
6971 auto his = q3 + (iqr * 3.);
6973 OutlierClassification o;
6974 for (; first !=
last; ++first) {
6976 if (t < los) ++o.low_severe;
6977 else if (t < lom) ++o.low_mild;
6978 else if (t > his) ++o.high_severe;
6979 else if (t > him) ++o.high_mild;
6985 template <
typename Iterator>
6986 double mean(Iterator first, Iterator last) {
6987 auto count = last - first;
6988 double sum = std::accumulate(first, last, 0.);
6992 template <
typename URng,
typename Iterator,
typename Estimator>
6993 sample resample(URng&
rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
6994 auto n = last - first;
6995 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6998 out.reserve(resamples);
6999 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7000 std::vector<double> resampled;
7001 resampled.reserve(n);
7002 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
return first[dist(rng)]; });
7003 return estimator(resampled.begin(), resampled.end());
7005 std::sort(out.begin(), out.end());
7009 template <
typename Estimator,
typename Iterator>
7010 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7011 auto n = last - first;
7012 auto second = std::next(first);
7016 for (
auto it = first; it !=
last; ++it) {
7017 std::iter_swap(it, first);
7018 results.push_back(estimator(second, last));
7024 inline double normal_cdf(
double x) {
7025 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7028 double erfc_inv(
double x);
7030 double normal_quantile(
double p);
7032 template <
typename Iterator,
typename Estimator>
7033 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last, sample
const& resample, Estimator&& estimator) {
7034 auto n_samples = last - first;
7036 double point = estimator(first, last);
7038 if (n_samples == 1)
return { point, point, point, confidence_level };
7040 sample jack = jackknife(estimator, first, last);
7041 double jack_mean = mean(jack.begin(), jack.end());
7042 double sum_squares, sum_cubes;
7043 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> {
7044 auto d = jack_mean - x;
7047 return { sqcb.first + d2, sqcb.second + d3 };
7050 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7051 int n =
static_cast<int>(resample.size());
7052 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) {
return x < point; }) / (
double)n;
7054 if (prob_n == 0)
return { point, point, point, confidence_level };
7056 double bias = normal_quantile(prob_n);
7057 double z1 = normal_quantile((1. - confidence_level) / 2.);
7059 auto cumn = [n](
double x) ->
int {
7060 return std::lround(normal_cdf(x) * n); };
7061 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7062 double b1 = bias + z1;
7063 double b2 = bias - z1;
7066 auto lo = std::max(cumn(a1), 0);
7067 auto hi = std::min(cumn(a2), n - 1);
7069 return { point, resample[lo], resample[hi], confidence_level };
7072 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7074 struct bootstrap_analysis {
7075 Estimate<double> mean;
7076 Estimate<double> standard_deviation;
7077 double outlier_variance;
7080 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7086 #include <algorithm> 7093 namespace Benchmark {
7095 template <
typename Clock>
7096 std::vector<double> resolution(
int k) {
7097 std::vector<TimePoint<Clock>> times;
7098 times.reserve(k + 1);
7099 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7101 std::vector<double> deltas;
7103 std::transform(std::next(times.begin()), times.end(), times.begin(),
7104 std::back_inserter(deltas),
7105 [](TimePoint<Clock> a, TimePoint<Clock> b) {
return static_cast<double>((a - b).count()); });
7110 const auto warmup_iterations = 10000;
7111 const auto warmup_time = std::chrono::milliseconds(100);
7112 const auto minimum_ticks = 1000;
7113 const auto warmup_seed = 10000;
7114 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7115 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7116 const auto clock_cost_estimation_tick_limit = 100000;
7117 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7118 const auto clock_cost_estimation_iterations = 10000;
7120 template <
typename Clock>
7122 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7125 template <
typename Clock>
7126 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7127 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7130 FloatDuration<Clock>(mean(r.begin(), r.end())),
7131 classify_outliers(r.begin(), r.end()),
7134 template <
typename Clock>
7135 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7136 auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, 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 );
7618 using TestCaseTracking::ITracker;
7619 using TestCaseTracking::TrackerContext;
7620 using TestCaseTracking::SectionTracker;
7630 struct LeakDetector {
7642 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 7647 #if defined(CATCH_CONFIG_USE_ASYNC) 7652 double erf_inv(
double x) {
7656 w = -log((1.0 - x) * (1.0 + x));
7660 p = -3.6444120640178196996e-21;
7661 p = -1.685059138182016589e-19 + p * w;
7662 p = 1.2858480715256400167e-18 + p * w;
7663 p = 1.115787767802518096e-17 + p * w;
7664 p = -1.333171662854620906e-16 + p * w;
7665 p = 2.0972767875968561637e-17 + p * w;
7666 p = 6.6376381343583238325e-15 + p * w;
7667 p = -4.0545662729752068639e-14 + p * w;
7668 p = -8.1519341976054721522e-14 + p * w;
7669 p = 2.6335093153082322977e-12 + p * w;
7670 p = -1.2975133253453532498e-11 + p * w;
7671 p = -5.4154120542946279317e-11 + p * w;
7672 p = 1.051212273321532285e-09 + p * w;
7673 p = -4.1126339803469836976e-09 + p * w;
7674 p = -2.9070369957882005086e-08 + p * w;
7675 p = 4.2347877827932403518e-07 + p * w;
7676 p = -1.3654692000834678645e-06 + p * w;
7677 p = -1.3882523362786468719e-05 + p * w;
7678 p = 0.0001867342080340571352 + p * w;
7679 p = -0.00074070253416626697512 + p * w;
7680 p = -0.0060336708714301490533 + p * w;
7681 p = 0.24015818242558961693 + p * w;
7682 p = 1.6536545626831027356 + p * w;
7683 }
else if (w < 16.000000) {
7684 w = sqrt(w) - 3.250000;
7685 p = 2.2137376921775787049e-09;
7686 p = 9.0756561938885390979e-08 + p * w;
7687 p = -2.7517406297064545428e-07 + p * w;
7688 p = 1.8239629214389227755e-08 + p * w;
7689 p = 1.5027403968909827627e-06 + p * w;
7690 p = -4.013867526981545969e-06 + p * w;
7691 p = 2.9234449089955446044e-06 + p * w;
7692 p = 1.2475304481671778723e-05 + p * w;
7693 p = -4.7318229009055733981e-05 + p * w;
7694 p = 6.8284851459573175448e-05 + p * w;
7695 p = 2.4031110387097893999e-05 + p * w;
7696 p = -0.0003550375203628474796 + p * w;
7697 p = 0.00095328937973738049703 + p * w;
7698 p = -0.0016882755560235047313 + p * w;
7699 p = 0.0024914420961078508066 + p * w;
7700 p = -0.0037512085075692412107 + p * w;
7701 p = 0.005370914553590063617 + p * w;
7702 p = 1.0052589676941592334 + p * w;
7703 p = 3.0838856104922207635 + p * w;
7705 w = sqrt(w) - 5.000000;
7706 p = -2.7109920616438573243e-11;
7707 p = -2.5556418169965252055e-10 + p * w;
7708 p = 1.5076572693500548083e-09 + p * w;
7709 p = -3.7894654401267369937e-09 + p * w;
7710 p = 7.6157012080783393804e-09 + p * w;
7711 p = -1.4960026627149240478e-08 + p * w;
7712 p = 2.9147953450901080826e-08 + p * w;
7713 p = -6.7711997758452339498e-08 + p * w;
7714 p = 2.2900482228026654717e-07 + p * w;
7715 p = -9.9298272942317002539e-07 + p * w;
7716 p = 4.5260625972231537039e-06 + p * w;
7717 p = -1.9681778105531670567e-05 + p * w;
7718 p = 7.5995277030017761139e-05 + p * w;
7719 p = -0.00021503011930044477347 + p * w;
7720 p = -0.00013871931833623122026 + p * w;
7721 p = 1.0103004648645343977 + p * w;
7722 p = 4.8499064014085844221 + p * w;
7727 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator
last) {
7728 auto m = Catch::Benchmark::Detail::mean(first, last);
7729 double variance = std::accumulate(first, last, 0., [m](
double a,
double b) {
7730 double diff = b - m;
7731 return a + diff * diff;
7732 }) / (last - first);
7733 return std::sqrt(variance);
7739 namespace Benchmark {
7742 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator
last) {
7743 auto count = last - first;
7744 double idx = (count - 1) * k / static_cast<double>(q);
7745 int j =
static_cast<int>(idx);
7747 std::nth_element(first, first + j, last);
7749 if (g == 0)
return xj;
7751 auto xj1 = *std::min_element(first + (j + 1), last);
7752 return xj + g * (xj1 - xj);
7755 double erfc_inv(
double x) {
7756 return erf_inv(1.0 - x);
7759 double normal_quantile(
double p) {
7760 static const double ROOT_TWO = std::sqrt(2.0);
7762 double result = 0.0;
7763 assert(p >= 0 && p <= 1);
7764 if (p < 0 || p > 1) {
7768 result = -erfc_inv(2.0 * p);
7775 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7776 double sb = stddev.point;
7777 double mn = mean.point / n;
7778 double mg_min = mn / 2.;
7779 double sg = std::min(mg_min / 4., sb / std::sqrt(n));
7780 double sg2 = sg * sg;
7781 double sb2 = sb * sb;
7783 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7787 double k0 = -n * nd;
7788 double k1 = sb2 - n * sg2 + nd;
7789 double det = k1 * k1 - 4 * sg2 * k0;
7790 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7793 auto var_out = [n, sb2, sg2](
double c) {
7795 return (nc / n) * (sb2 - nc * sg2);
7798 return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) /
sb2;
7801 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7804 static std::random_device entropy;
7807 auto n =
static_cast<int>(last - first);
7809 auto mean = &Detail::mean<std::vector<double>::iterator>;
7810 auto stddev = &standard_deviation;
7812 #if defined(CATCH_CONFIG_USE_ASYNC) 7813 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7814 auto seed = entropy();
7815 return std::async(std::launch::async, [=] {
7816 std::mt19937
rng(seed);
7817 auto resampled = resample(rng, n_resamples, first, last, f);
7818 return bootstrap(confidence_level, first, last, resampled, f);
7822 auto mean_future = Estimate(mean);
7823 auto stddev_future = Estimate(stddev);
7825 auto mean_estimate = mean_future.get();
7826 auto stddev_estimate = stddev_future.get();
7828 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7829 auto seed = entropy();
7830 std::mt19937
rng(seed);
7831 auto resampled = resample(rng, n_resamples, first, last, f);
7832 return bootstrap(confidence_level, first, last, resampled, f);
7835 auto mean_estimate = Estimate(mean);
7836 auto stddev_estimate = Estimate(stddev);
7837 #endif // CATCH_USE_ASYNC 7839 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7841 return { mean_estimate, stddev_estimate, outlier_variance };
7847 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 7858 bool marginComparison(
double lhs,
double rhs,
double margin) {
7859 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7868 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7874 Approx Approx::custom() {
7880 temp.m_value = -temp.m_value;
7884 std::string Approx::toString()
const {
7890 bool Approx::equalityComparisonImpl(
const double other)
const {
7893 return marginComparison(m_value, other, m_margin)
7894 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7897 void Approx::setMargin(
double newMargin) {
7899 "Invalid Approx::margin: " << newMargin <<
'.' 7900 <<
" Approx::Margin has to be non-negative.");
7901 m_margin = newMargin;
7904 void Approx::setEpsilon(
double newEpsilon) {
7906 "Invalid Approx::epsilon: " << newEpsilon <<
'.' 7907 <<
" Approx::epsilon has to be in [0, 1]");
7908 m_epsilon = newEpsilon;
7913 namespace literals {
7933 bool isDebuggerActive();
7936 #ifdef CATCH_PLATFORM_MAC 7938 #if defined(__i386__) || defined(__x86_64__) 7939 #define CATCH_TRAP() __asm__("int $3\n" : : ) 7940 #elif defined(__aarch64__) 7941 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7944 #elif defined(CATCH_PLATFORM_IPHONE) 7947 #if defined(__i386__) || defined(__x86_64__) 7948 #define CATCH_TRAP() __asm__("int $3") 7949 #elif defined(__aarch64__) 7950 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7951 #elif defined(__arm__) && !defined(__thumb__) 7952 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") 7953 #elif defined(__arm__) && defined(__thumb__) 7954 #define CATCH_TRAP() __asm__(".inst 0xde01") 7957 #elif defined(CATCH_PLATFORM_LINUX) 7961 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) 7962 #define CATCH_TRAP() asm volatile ("int $3") 7963 #else // Fall back to the generic way. 7966 #define CATCH_TRAP() raise(SIGTRAP) 7968 #elif defined(_MSC_VER) 7969 #define CATCH_TRAP() __debugbreak() 7970 #elif defined(__MINGW32__) 7971 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7972 #define CATCH_TRAP() DebugBreak() 7975 #ifndef CATCH_BREAK_INTO_DEBUGGER 7977 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() 7979 #define CATCH_BREAK_INTO_DEBUGGER() []{}() 7991 #if defined(CATCH_PLATFORM_WINDOWS) 7993 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) 7994 # define CATCH_DEFINED_NOMINMAX 7997 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) 7998 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN 7999 # define WIN32_LEAN_AND_MEAN 8005 #include <windows.h> 8008 #ifdef CATCH_DEFINED_NOMINMAX 8011 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN 8012 # undef WIN32_LEAN_AND_MEAN 8015 #endif // defined(CATCH_PLATFORM_WINDOWS) 8018 #if defined( CATCH_CONFIG_WINDOWS_SEH ) 8022 struct FatalConditionHandler {
8024 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
8025 FatalConditionHandler();
8026 static void reset();
8027 ~FatalConditionHandler();
8031 static ULONG guaranteeSize;
8032 static PVOID exceptionHandlerHandle;
8037 #elif defined ( CATCH_CONFIG_POSIX_SIGNALS ) 8043 struct FatalConditionHandler {
8046 static struct sigaction oldSigActions[];
8047 static stack_t oldSigStack;
8048 static char altStackMem[];
8050 static void handleSignal(
int sig );
8052 FatalConditionHandler();
8053 ~FatalConditionHandler();
8054 static void reset();
8062 struct FatalConditionHandler {
8081 RunContext( RunContext
const& ) =
delete;
8082 RunContext& operator =( RunContext
const& ) =
delete;
8084 explicit RunContext(
IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8086 ~RunContext()
override;
8088 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8089 void testGroupEnded( std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8094 IStreamingReporter& reporter()
const;
8108 void handleUnexpectedExceptionNotThrown
8111 void handleUnexpectedInflightException
8113 std::string
const& message,
8115 void handleIncomplete
8122 bool sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions )
override;
8125 void sectionEndedEarly(
SectionEndInfo const& endInfo )
override;
8129 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 8130 void benchmarkPreparing( std::string
const& name )
override;
8131 void benchmarkStarting( BenchmarkInfo
const& info )
override;
8132 void benchmarkEnded( BenchmarkStats<>
const& stats )
override;
8133 void benchmarkFailed( std::string
const& error )
override;
8134 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 8136 void pushScopedMessage(
MessageInfo const& message )
override;
8137 void popScopedMessage(
MessageInfo const& message )
override;
8139 void emplaceUnscopedMessage(
MessageBuilder const& builder )
override;
8141 std::string getCurrentTestName()
const override;
8143 const AssertionResult* getLastResult()
const override;
8145 void exceptionEarlyReported()
override;
8147 void handleFatalErrorCondition(
StringRef message )
override;
8149 bool lastAssertionPassed()
override;
8151 void assertionPassed()
override;
8155 bool aborting()
const final;
8159 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8160 void invokeActiveTestCase();
8162 void resetAssertionInfo();
8163 bool testForMissingAssertions(
Counts& assertions );
8165 void assertionEnded( AssertionResult
const& result );
8176 void handleUnfinishedSections();
8178 TestRunInfo m_runInfo;
8180 TestCase const* m_activeTestCase =
nullptr;
8181 ITracker* m_testCaseTracker =
nullptr;
8186 IStreamingReporterPtr m_reporter;
8187 std::vector<MessageInfo> m_messages;
8188 std::vector<ScopedMessage> m_messageScopes;
8190 std::vector<SectionEndInfo> m_unfinishedSections;
8191 std::vector<ITracker*> m_activeSections;
8192 TrackerContext m_trackerContext;
8193 bool m_lastAssertionPassed =
false;
8194 bool m_shouldReportUnexpected =
true;
8195 bool m_includeSuccessfulResults;
8198 void seedRng(
IConfig const& config);
8213 : m_isNegated( isNegated )
8218 LazyExpression::operator bool()
const {
8219 return m_transientExpression !=
nullptr;
8223 if( lazyExpr.m_isNegated )
8228 os <<
"(" << *lazyExpr.m_transientExpression <<
")";
8230 os << *lazyExpr.m_transientExpression;
8233 os <<
"{** error - unchecked empty expression requested **}";
8243 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8248 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8251 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8260 if( m_reaction.shouldDebugBreak ) {
8266 CATCH_BREAK_INTO_DEBUGGER();
8268 if (m_reaction.shouldThrow) {
8269 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 8272 CATCH_ERROR(
"Test failure requires aborting test!" );
8285 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8288 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8292 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8296 m_resultCapture.handleNonExpr(m_assertionInfo,
ResultWas::Ok, m_reaction);
8311 lazyExpression(_lazyExpression),
8312 resultType(_resultType) {}
8314 std::string AssertionResultData::reconstructExpression()
const {
8316 if( reconstructedExpression.empty() ) {
8317 if( lazyExpression ) {
8319 rss << lazyExpression;
8320 reconstructedExpression = rss.
str();
8323 return reconstructedExpression;
8326 AssertionResult::AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data )
8328 m_resultData( data )
8332 bool AssertionResult::succeeded()
const {
8342 return m_resultData.resultType;
8345 bool AssertionResult::hasExpression()
const {
8346 return !m_info.capturedExpression.empty();
8349 bool AssertionResult::hasMessage()
const {
8350 return !m_resultData.message.empty();
8353 std::string AssertionResult::getExpression()
const {
8355 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8359 expr += m_info.capturedExpression;
8366 std::string AssertionResult::getExpressionInMacro()
const {
8368 if( m_info.macroName.empty() )
8369 expr = static_cast<std::string>(m_info.capturedExpression);
8371 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8372 expr += m_info.macroName;
8374 expr += m_info.capturedExpression;
8380 bool AssertionResult::hasExpandedExpression()
const {
8381 return hasExpression() && getExpandedExpression() != getExpression();
8384 std::string AssertionResult::getExpandedExpression()
const {
8385 std::string expr = m_resultData.reconstructExpression();
8391 std::string AssertionResult::getMessage()
const {
8392 return m_resultData.message;
8395 return m_info.lineInfo;
8398 StringRef AssertionResult::getTestMacroName()
const {
8399 return m_info.macroName;
8428 #ifdef CLARA_CONFIG_CONSOLE_WIDTH 8429 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8430 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8432 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 8435 #pragma clang diagnostic push 8436 #pragma clang diagnostic ignored "-Wweak-vtables" 8437 #pragma clang diagnostic ignored "-Wexit-time-destructors" 8438 #pragma clang diagnostic ignored "-Wshadow" 8452 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8453 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 8456 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8457 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8460 #ifndef CLARA_CONFIG_OPTIONAL_TYPE 8461 #ifdef __has_include 8462 #if __has_include(<optional>) && __cplusplus >= 201703L 8464 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional 8486 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8487 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 8492 namespace TextFlow {
8494 inline auto isWhitespace(
char c) ->
bool {
8495 static std::string chars =
" \t\n\r";
8496 return chars.find(c) != std::string::npos;
8498 inline auto isBreakableBefore(
char c) ->
bool {
8499 static std::string chars =
"[({<|";
8500 return chars.find(c) != std::string::npos;
8502 inline auto isBreakableAfter(
char c) ->
bool {
8503 static std::string chars =
"])}>.,:;*+-=&/\\";
8504 return chars.find(c) != std::string::npos;
8510 std::vector<std::string> m_strings;
8511 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8512 size_t m_indent = 0;
8513 size_t m_initialIndent = std::string::npos;
8519 Column
const& m_column;
8520 size_t m_stringIndex = 0;
8525 bool m_suffix =
false;
8527 iterator(Column
const& column,
size_t stringIndex)
8529 m_stringIndex(stringIndex) {}
8531 auto line()
const -> std::string
const& {
return m_column.m_strings[m_stringIndex]; }
8533 auto isBoundary(
size_t at)
const ->
bool {
8535 assert(at <= line().size());
8537 return at == line().size() ||
8538 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8539 isBreakableBefore(line()[at]) ||
8540 isBreakableAfter(line()[at - 1]);
8544 assert(m_stringIndex < m_column.m_strings.size());
8547 auto width = m_column.m_width - indent();
8549 if (line()[m_pos] ==
'\n') {
8552 while (m_end < line().size() && line()[m_end] !=
'\n')
8555 if (m_end < m_pos + width) {
8556 m_len = m_end - m_pos;
8559 while (len > 0 && !isBoundary(m_pos + len))
8561 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8573 auto indent()
const ->
size_t {
8574 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8575 return initial == std::string::npos ? m_column.m_indent : initial;
8578 auto addIndentAndSuffix(std::string
const &plain)
const -> std::string {
8579 return std::string(indent(),
' ') + (m_suffix ? plain +
"-" : plain);
8583 using difference_type = std::ptrdiff_t;
8584 using value_type = std::string;
8585 using pointer = value_type * ;
8586 using reference = value_type & ;
8587 using iterator_category = std::forward_iterator_tag;
8589 explicit iterator(Column
const& column) : m_column(column) {
8590 assert(m_column.m_width > m_column.m_indent);
8591 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8597 auto operator *()
const -> std::string {
8598 assert(m_stringIndex < m_column.m_strings.size());
8599 assert(m_pos <= m_end);
8600 return addIndentAndSuffix(line().substr(m_pos, m_len));
8603 auto operator ++() -> iterator& {
8605 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8608 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8611 if (m_pos == line().size()) {
8615 if (m_stringIndex < m_column.m_strings.size())
8619 auto operator ++(
int) -> iterator {
8620 iterator prev(*
this);
8625 auto operator ==(iterator
const& other)
const ->
bool {
8627 m_pos == other.m_pos &&
8628 m_stringIndex == other.m_stringIndex &&
8629 &m_column == &other.m_column;
8631 auto operator !=(iterator
const& other)
const ->
bool {
8635 using const_iterator = iterator;
8637 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8639 auto width(
size_t newWidth) -> Column& {
8640 assert(newWidth > 0);
8644 auto indent(
size_t newIndent) -> Column& {
8645 m_indent = newIndent;
8648 auto initialIndent(
size_t newIndent) -> Column& {
8649 m_initialIndent = newIndent;
8653 auto width()
const ->
size_t {
return m_width; }
8654 auto begin()
const -> iterator {
return iterator(*
this); }
8655 auto end()
const -> iterator {
return { *
this, m_strings.size() }; }
8657 inline friend std::ostream&
operator << (std::ostream& os, Column
const& col) {
8659 for (
auto line : col) {
8669 auto operator + (Column
const& other)->Columns;
8671 auto toString()
const -> std::string {
8672 std::ostringstream oss;
8678 class Spacer :
public Column {
8681 explicit Spacer(
size_t spaceWidth) : Column(
"") {
8687 std::vector<Column> m_columns;
8695 std::vector<Column>
const& m_columns;
8696 std::vector<Column::iterator> m_iterators;
8697 size_t m_activeIterators;
8699 iterator(Columns
const& columns, EndTag)
8700 : m_columns(columns.m_columns),
8701 m_activeIterators(0) {
8702 m_iterators.reserve(m_columns.size());
8704 for (
auto const& col : m_columns)
8705 m_iterators.push_back(col.end());
8709 using difference_type = std::ptrdiff_t;
8710 using value_type = std::string;
8711 using pointer = value_type * ;
8712 using reference = value_type & ;
8713 using iterator_category = std::forward_iterator_tag;
8715 explicit iterator(Columns
const& columns)
8716 : m_columns(columns.m_columns),
8717 m_activeIterators(m_columns.size()) {
8718 m_iterators.reserve(m_columns.size());
8720 for (
auto const& col : m_columns)
8721 m_iterators.push_back(col.begin());
8724 auto operator ==(iterator
const& other)
const ->
bool {
8725 return m_iterators == other.m_iterators;
8727 auto operator !=(iterator
const& other)
const ->
bool {
8728 return m_iterators != other.m_iterators;
8730 auto operator *()
const -> std::string {
8731 std::string row, padding;
8733 for (
size_t i = 0; i < m_columns.size(); ++i) {
8734 auto width = m_columns[i].width();
8735 if (m_iterators[i] != m_columns[i].end()) {
8736 std::string col = *m_iterators[i];
8737 row += padding + col;
8738 if (col.size() < width)
8739 padding = std::string(width - col.size(),
' ');
8743 padding += std::string(width,
' ');
8748 auto operator ++() -> iterator& {
8749 for (
size_t i = 0; i < m_columns.size(); ++i) {
8750 if (m_iterators[i] != m_columns[i].end())
8755 auto operator ++(
int) -> iterator {
8756 iterator prev(*
this);
8761 using const_iterator = iterator;
8763 auto begin()
const -> iterator {
return iterator(*
this); }
8764 auto end()
const -> iterator {
return { *
this, iterator::EndTag() }; }
8766 auto operator += (Column
const& col) -> Columns& {
8767 m_columns.push_back(col);
8770 auto operator + (Column
const& col) -> Columns {
8771 Columns combined = *
this;
8776 inline friend std::ostream&
operator << (std::ostream& os, Columns
const& cols) {
8779 for (
auto line : cols) {
8789 auto toString()
const -> std::string {
8790 std::ostringstream oss;
8814 #include <algorithm> 8816 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) 8817 #define CATCH_PLATFORM_WINDOWS 8820 namespace Catch {
namespace clara {
8824 template<
typename L>
8825 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8827 template<
typename ClassT,
typename ReturnT,
typename... Args>
8828 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8829 static const bool isValid =
false;
8832 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8833 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8834 static const bool isValid =
true;
8835 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8836 using ReturnType = ReturnT;
8844 std::string m_exeName;
8845 std::vector<std::string> m_args;
8848 Args(
int argc,
char const*
const* argv )
8849 : m_exeName(argv[0]),
8850 m_args(argv + 1, argv + argc) {}
8852 Args( std::initializer_list<std::string> args )
8853 : m_exeName( *args.begin() ),
8854 m_args( args.begin()+1, args.end() )
8857 auto exeName()
const -> std::string {
8864 enum class TokenType {
8872 inline auto isOptPrefix(
char c ) ->
bool {
8874 #ifdef CATCH_PLATFORM_WINDOWS 8882 using Iterator = std::vector<std::string>::const_iterator;
8885 std::vector<Token> m_tokenBuffer;
8888 m_tokenBuffer.resize( 0 );
8891 while( it != itEnd && it->empty() )
8895 auto const &next = *it;
8896 if( isOptPrefix( next[0] ) ) {
8897 auto delimiterPos = next.find_first_of(
" :=" );
8898 if( delimiterPos != std::string::npos ) {
8899 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8900 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8902 if( next[1] !=
'-' && next.size() > 2 ) {
8903 std::string opt =
"- ";
8904 for(
size_t i = 1; i < next.size(); ++i ) {
8906 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8909 m_tokenBuffer.push_back( { TokenType::Option, next } );
8913 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8919 explicit TokenStream( Args
const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8921 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8925 explicit operator bool()
const {
8926 return !m_tokenBuffer.empty() || it != itEnd;
8929 auto count()
const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8931 auto operator*()
const ->
Token {
8932 assert( !m_tokenBuffer.empty() );
8933 return m_tokenBuffer.front();
8936 auto operator->()
const ->
Token const * {
8937 assert( !m_tokenBuffer.empty() );
8938 return &m_tokenBuffer.front();
8941 auto operator++() -> TokenStream & {
8942 if( m_tokenBuffer.size() >= 2 ) {
8943 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8956 Ok, LogicError, RuntimeError
8960 ResultBase( Type type ) : m_type( type ) {}
8961 virtual ~ResultBase() =
default;
8963 virtual void enforceOk()
const = 0;
8968 template<
typename T>
8969 class ResultValueBase :
public ResultBase {
8971 auto value()
const -> T
const & {
8977 ResultValueBase( Type type ) : ResultBase( type ) {}
8979 ResultValueBase( ResultValueBase
const &other ) : ResultBase( other ) {
8980 if( m_type == ResultBase::Ok )
8981 new( &m_value ) T( other.m_value );
8984 ResultValueBase( Type, T
const &
value ) : ResultBase( Ok ) {
8985 new( &m_value ) T( value );
8988 auto operator=( ResultValueBase
const &other ) -> ResultValueBase & {
8989 if( m_type == ResultBase::Ok )
8991 ResultBase::operator=(other);
8992 if( m_type == ResultBase::Ok )
8993 new( &m_value ) T( other.m_value );
8997 ~ResultValueBase()
override {
9008 class ResultValueBase<void> :
public ResultBase {
9010 using ResultBase::ResultBase;
9013 template<
typename T =
void>
9014 class BasicResult :
public ResultValueBase<T> {
9016 template<
typename U>
9017 explicit BasicResult( BasicResult<U>
const &other )
9018 : ResultValueBase<T>( other.type() ),
9019 m_errorMessage( other.errorMessage() )
9021 assert( type() != ResultBase::Ok );
9024 template<
typename U>
9025 static auto ok( U
const &
value ) -> BasicResult {
return { ResultBase::Ok, value }; }
9026 static auto ok() -> BasicResult {
return { ResultBase::Ok }; }
9027 static auto logicError( std::string
const &message ) -> BasicResult {
return { ResultBase::LogicError, message }; }
9028 static auto runtimeError( std::string
const &message ) -> BasicResult {
return { ResultBase::RuntimeError, message }; }
9030 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9031 auto type()
const -> ResultBase::Type {
return m_type; }
9032 auto errorMessage()
const -> std::string {
return m_errorMessage; }
9035 void enforceOk()
const override {
9039 assert( m_type != ResultBase::LogicError );
9040 assert( m_type != ResultBase::RuntimeError );
9041 if( m_type != ResultBase::Ok )
9045 std::string m_errorMessage;
9047 BasicResult( ResultBase::Type type, std::string
const &message )
9048 : ResultValueBase<T>(type),
9049 m_errorMessage(message)
9051 assert( m_type != ResultBase::Ok );
9054 using ResultValueBase<T>::ResultValueBase;
9055 using ResultBase::m_type;
9058 enum class ParseResultType {
9059 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9065 ParseState( ParseResultType type, TokenStream
const &remainingTokens )
9067 m_remainingTokens( remainingTokens )
9070 auto type()
const -> ParseResultType {
return m_type; }
9071 auto remainingTokens()
const -> TokenStream {
return m_remainingTokens; }
9074 ParseResultType m_type;
9075 TokenStream m_remainingTokens;
9078 using Result = BasicResult<void>;
9079 using ParserResult = BasicResult<ParseResultType>;
9080 using InternalParseResult = BasicResult<ParseState>;
9082 struct HelpColumns {
9087 template<
typename T>
9088 inline auto convertInto( std::string
const &source, T& target ) -> ParserResult {
9089 std::stringstream ss;
9093 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9095 return ParserResult::ok( ParseResultType::Matched );
9097 inline auto convertInto( std::string
const &source, std::string& target ) -> ParserResult {
9099 return ParserResult::ok( ParseResultType::Matched );
9101 inline auto convertInto( std::string
const &source,
bool &target ) -> ParserResult {
9102 std::string srcLC = source;
9103 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
unsigned char c ) {
return static_cast<char>( std::tolower(c) ); } );
9104 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9106 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9109 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9110 return ParserResult::ok( ParseResultType::Matched );
9112 #ifdef CLARA_CONFIG_OPTIONAL_TYPE 9113 template<
typename T>
9114 inline auto convertInto( std::string
const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9116 auto result = convertInto( source, temp );
9118 target = std::move(temp);
9121 #endif // CLARA_CONFIG_OPTIONAL_TYPE 9132 virtual ~BoundRef() =
default;
9133 virtual auto isContainer()
const ->
bool {
return false; }
9134 virtual auto isFlag()
const ->
bool {
return false; }
9136 struct BoundValueRefBase : BoundRef {
9137 virtual auto setValue( std::string
const &arg ) -> ParserResult = 0;
9139 struct BoundFlagRefBase : BoundRef {
9140 virtual auto setFlag(
bool flag ) -> ParserResult = 0;
9141 virtual auto isFlag()
const ->
bool {
return true; }
9144 template<
typename T>
9145 struct BoundValueRef : BoundValueRefBase {
9148 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9150 auto setValue( std::string
const &arg ) -> ParserResult
override {
9151 return convertInto( arg, m_ref );
9155 template<
typename T>
9156 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9157 std::vector<T> &m_ref;
9159 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9161 auto isContainer()
const ->
bool override {
return true; }
9163 auto setValue( std::string
const &arg ) -> ParserResult
override {
9165 auto result = convertInto( arg, temp );
9167 m_ref.push_back( temp );
9172 struct BoundFlagRef : BoundFlagRefBase {
9175 explicit BoundFlagRef(
bool &ref ) : m_ref( ref ) {}
9177 auto setFlag(
bool flag ) -> ParserResult
override {
9179 return ParserResult::ok( ParseResultType::Matched );
9183 template<
typename ReturnType>
9184 struct LambdaInvoker {
9187 template<
typename L,
typename ArgType>
9188 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9189 return lambda( arg );
9194 struct LambdaInvoker<void> {
9195 template<
typename L,
typename ArgType>
9196 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9198 return ParserResult::ok( ParseResultType::Matched );
9202 template<
typename ArgType,
typename L>
9203 inline auto invokeLambda( L
const &lambda, std::string
const &arg ) -> ParserResult {
9205 auto result = convertInto( arg, temp );
9208 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9211 template<
typename L>
9212 struct BoundLambda : BoundValueRefBase {
9215 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9216 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9218 auto setValue( std::string
const &arg ) -> ParserResult
override {
9219 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9223 template<
typename L>
9224 struct BoundFlagLambda : BoundFlagRefBase {
9227 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9228 static_assert( std::is_same<
typename UnaryLambdaTraits<L>::ArgType,
bool>::
value,
"flags must be boolean" );
9230 explicit BoundFlagLambda( L
const &lambda ) : m_lambda( lambda ) {}
9232 auto setFlag(
bool flag ) -> ParserResult
override {
9233 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9237 enum class Optionality { Optional, Required };
9243 virtual ~ParserBase() =
default;
9244 virtual auto validate()
const -> Result {
return Result::ok(); }
9245 virtual auto parse( std::string
const& exeName, TokenStream
const &tokens)
const -> InternalParseResult = 0;
9246 virtual auto cardinality()
const ->
size_t {
return 1; }
9248 auto parse( Args
const &args )
const -> InternalParseResult {
9249 return parse( args.exeName(), TokenStream( args ) );
9253 template<
typename DerivedT>
9254 class ComposableParserImpl :
public ParserBase {
9256 template<
typename T>
9257 auto operator|( T
const &other )
const -> Parser;
9259 template<
typename T>
9260 auto operator+( T
const &other )
const -> Parser;
9264 template<
typename DerivedT>
9265 class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9267 Optionality m_optionality = Optionality::Optional;
9268 std::shared_ptr<BoundRef> m_ref;
9270 std::string m_description;
9272 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &ref ) : m_ref( ref ) {}
9275 template<
typename T>
9276 ParserRefImpl( T &ref, std::string
const &hint )
9277 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9281 template<
typename LambdaT>
9282 ParserRefImpl( LambdaT
const &ref, std::string
const &hint )
9283 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9287 auto operator()( std::string
const &description ) -> DerivedT & {
9288 m_description = description;
9289 return static_cast<DerivedT &
>( *this );
9292 auto optional() -> DerivedT & {
9293 m_optionality = Optionality::Optional;
9294 return static_cast<DerivedT &
>( *this );
9297 auto required() -> DerivedT & {
9298 m_optionality = Optionality::Required;
9299 return static_cast<DerivedT &
>( *this );
9302 auto isOptional()
const ->
bool {
9303 return m_optionality == Optionality::Optional;
9306 auto cardinality()
const ->
size_t override {
9307 if( m_ref->isContainer() )
9313 auto hint()
const -> std::string {
return m_hint; }
9316 class ExeName :
public ComposableParserImpl<ExeName> {
9317 std::shared_ptr<std::string> m_name;
9318 std::shared_ptr<BoundValueRefBase> m_ref;
9320 template<
typename LambdaT>
9321 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9322 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9326 ExeName() : m_name( std::make_shared<std::string>(
"<executable>" ) ) {}
9328 explicit ExeName( std::string &ref ) : ExeName() {
9329 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9332 template<
typename LambdaT>
9333 explicit ExeName( LambdaT
const& lambda ) : ExeName() {
9334 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9338 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9339 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9342 auto name()
const -> std::string {
return *m_name; }
9343 auto set( std::string
const& newName ) -> ParserResult {
9345 auto lastSlash = newName.find_last_of(
"\\/" );
9346 auto filename = ( lastSlash == std::string::npos )
9348 : newName.substr( lastSlash+1 );
9352 return m_ref->setValue( filename );
9354 return ParserResult::ok( ParseResultType::Matched );
9358 class Arg :
public ParserRefImpl<Arg> {
9360 using ParserRefImpl::ParserRefImpl;
9362 auto parse( std::string
const &, TokenStream
const &tokens )
const -> InternalParseResult
override {
9363 auto validationResult = validate();
9364 if( !validationResult )
9365 return InternalParseResult( validationResult );
9367 auto remainingTokens = tokens;
9368 auto const &token = *remainingTokens;
9369 if( token.type != TokenType::Argument )
9370 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9372 assert( !m_ref->isFlag() );
9373 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9375 auto result = valueRef->setValue( remainingTokens->token );
9377 return InternalParseResult( result );
9379 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9383 inline auto normaliseOpt( std::string
const &optName ) -> std::string {
9384 #ifdef CATCH_PLATFORM_WINDOWS 9385 if( optName[0] ==
'/' )
9386 return "-" + optName.substr( 1 );
9392 class Opt :
public ParserRefImpl<Opt> {
9394 std::vector<std::string> m_optNames;
9397 template<
typename LambdaT>
9398 explicit Opt( LambdaT
const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9400 explicit Opt(
bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9402 template<
typename LambdaT>
9403 Opt( LambdaT
const &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9405 template<
typename T>
9406 Opt( T &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9408 auto operator[]( std::string
const &optName ) -> Opt & {
9409 m_optNames.push_back( optName );
9413 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9414 std::ostringstream oss;
9416 for(
auto const &opt : m_optNames ) {
9423 if( !m_hint.empty() )
9424 oss <<
" <" << m_hint <<
">";
9425 return { { oss.str(), m_description } };
9428 auto isMatch( std::string
const &optToken )
const ->
bool {
9429 auto normalisedToken = normaliseOpt( optToken );
9430 for(
auto const &name : m_optNames ) {
9431 if( normaliseOpt( name ) == normalisedToken )
9439 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9440 auto validationResult = validate();
9441 if( !validationResult )
9442 return InternalParseResult( validationResult );
9444 auto remainingTokens = tokens;
9445 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9446 auto const &token = *remainingTokens;
9447 if( isMatch(token.token ) ) {
9448 if( m_ref->isFlag() ) {
9449 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>( m_ref.get() );
9450 auto result = flagRef->setFlag(
true );
9452 return InternalParseResult( result );
9453 if( result.value() == ParseResultType::ShortCircuitAll )
9454 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9456 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9458 if( !remainingTokens )
9459 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9460 auto const &argToken = *remainingTokens;
9461 if( argToken.type != TokenType::Argument )
9462 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9463 auto result = valueRef->setValue( argToken.token );
9465 return InternalParseResult( result );
9466 if( result.value() == ParseResultType::ShortCircuitAll )
9467 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9469 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9472 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9475 auto validate()
const -> Result
override {
9476 if( m_optNames.empty() )
9477 return Result::logicError(
"No options supplied to Opt" );
9478 for(
auto const &name : m_optNames ) {
9480 return Result::logicError(
"Option name cannot be empty" );
9481 #ifdef CATCH_PLATFORM_WINDOWS 9482 if( name[0] !=
'-' && name[0] !=
'/' )
9483 return Result::logicError(
"Option name must begin with '-' or '/'" );
9485 if( name[0] !=
'-' )
9486 return Result::logicError(
"Option name must begin with '-'" );
9489 return ParserRefImpl::validate();
9494 Help(
bool &showHelpFlag )
9495 : Opt([&](
bool flag ) {
9496 showHelpFlag = flag;
9497 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9500 static_cast<Opt &
>( *this )
9501 (
"display usage information")
9502 [
"-?"][
"-h"][
"--help"]
9507 struct Parser : ParserBase {
9509 mutable ExeName m_exeName;
9510 std::vector<Opt> m_options;
9511 std::vector<Arg> m_args;
9513 auto operator|=( ExeName
const &exeName ) -> Parser & {
9514 m_exeName = exeName;
9518 auto operator|=( Arg
const &arg ) -> Parser & {
9519 m_args.push_back(arg);
9523 auto operator|=( Opt
const &opt ) -> Parser & {
9524 m_options.push_back(opt);
9528 auto operator|=( Parser
const &other ) -> Parser & {
9529 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9530 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9534 template<
typename T>
9535 auto operator|( T
const &other )
const -> Parser {
9536 return Parser( *
this ) |= other;
9540 template<
typename T>
9541 auto operator+=( T
const &other ) -> Parser & {
return operator|=( other ); }
9542 template<
typename T>
9545 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9546 std::vector<HelpColumns> cols;
9547 for (
auto const &o : m_options) {
9548 auto childCols = o.getHelpColumns();
9549 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9554 void writeToStream( std::ostream &os )
const {
9555 if (!m_exeName.name().empty()) {
9556 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9557 bool required =
true, first =
true;
9558 for(
auto const &arg : m_args ) {
9563 if( arg.isOptional() && required ) {
9567 os <<
"<" << arg.hint() <<
">";
9568 if( arg.cardinality() == 0 )
9573 if( !m_options.empty() )
9575 os <<
"\n\nwhere options are:" << std::endl;
9578 auto rows = getHelpColumns();
9579 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9580 size_t optWidth = 0;
9581 for(
auto const &cols : rows )
9582 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9584 optWidth = (std::min)(optWidth, consoleWidth/2);
9586 for(
auto const &cols : rows ) {
9588 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9589 TextFlow::Spacer(4) +
9590 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9591 os << row << std::endl;
9595 friend auto operator<<( std::ostream &os, Parser
const &parser ) -> std::ostream& {
9596 parser.writeToStream( os );
9600 auto validate()
const -> Result
override {
9601 for(
auto const &opt : m_options ) {
9602 auto result = opt.validate();
9606 for(
auto const &arg : m_args ) {
9607 auto result = arg.validate();
9611 return Result::ok();
9616 auto parse( std::string
const& exeName, TokenStream
const &tokens )
const -> InternalParseResult
override {
9619 ParserBase
const* parser =
nullptr;
9622 const size_t totalParsers = m_options.size() + m_args.size();
9623 assert( totalParsers < 512 );
9625 ParserInfo parseInfos[512];
9629 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9630 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9633 m_exeName.set( exeName );
9635 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9636 while( result.value().remainingTokens() ) {
9637 bool tokenParsed =
false;
9639 for(
size_t i = 0; i < totalParsers; ++i ) {
9640 auto& parseInfo = parseInfos[i];
9641 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9642 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9645 if (result.value().type() != ParseResultType::NoMatch) {
9653 if( result.value().type() == ParseResultType::ShortCircuitAll )
9656 return InternalParseResult::runtimeError(
"Unrecognised token: " + result.value().remainingTokens()->token );
9663 template<
typename DerivedT>
9664 template<
typename T>
9666 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9671 using detail::Parser;
9683 using detail::ExeName;
9689 using detail::ParseResultType;
9692 using detail::ParserResult;
9698 #pragma clang diagnostic pop 9702 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9703 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9704 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9710 clara::Parser makeCommandLineParser( ConfigData& config );
9720 clara::Parser makeCommandLineParser( ConfigData& config ) {
9722 using namespace clara;
9724 auto const setWarning = [&]( std::string
const& warning ) {
9725 auto warningSet = [&]() {
9726 if( warning ==
"NoAssertions" )
9729 if ( warning ==
"NoTests" )
9736 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9737 config.warnings =
static_cast<WarnAbout::What>( config.warnings | warningSet );
9738 return ParserResult::ok( ParseResultType::Matched );
9740 auto const loadTestNamesFromFile = [&]( std::string
const& filename ) {
9741 std::ifstream f( filename.c_str() );
9743 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'" );
9746 while( std::getline( f, line ) ) {
9748 if( !line.empty() && !
startsWith( line,
'#' ) ) {
9750 line =
'"' + line +
'"';
9751 config.testsOrTags.push_back( line );
9752 config.testsOrTags.emplace_back(
"," );
9756 if(!config.testsOrTags.empty())
9757 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9759 return ParserResult::ok( ParseResultType::Matched );
9761 auto const setTestOrder = [&]( std::string
const& order ) {
9769 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'" );
9770 return ParserResult::ok( ParseResultType::Matched );
9772 auto const setRngSeed = [&]( std::string
const& seed ) {
9773 if( seed !=
"time" )
9774 return clara::detail::convertInto( seed, config.rngSeed );
9775 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9776 return ParserResult::ok( ParseResultType::Matched );
9778 auto const setColourUsage = [&]( std::string
const& useColour ) {
9779 auto mode =
toLower( useColour );
9783 else if( mode ==
"no" )
9785 else if( mode ==
"auto" )
9788 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9789 return ParserResult::ok( ParseResultType::Matched );
9791 auto const setWaitForKeypress = [&]( std::string
const& keypress ) {
9792 auto keypressLc =
toLower( keypress );
9793 if (keypressLc ==
"never")
9795 else if( keypressLc ==
"start" )
9797 else if( keypressLc ==
"exit" )
9799 else if( keypressLc ==
"both" )
9802 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9803 return ParserResult::ok( ParseResultType::Matched );
9805 auto const setVerbosity = [&]( std::string
const& verbosity ) {
9806 auto lcVerbosity =
toLower( verbosity );
9807 if( lcVerbosity ==
"quiet" )
9809 else if( lcVerbosity ==
"normal" )
9811 else if( lcVerbosity ==
"high" )
9814 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9815 return ParserResult::ok( ParseResultType::Matched );
9817 auto const setReporter = [&]( std::string
const& reporter ) {
9820 auto lcReporter =
toLower( reporter );
9821 auto result = factories.find( lcReporter );
9823 if( factories.end() != result )
9824 config.reporterName = lcReporter;
9826 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9827 return ParserResult::ok( ParseResultType::Matched );
9831 = ExeName( config.processName )
9832 | Help( config.showHelp )
9833 | Opt( config.listTests )
9834 ["-l"]["--list-tests"]
9835 (
"list all/matching test cases" )
9836 | Opt( config.listTags )
9837 ["-t"]["--list-tags"]
9838 (
"list all/matching tags" )
9839 | Opt( config.showSuccessfulTests )
9841 (
"include successful tests in output" )
9842 | Opt( config.shouldDebugBreak )
9844 (
"break into debugger on failure" )
9845 | Opt( config.noThrow )
9847 (
"skip exception tests" )
9848 | Opt( config.showInvisibles )
9849 ["-i"]["--invisibles"]
9850 (
"show invisibles (tabs, newlines)" )
9851 | Opt( config.outputFilename,
"filename" )
9853 (
"output filename" )
9854 | Opt( setReporter,
"name" )
9855 ["-r"]["--reporter"]
9856 (
"reporter to use (defaults to console)" )
9857 | Opt( config.name,
"name" )
9860 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9862 (
"abort at first failure" )
9863 | Opt( [&](
int x ){ config.abortAfter = x; },
"no. failures" )
9865 (
"abort after x failures" )
9866 | Opt( setWarning,
"warning name" )
9868 (
"enable warnings" )
9870 [
"-d"][
"--durations"]
9871 (
"show test durations" )
9872 | Opt( config.minDuration,
"seconds" )
9873 ["-D"]["--min-duration"]
9874 (
"show test durations for tests taking at least the given number of seconds" )
9875 | Opt( loadTestNamesFromFile,
"filename" )
9876 ["-f"]["--input-file"]
9877 (
"load test names to run from a file" )
9878 | Opt( config.filenamesAsTags )
9879 ["-#"]["--filenames-as-tags"]
9880 (
"adds a tag for the filename" )
9881 | Opt( config.sectionsToRun,
"section name" )
9883 (
"specify section to run" )
9884 | Opt( setVerbosity,
"quiet|normal|high" )
9885 ["-v"]["--verbosity"]
9886 (
"set output verbosity" )
9887 | Opt( config.listTestNamesOnly )
9888 ["--list-test-names-only"]
9889 (
"list all/matching test cases names only" )
9890 | Opt( config.listReporters )
9891 ["--list-reporters"]
9892 (
"list all reporters" )
9893 | Opt( setTestOrder,
"decl|lex|rand" )
9895 (
"test case order (defaults to decl)" )
9896 | Opt( setRngSeed,
"'time'|number" )
9898 (
"set a specific seed for random numbers" )
9899 | Opt( setColourUsage,
"yes|no" )
9901 (
"should output be colourised" )
9902 | Opt( config.libIdentify )
9904 (
"report name and version according to libidentify standard" )
9905 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9906 ["--wait-for-keypress"]
9907 (
"waits for a keypress before exiting" )
9908 | Opt( config.benchmarkSamples,
"samples" )
9909 ["--benchmark-samples"]
9910 (
"number of samples to collect (default: 100)" )
9911 | Opt( config.benchmarkResamples,
"resamples" )
9912 ["--benchmark-resamples"]
9913 (
"number of resamples for the bootstrap (default: 100000)" )
9914 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9915 ["--benchmark-confidence-interval"]
9916 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9917 | Opt( config.benchmarkNoAnalysis )
9918 ["--benchmark-no-analysis"]
9919 (
"perform only measurements; do not perform any analysis" )
9920 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9921 ["--benchmark-warmup-time"]
9922 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9923 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9924 (
"which test or tests to use" );
9939 return line == other.
line && (file == other.
file || std::strcmp(file, other.
file) == 0);
9944 return line < other.
line || ( line == other.
line && file != other.
file && (std::strcmp(file, other.
file) < 0));
9949 os << info.
file <<
'(' << info.
line <<
')';
9951 os << info.
file <<
':' << info.
line;
9957 return std::string();
9971 m_stream( openStream() )
9977 for (
auto& elem : m_data.testsOrTags) {
9980 for (
auto& elem : m_data.sectionsToRun) {
9984 TestSpecParser parser(ITagAliasRegistry::get());
9985 if (!m_data.testsOrTags.empty()) {
9986 m_hasTestFilters =
true;
9987 for (
auto const& testOrTags : m_data.testsOrTags) {
9988 parser.parse(testOrTags);
9991 m_testSpec = parser.testSpec();
9994 std::string
const& Config::getFilename()
const {
9995 return m_data.outputFilename ;
9998 bool Config::listTests()
const {
return m_data.listTests; }
9999 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
10000 bool Config::listTags()
const {
return m_data.listTags; }
10001 bool Config::listReporters()
const {
return m_data.listReporters; }
10003 std::string Config::getProcessName()
const {
return m_data.processName; }
10004 std::string
const& Config::getReporterName()
const {
return m_data.reporterName; }
10006 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
10007 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
10009 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
10010 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
10012 bool Config::showHelp()
const {
return m_data.showHelp; }
10015 bool Config::allowThrows()
const {
return !m_data.noThrow; }
10016 std::ostream& Config::stream()
const {
return m_stream->stream(); }
10017 std::string Config::name()
const {
return m_data.name.empty() ? m_data.processName : m_data.name; }
10018 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
10020 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings &
WarnAbout::NoTests); }
10022 double Config::minDuration()
const {
return m_data.minDuration; }
10026 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
10027 int Config::abortAfter()
const {
return m_data.abortAfter; }
10028 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
10029 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
10031 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
10032 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
10033 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
10034 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
10035 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10037 IStream const* Config::openStream() {
10045 #if defined(__clang__) 10046 # pragma clang diagnostic push 10047 # pragma clang diagnostic ignored "-Wexit-time-destructors" 10070 struct IColourImpl {
10071 virtual ~IColourImpl() =
default;
10072 virtual void use( Colour::Code _colourCode ) = 0;
10075 struct NoColourImpl : IColourImpl {
10076 void use( Colour::Code )
override {}
10078 static IColourImpl* instance() {
10079 static NoColourImpl s_instance;
10080 return &s_instance;
10087 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) 10088 # ifdef CATCH_PLATFORM_WINDOWS 10089 # define CATCH_CONFIG_COLOUR_WINDOWS 10091 # define CATCH_CONFIG_COLOUR_ANSI 10095 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) 10100 class Win32ColourImpl :
public IColourImpl {
10102 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10104 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10105 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10106 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10107 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10110 void use( Colour::Code _colourCode )
override {
10111 switch( _colourCode ) {
10112 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
10113 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10114 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
10115 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
10116 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
10117 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10118 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10119 case Colour::Grey:
return setTextAttribute( 0 );
10121 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
10122 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10123 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10124 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10125 case Colour::BrightYellow:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10135 void setTextAttribute( WORD _textAttribute ) {
10136 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10138 HANDLE stdoutHandle;
10139 WORD originalForegroundAttributes;
10140 WORD originalBackgroundAttributes;
10143 IColourImpl* platformColourInstance() {
10144 static Win32ColourImpl s_instance;
10148 ? config->useColour()
10154 : NoColourImpl::instance();
10160 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) 10162 #include <unistd.h> 10171 class PosixColourImpl :
public IColourImpl {
10173 void use( Colour::Code _colourCode )
override {
10174 switch( _colourCode ) {
10176 case Colour::White:
return setColour(
"[0m" );
10177 case Colour::Red:
return setColour(
"[0;31m" );
10178 case Colour::Green:
return setColour(
"[0;32m" );
10179 case Colour::Blue:
return setColour(
"[0;34m" );
10180 case Colour::Cyan:
return setColour(
"[0;36m" );
10181 case Colour::Yellow:
return setColour(
"[0;33m" );
10182 case Colour::Grey:
return setColour(
"[1;30m" );
10184 case Colour::LightGrey:
return setColour(
"[0;37m" );
10185 case Colour::BrightRed:
return setColour(
"[1;31m" );
10186 case Colour::BrightGreen:
return setColour(
"[1;32m" );
10187 case Colour::BrightWhite:
return setColour(
"[1;37m" );
10188 case Colour::BrightYellow:
return setColour(
"[1;33m" );
10194 static IColourImpl* instance() {
10195 static PosixColourImpl s_instance;
10196 return &s_instance;
10200 void setColour(
const char* _escapeCode ) {
10202 <<
'\033' << _escapeCode;
10206 bool useColourOnPlatform() {
10208 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10209 !isDebuggerActive() &&
10211 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) 10212 isatty(STDOUT_FILENO)
10218 IColourImpl* platformColourInstance() {
10222 ? config->useColour()
10225 colourMode = useColourOnPlatform()
10229 ? PosixColourImpl::instance()
10230 : NoColourImpl::instance();
10236 #else // not Windows or ANSI 10240 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
10244 #endif // Windows/ ANSI/ None 10248 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10249 Colour::Colour( Colour&& other ) noexcept {
10250 m_moved = other.m_moved;
10251 other.m_moved =
true;
10253 Colour& Colour::operator=( Colour&& other ) noexcept {
10254 m_moved = other.m_moved;
10255 other.m_moved =
true;
10259 Colour::~Colour(){
if( !m_moved ) use( None ); }
10261 void Colour::use( Code _colourCode ) {
10262 static IColourImpl* impl = platformColourInstance();
10267 if (impl !=
nullptr) {
10268 impl->use( _colourCode );
10272 std::ostream&
operator << ( std::ostream& os, Colour
const& ) {
10278 #if defined(__clang__) 10279 # pragma clang diagnostic pop 10291 return m_resultCapture;
10293 IRunner* getRunner()
override {
10297 IConfigPtr const& getConfig()
const override {
10301 ~Context()
override;
10304 void setResultCapture(
IResultCapture* resultCapture )
override {
10305 m_resultCapture = resultCapture;
10307 void setRunner(
IRunner* runner )
override {
10310 void setConfig(
IConfigPtr const& config )
override {
10324 void IMutableContext::createContext()
10326 currentContext =
new Context();
10330 delete IMutableContext::currentContext;
10331 IMutableContext::currentContext =
nullptr;
10335 Context::~Context() =
default;
10351 void writeToDebugConsole( std::string
const& text );
10355 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE) 10356 #include <android/log.h> 10359 void writeToDebugConsole( std::string
const& text ) {
10360 __android_log_write( ANDROID_LOG_DEBUG,
"Catch", text.c_str() );
10364 #elif defined(CATCH_PLATFORM_WINDOWS) 10367 void writeToDebugConsole( std::string
const& text ) {
10368 ::OutputDebugStringA( text.c_str() );
10375 void writeToDebugConsole( std::string
const& text ) {
10385 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10387 # include <cassert> 10388 # include <sys/types.h> 10389 # include <unistd.h> 10390 # include <cstddef> 10391 # include <ostream> 10393 #ifdef __apple_build_version__ 10396 # include <sys/sysctl.h> 10400 #ifdef __apple_build_version__ 10406 bool isDebuggerActive(){
10408 struct kinfo_proc info;
10414 info.kp_proc.p_flag = 0;
10420 mib[1] = KERN_PROC;
10421 mib[2] = KERN_PROC_PID;
10426 size =
sizeof(info);
10427 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0 ) {
10428 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10434 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10437 bool isDebuggerActive() {
10444 #elif defined(CATCH_PLATFORM_LINUX) 10456 bool isDebuggerActive(){
10460 std::ifstream in(
"/proc/self/status");
10461 for( std::string line; std::getline(in, line); ) {
10462 static const int PREFIX_LEN = 11;
10463 if( line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
10467 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
10474 #elif defined(_MSC_VER) 10475 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10477 bool isDebuggerActive() {
10478 return IsDebuggerPresent() != 0;
10481 #elif defined(__MINGW32__) 10482 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10484 bool isDebuggerActive() {
10485 return IsDebuggerPresent() != 0;
10490 bool isDebuggerActive() {
return false; }
10501 if( lhs.size() + rhs.size() < 40 &&
10502 lhs.find(
'\n') == std::string::npos &&
10503 rhs.find(
'\n') == std::string::npos )
10504 os << lhs <<
" " << op <<
" " << rhs;
10506 os << lhs <<
"\n" << op <<
"\n" << rhs;
10512 #include <stdexcept> 10515 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) 10518 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n" 10519 <<
"The message was: " << e.what() <<
'\n';
10551 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const&
values );
10555 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10557 EnumInfo
const& registerEnum(
StringRef enumName,
StringRef allEnums, std::vector<int>
const& values)
override;
10560 std::vector<StringRef> parseEnums(
StringRef enums );
10582 size_t name_start = enumInstance.
size();
10583 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10586 return enumInstance.
substr(name_start, enumInstance.
size() - name_start);
10590 std::vector<StringRef> parseEnums(
StringRef enums ) {
10592 std::vector<StringRef> parsed;
10593 parsed.reserve( enumValues.size() );
10594 for(
auto const& enumValue : enumValues ) {
10595 parsed.push_back(
trim(extractInstanceName(enumValue)));
10600 EnumInfo::~EnumInfo() {}
10603 for(
auto const& valueToName : m_values ) {
10604 if( valueToName.first == value )
10605 return valueToName.second;
10607 return "{** unexpected enum value **}"_sr;
10610 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const&
values ) {
10611 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo );
10612 enumInfo->m_name = enumName;
10613 enumInfo->m_values.reserve( values.size() );
10615 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10616 assert( valueNames.size() == values.size() );
10618 for(
auto value : values )
10619 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10624 EnumInfo
const& EnumValuesRegistry::registerEnum(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const& values ) {
10625 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10626 return *m_enumInfos.back();
10638 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10639 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10654 ~ExceptionTranslatorRegistry();
10657 std::string tryTranslators()
const;
10660 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10666 #import "Foundation/Foundation.h" 10671 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10674 void ExceptionTranslatorRegistry::registerTranslator(
const IExceptionTranslator* translator ) {
10675 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10678 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 10684 return tryTranslators();
10686 @catch (NSException *exception) {
10698 if (std::current_exception() ==
nullptr) {
10699 return "Non C++ exception. Possibly a CLR exception.";
10701 return tryTranslators();
10705 std::rethrow_exception(std::current_exception());
10707 catch( std::exception& ex ) {
10710 catch( std::string& msg ) {
10713 catch(
const char* msg ) {
10717 return "Unknown exception";
10721 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10722 if (m_translators.empty()) {
10723 std::rethrow_exception(std::current_exception());
10725 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10729 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 10731 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10734 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10735 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10743 #if defined(__GNUC__) 10744 # pragma GCC diagnostic push 10745 # pragma GCC diagnostic ignored "-Wmissing-field-initializers" 10748 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) 10752 void reportFatal(
char const *
const message ) {
10757 #endif // signals/SEH handling 10759 #if defined( CATCH_CONFIG_WINDOWS_SEH ) 10762 struct SignalDefs { DWORD id;
const char* name; };
10767 static SignalDefs signalDefs[] = {
10768 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10769 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10770 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10771 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10774 LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10775 for (
auto const& def : signalDefs) {
10776 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10777 reportFatal(def.name);
10782 return EXCEPTION_CONTINUE_SEARCH;
10785 FatalConditionHandler::FatalConditionHandler() {
10789 guaranteeSize = 32 * 1024;
10790 exceptionHandlerHandle =
nullptr;
10792 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10794 SetThreadStackGuarantee(&guaranteeSize);
10797 void FatalConditionHandler::reset() {
10799 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
10800 SetThreadStackGuarantee(&guaranteeSize);
10801 exceptionHandlerHandle =
nullptr;
10806 FatalConditionHandler::~FatalConditionHandler() {
10810 bool FatalConditionHandler::isSet =
false;
10811 ULONG FatalConditionHandler::guaranteeSize = 0;
10812 PVOID FatalConditionHandler::exceptionHandlerHandle =
nullptr;
10816 #elif defined( CATCH_CONFIG_POSIX_SIGNALS ) 10820 struct SignalDefs {
10827 static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
10829 static SignalDefs signalDefs[] = {
10830 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10831 { SIGILL,
"SIGILL - Illegal instruction signal" },
10832 { SIGFPE,
"SIGFPE - Floating point error signal" },
10833 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10834 { SIGTERM,
"SIGTERM - Termination request signal" },
10835 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10838 void FatalConditionHandler::handleSignal(
int sig ) {
10839 char const * name =
"<unknown signal>";
10840 for (
auto const& def : signalDefs) {
10841 if (sig == def.id) {
10851 FatalConditionHandler::FatalConditionHandler() {
10854 sigStack.ss_sp = altStackMem;
10855 sigStack.ss_size = sigStackSize;
10856 sigStack.ss_flags = 0;
10857 sigaltstack(&sigStack, &oldSigStack);
10858 struct sigaction sa = { };
10860 sa.sa_handler = handleSignal;
10861 sa.sa_flags = SA_ONSTACK;
10862 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
10863 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
10867 FatalConditionHandler::~FatalConditionHandler() {
10871 void FatalConditionHandler::reset() {
10874 for( std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i ) {
10875 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10878 sigaltstack(&oldSigStack,
nullptr);
10883 bool FatalConditionHandler::isSet =
false;
10884 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
10885 stack_t FatalConditionHandler::oldSigStack = {};
10886 char FatalConditionHandler::altStackMem[sigStackSize] = {};
10893 void FatalConditionHandler::reset() {}
10896 #endif // signals/SEH handling 10898 #if defined(__GNUC__) 10899 # pragma GCC diagnostic pop 10915 namespace Generators {
10917 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10958 class ListeningReporter :
public IStreamingReporter {
10959 using Reporters = std::vector<IStreamingReporterPtr>;
10960 Reporters m_listeners;
10961 IStreamingReporterPtr m_reporter =
nullptr;
10962 ReporterPreferences m_preferences;
10965 ListeningReporter();
10967 void addListener( IStreamingReporterPtr&& listener );
10968 void addReporter( IStreamingReporterPtr&& reporter );
10972 ReporterPreferences getPreferences()
const override;
10974 void noMatchingTestCases( std::string
const& spec )
override;
10976 void reportInvalidArguments(std::string
const&arg)
override;
10978 static std::set<Verbosity> getSupportedVerbosities();
10980 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 10981 void benchmarkPreparing(std::string
const& name)
override;
10982 void benchmarkStarting( BenchmarkInfo
const& benchmarkInfo )
override;
10983 void benchmarkEnded( BenchmarkStats<>
const& benchmarkStats )
override;
10984 void benchmarkFailed(std::string
const&)
override;
10985 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 10987 void testRunStarting( TestRunInfo
const& testRunInfo )
override;
10988 void testGroupStarting( GroupInfo
const& groupInfo )
override;
10989 void testCaseStarting(
TestCaseInfo const& testInfo )
override;
10990 void sectionStarting(
SectionInfo const& sectionInfo )
override;
10991 void assertionStarting(
AssertionInfo const& assertionInfo )
override;
10994 bool assertionEnded( AssertionStats
const& assertionStats )
override;
10995 void sectionEnded( SectionStats
const& sectionStats )
override;
10996 void testCaseEnded( TestCaseStats
const& testCaseStats )
override;
10997 void testGroupEnded( TestGroupStats
const& testGroupStats )
override;
10998 void testRunEnded( TestRunStats
const& testRunStats )
override;
11000 void skipTest(
TestCaseInfo const& testInfo )
override;
11001 bool isMulti()
const override;
11010 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig )
11011 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11013 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream )
11014 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11016 std::ostream& ReporterConfig::stream()
const {
return *m_stream; }
11017 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
11019 TestRunInfo::TestRunInfo( std::string
const& _name ) : name( _name ) {}
11021 GroupInfo::GroupInfo( std::string
const& _name,
11022 std::size_t _groupIndex,
11023 std::size_t _groupsCount )
11025 groupIndex( _groupIndex ),
11026 groupsCounts( _groupsCount )
11029 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
11030 std::vector<MessageInfo>
const& _infoMessages,
11032 : assertionResult( _assertionResult ),
11033 infoMessages( _infoMessages ),
11036 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11038 if( assertionResult.hasMessage() ) {
11041 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11042 builder << assertionResult.getMessage();
11045 infoMessages.push_back( builder.m_info );
11049 AssertionStats::~AssertionStats() =
default;
11051 SectionStats::SectionStats(
SectionInfo const& _sectionInfo,
11052 Counts const& _assertions,
11053 double _durationInSeconds,
11054 bool _missingAssertions )
11055 : sectionInfo( _sectionInfo ),
11056 assertions( _assertions ),
11057 durationInSeconds( _durationInSeconds ),
11058 missingAssertions( _missingAssertions )
11061 SectionStats::~SectionStats() =
default;
11063 TestCaseStats::TestCaseStats(
TestCaseInfo const& _testInfo,
11065 std::string
const& _stdOut,
11066 std::string
const& _stdErr,
11068 : testInfo( _testInfo ),
11072 aborting( _aborting )
11075 TestCaseStats::~TestCaseStats() =
default;
11077 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11080 : groupInfo( _groupInfo ),
11082 aborting( _aborting )
11085 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11086 : groupInfo( _groupInfo ),
11090 TestGroupStats::~TestGroupStats() =
default;
11092 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11095 : runInfo( _runInfo ),
11097 aborting( _aborting )
11100 TestRunStats::~TestRunStats() =
default;
11102 void IStreamingReporter::fatalErrorEncountered(
StringRef ) {}
11103 bool IStreamingReporter::isMulti()
const {
return false; }
11105 IReporterFactory::~IReporterFactory() =
default;
11106 IReporterRegistry::~IReporterRegistry() =
default;
11125 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG 11126 #include <crtdbg.h> 11130 LeakDetector::LeakDetector() {
11131 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11132 flag |= _CRTDBG_LEAK_CHECK_DF;
11133 flag |= _CRTDBG_ALLOC_MEM_DF;
11134 _CrtSetDbgFlag(flag);
11135 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11136 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11138 _CrtSetBreakAlloc(-1);
11144 Catch::LeakDetector::LeakDetector() {}
11148 Catch::LeakDetector::~LeakDetector() {
11160 std::size_t listTests(
Config const& config );
11162 std::size_t listTestsNamesOnly(
Config const& config );
11165 void add( std::string
const& spelling );
11166 std::string all()
const;
11168 std::set<std::string> spellings;
11169 std::size_t count = 0;
11172 std::size_t listTags(
Config const& config );
11174 std::size_t listReporters();
11184 using namespace clara::TextFlow;
11189 #include <algorithm> 11194 std::size_t listTests(
Config const& config ) {
11195 TestSpec
const& testSpec = config.testSpec();
11196 if( config.hasTestFilters() )
11203 for(
auto const& testCaseInfo : matchedTestCases ) {
11204 Colour::Code colour = testCaseInfo.isHidden()
11205 ? Colour::SecondaryText
11207 Colour colourGuard( colour );
11209 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11212 std::string description = testCaseInfo.description;
11213 if( description.empty() )
11214 description =
"(NO DESCRIPTION)";
11215 Catch::cout() << Column( description ).indent(4) << std::endl;
11217 if( !testCaseInfo.tags.empty() )
11218 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) <<
"\n";
11221 if( !config.hasTestFilters() )
11224 Catch::cout() <<
pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11225 return matchedTestCases.size();
11228 std::size_t listTestsNamesOnly(
Config const& config ) {
11229 TestSpec
const& testSpec = config.testSpec();
11230 std::size_t matchedTests = 0;
11232 for(
auto const& testCaseInfo : matchedTestCases ) {
11235 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11242 return matchedTests;
11247 spellings.insert( spelling );
11250 std::string TagInfo::all()
const {
11252 for (
auto const& spelling : spellings) {
11254 size += spelling.size() + 2;
11257 std::string out; out.reserve(size);
11258 for (
auto const& spelling : spellings) {
11266 std::size_t listTags(
Config const& config ) {
11267 TestSpec
const& testSpec = config.testSpec();
11268 if( config.hasTestFilters() )
11269 Catch::cout() <<
"Tags for matching test cases:\n";
11274 std::map<std::string, TagInfo> tagCounts;
11277 for(
auto const& testCase : matchedTestCases ) {
11278 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11279 std::string lcaseTagName =
toLower( tagName );
11280 auto countIt = tagCounts.find( lcaseTagName );
11281 if( countIt == tagCounts.end() )
11282 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11283 countIt->second.add( tagName );
11287 for(
auto const& tagCount : tagCounts ) {
11289 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11291 auto wrapper = Column( tagCount.second.all() )
11292 .initialIndent( 0 )
11293 .indent(
str.size() )
11298 return tagCounts.size();
11301 std::size_t listReporters() {
11304 std::size_t maxNameLen = 0;
11305 for(
auto const& factoryKvp : factories )
11306 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11308 for(
auto const& factoryKvp : factories ) {
11310 << Column( factoryKvp.first +
":" )
11312 .width( 5+maxNameLen )
11313 + Column( factoryKvp.second->getDescription() )
11320 return factories.size();
11326 if( config->listTests() )
11327 listedCount = listedCount.
valueOr(0) + listTests( *config );
11328 if( config->listTestNamesOnly() )
11329 listedCount = listedCount.
valueOr(0) + listTestsNamesOnly( *config );
11330 if( config->listTags() )
11331 listedCount = listedCount.
valueOr(0) + listTags( *config );
11332 if( config->listReporters() )
11333 listedCount = listedCount.
valueOr(0) + listReporters();
11334 return listedCount;
11342 namespace Matchers {
11345 std::string MatcherUntypedBase::toString()
const {
11346 if( m_cachedToString.empty() )
11347 m_cachedToString = describe();
11348 return m_cachedToString;
11351 MatcherUntypedBase::~MatcherUntypedBase() =
default;
11356 using namespace Matchers;
11364 namespace Matchers {
11367 bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11368 return ex.what() == m_message;
11371 std::string ExceptionMessageMatcher::describe()
const {
11372 return "exception message matches \"" + m_message +
"\"";
11389 bool isnan(
float f);
11390 bool isnan(
double d);
11399 template <
typename T>
11401 #if defined(CATCH_CONFIG_CPP11_TO_STRING) 11412 #include <algorithm> 11418 #include <type_traits> 11425 int32_t convert(
float f) {
11426 static_assert(
sizeof(
float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11428 std::memcpy(&i, &f,
sizeof(f));
11432 int64_t convert(
double d) {
11433 static_assert(
sizeof(
double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11435 std::memcpy(&i, &d,
sizeof(d));
11439 template <
typename FP>
11440 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11443 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11447 auto lc = convert(lhs);
11448 auto rc = convert(rhs);
11450 if ((lc < 0) != (rc < 0)) {
11456 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11459 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11461 float nextafter(
float x,
float y) {
11462 return ::nextafterf(x, y);
11465 double nextafter(
double x,
double y) {
11466 return ::nextafter(x, y);
11469 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^ 11471 template <
typename FP>
11472 FP step(FP start, FP direction, uint64_t steps) {
11473 for (uint64_t i = 0; i < steps; ++i) {
11474 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11475 start = Catch::nextafter(start, direction);
11477 start = std::nextafter(start, direction);
11485 bool marginComparison(
double lhs,
double rhs,
double margin) {
11486 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11489 template <
typename FloatingPo
int>
11490 void write(std::ostream& out, FloatingPoint num) {
11491 out << std::scientific
11492 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11498 namespace Matchers {
11499 namespace Floating {
11501 enum class FloatingPointKind : uint8_t {
11506 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11507 :m_target{ target }, m_margin{ margin } {
11508 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.' 11509 <<
" Margin has to be non-negative.");
11514 bool WithinAbsMatcher::match(
double const& matchee)
const {
11515 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11518 std::string WithinAbsMatcher::describe()
const {
11522 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11523 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11525 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11526 "Provided ULP is impossibly large for a float comparison.");
11529 #if defined(__clang__) 11530 #pragma clang diagnostic push 11532 #pragma clang diagnostic ignored "-Wunreachable-code" 11535 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11538 return almostEqualUlps<float>(
static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11540 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11546 #if defined(__clang__) 11547 #pragma clang diagnostic pop 11550 std::string WithinUlpsMatcher::describe()
const {
11551 std::stringstream ret;
11553 ret <<
"is within " << m_ulps <<
" ULPs of ";
11556 write(ret, static_cast<float>(m_target));
11559 write(ret, m_target);
11564 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11566 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11569 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11571 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11578 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11580 m_epsilon(epsilon){
11581 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11582 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
"); 11585 bool WithinRelMatcher::match(double const& matchee) const { 11586 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); 11587 return marginComparison(matchee, m_target, 11588 std::isinf(relMargin)? 0 : relMargin); 11591 std::string WithinRelMatcher::describe() const { 11592 Catch::ReusableStringStream sstr; 11593 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
"; 11597 }// namespace Floating 11599 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { 11600 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); 11603 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { 11604 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); 11607 Floating::WithinAbsMatcher WithinAbs(double target, double margin) { 11608 return Floating::WithinAbsMatcher(target, margin); 11611 Floating::WithinRelMatcher WithinRel(double target, double eps) { 11612 return Floating::WithinRelMatcher(target, eps); 11615 Floating::WithinRelMatcher WithinRel(double target) { 11616 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); 11619 Floating::WithinRelMatcher WithinRel(float target, float eps) { 11620 return Floating::WithinRelMatcher(target, eps); 11623 Floating::WithinRelMatcher WithinRel(float target) { 11624 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); 11627 } // namespace Matchers 11628 } // namespace Catch 11630 // end catch_matchers_floating.cpp 11631 // start catch_matchers_generic.cpp 11633 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { 11634 if (desc.empty()) { 11635 return "matches undescribed predicate
"; 11637 return "matches predicate: \
"" + desc +
'"';
11646 namespace Matchers {
11648 namespace StdString {
11651 : m_caseSensitivity( caseSensitivity ),
11652 m_str( adjustString( str ) )
11654 std::string CasedString::adjustString( std::string
const& str )
const {
11659 std::string CasedString::caseSensitivitySuffix()
const {
11661 ?
" (case insensitive)" 11665 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
11666 : m_comparator( comparator ),
11667 m_operation( operation ) {
11670 std::string StringMatcherBase::describe()
const {
11671 std::string description;
11672 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11673 m_comparator.caseSensitivitySuffix().size());
11674 description += m_operation;
11675 description +=
": \"";
11676 description += m_comparator.m_str;
11677 description +=
"\"";
11678 description += m_comparator.caseSensitivitySuffix();
11679 return description;
11682 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11684 bool EqualsMatcher::match( std::string
const& source )
const {
11685 return m_comparator.adjustString( source ) == m_comparator.m_str;
11688 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11690 bool ContainsMatcher::match( std::string
const& source )
const {
11691 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11694 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11696 bool StartsWithMatcher::match( std::string
const& source )
const {
11697 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11700 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11702 bool EndsWithMatcher::match( std::string
const& source )
const {
11703 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11706 RegexMatcher::RegexMatcher(std::string regex,
CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11708 bool RegexMatcher::match(std::string
const& matchee)
const {
11709 auto flags = std::regex::ECMAScript;
11710 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11711 flags |= std::regex::icase;
11713 auto reg = std::regex(m_regex, flags);
11714 return std::regex_match(matchee, reg);
11717 std::string RegexMatcher::describe()
const {
11718 return "matches " +
::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)?
" case sensitively" :
" case insensitively");
11748 bool uncaught_exceptions();
11760 : macroName( _macroName ),
11761 lineInfo( _lineInfo ),
11763 sequence( ++globalCount )
11767 return sequence == other.
sequence;
11775 unsigned int MessageInfo::globalCount = 0;
11782 :m_info(macroName, lineInfo, type) {}
11787 : m_info( builder.
m_info ), m_moved()
11794 : m_info( old.m_info ), m_moved()
11796 old.m_moved =
true;
11800 if ( !uncaught_exceptions() && !m_moved ){
11806 auto trimmed = [&] (
size_t start,
size_t end) {
11807 while (names[start] ==
',' || isspace(static_cast<unsigned char>(names[start]))) {
11810 while (names[end] ==
',' || isspace(static_cast<unsigned char>(names[end]))) {
11813 return names.
substr(start, end - start + 1);
11815 auto skipq = [&] (
size_t start,
char quote) {
11816 for (
auto i = start + 1; i < names.
size() ; ++i) {
11817 if (names[i] == quote)
11819 if (names[i] ==
'\\')
11826 std::stack<char> openings;
11827 for (
size_t pos = 0; pos < names.
size(); ++pos) {
11828 char c = names[pos];
11846 pos = skipq(pos, c);
11849 if (start != pos && openings.empty()) {
11850 m_messages.emplace_back(macroName, lineInfo, resultType);
11851 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11852 m_messages.back().message +=
" := ";
11857 assert(openings.empty() &&
"Mismatched openings");
11858 m_messages.emplace_back(macroName, lineInfo, resultType);
11859 m_messages.back().message =
static_cast<std::string
>(trimmed(start, names.
size() - 1));
11860 m_messages.back().message +=
" := ";
11863 if ( !uncaught_exceptions() ){
11864 assert( m_captured == m_messages.size() );
11865 for(
size_t i = 0; i < m_captured; ++i )
11866 m_resultCapture.popScopedMessage( m_messages[i] );
11871 assert( index < m_messages.size() );
11872 m_messages[index].message +=
value;
11873 m_resultCapture.pushScopedMessage( m_messages[index] );
11882 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11883 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11891 class RedirectedStream {
11892 std::ostream& m_originalStream;
11893 std::ostream& m_redirectionStream;
11894 std::streambuf* m_prevBuf;
11897 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11898 ~RedirectedStream();
11901 class RedirectedStdOut {
11903 RedirectedStream m_cout;
11905 RedirectedStdOut();
11906 auto str()
const -> std::string;
11912 class RedirectedStdErr {
11914 RedirectedStream m_cerr;
11915 RedirectedStream m_clog;
11917 RedirectedStdErr();
11918 auto str()
const -> std::string;
11921 class RedirectedStreams {
11923 RedirectedStreams(RedirectedStreams
const&) =
delete;
11924 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
11925 RedirectedStreams(RedirectedStreams&&) =
delete;
11926 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
11928 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11929 ~RedirectedStreams();
11931 std::string& m_redirectedCout;
11932 std::string& m_redirectedCerr;
11933 RedirectedStdOut m_redirectedStdOut;
11934 RedirectedStdErr m_redirectedStdErr;
11937 #if defined(CATCH_CONFIG_NEW_CAPTURE) 11945 TempFile(TempFile
const&) =
delete;
11946 TempFile& operator=(TempFile
const&) =
delete;
11947 TempFile(TempFile&&) =
delete;
11948 TempFile& operator=(TempFile&&) =
delete;
11953 std::FILE* getFile();
11954 std::string getContents();
11957 std::FILE* m_file =
nullptr;
11958 #if defined(_MSC_VER) 11959 char m_buffer[L_tmpnam] = { 0 };
11963 class OutputRedirect {
11965 OutputRedirect(OutputRedirect
const&) =
delete;
11966 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
11967 OutputRedirect(OutputRedirect&&) =
delete;
11968 OutputRedirect& operator=(OutputRedirect&&) =
delete;
11970 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
11974 int m_originalStdout = -1;
11975 int m_originalStderr = -1;
11976 TempFile m_stdoutFile;
11977 TempFile m_stderrFile;
11978 std::string& m_stdoutDest;
11979 std::string& m_stderrDest;
11986 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11992 #include <stdexcept> 11994 #if defined(CATCH_CONFIG_NEW_CAPTURE) 11995 #if defined(_MSC_VER) 11999 #define fileno _fileno 12001 #include <unistd.h> 12007 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12008 : m_originalStream( originalStream ),
12009 m_redirectionStream( redirectionStream ),
12010 m_prevBuf( m_originalStream.rdbuf() )
12012 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12015 RedirectedStream::~RedirectedStream() {
12016 m_originalStream.rdbuf( m_prevBuf );
12019 RedirectedStdOut::RedirectedStdOut() : m_cout(
Catch::cout(), m_rss.get() ) {}
12022 RedirectedStdErr::RedirectedStdErr()
12028 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12029 : m_redirectedCout(redirectedCout),
12030 m_redirectedCerr(redirectedCerr)
12033 RedirectedStreams::~RedirectedStreams() {
12034 m_redirectedCout += m_redirectedStdOut.str();
12035 m_redirectedCerr += m_redirectedStdErr.str();
12038 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12040 #if defined(_MSC_VER) 12041 TempFile::TempFile() {
12042 if (tmpnam_s(m_buffer)) {
12045 if (fopen_s(&m_file, m_buffer,
"w")) {
12047 if (strerror_s(buffer, errno)) {
12050 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12054 TempFile::TempFile() {
12055 m_file = std::tmpfile();
12063 TempFile::~TempFile() {
12065 std::fclose(m_file);
12068 #if defined(_MSC_VER) 12069 std::remove(m_buffer);
12073 FILE* TempFile::getFile() {
12077 std::string TempFile::getContents() {
12078 std::stringstream sstr;
12079 char buffer[100] = {};
12080 std::rewind(m_file);
12081 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12087 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12088 m_originalStdout(dup(1)),
12089 m_originalStderr(dup(2)),
12090 m_stdoutDest(stdout_dest),
12091 m_stderrDest(stderr_dest) {
12092 dup2(fileno(m_stdoutFile.getFile()), 1);
12093 dup2(fileno(m_stderrFile.getFile()), 2);
12096 OutputRedirect::~OutputRedirect() {
12105 dup2(m_originalStdout, 1);
12106 dup2(m_originalStderr, 2);
12108 m_stdoutDest += m_stdoutFile.getContents();
12109 m_stderrDest += m_stderrFile.getContents();
12112 #endif // CATCH_CONFIG_NEW_CAPTURE 12116 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12117 #if defined(_MSC_VER) 12130 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) 12131 bool isnan(
float f) {
12132 return std::isnan(f);
12134 bool isnan(
double d) {
12135 return std::isnan(d);
12139 bool isnan(
float f) {
12140 return std::_isnan(f);
12142 bool isnan(
double d) {
12143 return std::_isnan(d);
12155 #if defined(_MSC_VER) 12156 #pragma warning(push) 12157 #pragma warning(disable:4146) // we negate uint32 during the rotate 12160 uint32_t rotate_right(uint32_t val, uint32_t count) {
12161 const uint32_t mask = 31;
12163 return (val >> count) | (val << (-count & mask));
12166 #if defined(_MSC_VER) 12167 #pragma warning(pop) 12186 for (uint64_t s = 0; s < skip; ++s) {
12187 static_cast<void>((*this)());
12193 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12194 const auto output = rotate_right(xorshifted, m_state >> 59u);
12197 m_state = m_state * 6364136223846793005ULL + s_inc;
12203 return lhs.m_state == rhs.m_state;
12207 return lhs.m_state != rhs.m_state;
12217 #include <algorithm> 12225 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases );
12230 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12232 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
12237 virtual ~TestRegistry() =
default;
12239 virtual void registerTest(
TestCase const& testCase );
12241 std::vector<TestCase>
const& getAllTests()
const override;
12242 std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const override;
12245 std::vector<TestCase> m_functions;
12247 mutable std::vector<TestCase> m_sortedFunctions;
12248 std::size_t m_unnamedCount = 0;
12249 std::ios_base::Init m_ostreamInit;
12255 void(*m_testAsFunction)();
12257 TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept;
12259 void invoke()
const override;
12262 std::string extractClassName(
StringRef const& classOrQualifiedMethodName );
12275 class ReporterRegistry :
public IReporterRegistry {
12279 ~ReporterRegistry()
override;
12281 IStreamingReporterPtr create( std::string
const& name,
IConfigPtr const& config )
const override;
12286 FactoryMap
const& getFactories()
const override;
12287 Listeners
const& getListeners()
const override;
12290 FactoryMap m_factories;
12291 Listeners m_listeners;
12318 class TagAliasRegistry :
public ITagAliasRegistry {
12320 ~TagAliasRegistry()
override;
12321 TagAlias
const* find( std::string
const& alias )
const override;
12322 std::string expandAliases( std::string
const& unexpandedTestSpec )
const override;
12323 void add( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo );
12326 std::map<std::string, TagAlias> m_registry;
12335 #include <exception> 12339 class StartupExceptionRegistry {
12340 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 12342 void add(std::exception_ptr
const& exception) noexcept;
12343 std::vector<std::exception_ptr>
const& getExceptions()
const noexcept;
12345 std::vector<std::exception_ptr> m_exceptions;
12356 struct ISingleton {
12357 virtual ~ISingleton();
12360 void addSingleton( ISingleton* singleton );
12361 void cleanupSingletons();
12363 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12364 class Singleton : SingletonImplT,
public ISingleton {
12366 static auto getInternal() -> Singleton* {
12367 static Singleton* s_instance =
nullptr;
12368 if( !s_instance ) {
12369 s_instance =
new Singleton;
12370 addSingleton( s_instance );
12376 static auto get() -> InterfaceT
const& {
12377 return *getInternal();
12379 static auto getMutable() -> MutableInterfaceT& {
12380 return *getInternal();
12395 RegistryHub() =
default;
12396 IReporterRegistry
const& getReporterRegistry()
const override {
12397 return m_reporterRegistry;
12400 return m_testCaseRegistry;
12403 return m_exceptionTranslatorRegistry;
12405 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
12406 return m_tagAliasRegistry;
12408 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12409 return m_exceptionRegistry;
12413 void registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory )
override {
12414 m_reporterRegistry.registerReporter( name, factory );
12417 m_reporterRegistry.registerListener( factory );
12419 void registerTest(
TestCase const& testInfo )
override {
12420 m_testCaseRegistry.registerTest( testInfo );
12423 m_exceptionTranslatorRegistry.registerTranslator( translator );
12425 void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo )
override {
12426 m_tagAliasRegistry.add( alias, tag, lineInfo );
12428 void registerStartupException() noexcept
override {
12429 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 12430 m_exceptionRegistry.add(std::current_exception());
12432 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12436 return m_enumValuesRegistry;
12440 TestRegistry m_testCaseRegistry;
12441 ReporterRegistry m_reporterRegistry;
12442 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12443 TagAliasRegistry m_tagAliasRegistry;
12444 StartupExceptionRegistry m_exceptionRegistry;
12445 Detail::EnumValuesRegistry m_enumValuesRegistry;
12449 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12452 return RegistryHubSingleton::get();
12455 return RegistryHubSingleton::getMutable();
12458 cleanupSingletons();
12471 ReporterRegistry::~ReporterRegistry() =
default;
12473 IStreamingReporterPtr ReporterRegistry::create( std::string
const& name,
IConfigPtr const& config )
const {
12474 auto it = m_factories.find( name );
12475 if( it == m_factories.end() )
12477 return it->second->create( ReporterConfig( config ) );
12480 void ReporterRegistry::registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory ) {
12481 m_factories.emplace(name, factory);
12484 m_listeners.push_back( factory );
12487 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12488 return m_factories;
12490 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12491 return m_listeners;
12519 #include <algorithm> 12524 namespace Generators {
12528 GeneratorTracker( TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12529 : TrackerBase( nameAndLocation, ctx, parent )
12531 ~GeneratorTracker();
12533 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation
const& nameAndLocation ) {
12534 std::shared_ptr<GeneratorTracker> tracker;
12536 ITracker& currentTracker = ctx.currentTracker();
12548 if (currentTracker.nameAndLocation() == nameAndLocation) {
12549 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12550 assert(thisTracker);
12551 assert(thisTracker->isGeneratorTracker());
12552 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12553 }
else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12554 assert( childTracker );
12555 assert( childTracker->isGeneratorTracker() );
12556 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12558 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12559 currentTracker.addChild( tracker );
12562 if( !tracker->isComplete() ) {
12570 bool isGeneratorTracker()
const override {
return true; }
12571 auto hasGenerator()
const ->
bool override {
12572 return !!m_generator;
12574 void close()
override {
12575 TrackerBase::close();
12583 const bool should_wait_for_child =
12584 !m_children.empty() &&
12585 std::find_if( m_children.begin(),
12587 []( TestCaseTracking::ITrackerPtr tracker ) {
12588 return tracker->hasStarted();
12589 } ) == m_children.end();
12595 if ( should_wait_for_child ||
12596 ( m_runState == CompletedSuccessfully &&
12597 m_generator->next() ) ) {
12598 m_children.clear();
12599 m_runState = Executing;
12605 return m_generator;
12608 m_generator = std::move( generator );
12611 GeneratorTracker::~GeneratorTracker() {}
12614 RunContext::RunContext(
IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12615 : m_runInfo(_config->name()),
12618 m_reporter(std::move(reporter)),
12620 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12622 m_context.setRunner(
this);
12623 m_context.setConfig(m_config);
12624 m_context.setResultCapture(
this);
12625 m_reporter->testRunStarting(m_runInfo);
12628 RunContext::~RunContext() {
12629 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12632 void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12633 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12636 void RunContext::testGroupEnded(std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12637 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12641 Totals prevTotals = m_totals;
12643 std::string redirectedCout;
12644 std::string redirectedCerr;
12648 m_reporter->testCaseStarting(testInfo);
12650 m_activeTestCase = &testCase;
12652 ITracker& rootTracker = m_trackerContext.startRun();
12653 assert(rootTracker.isSectionTracker());
12654 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12656 m_trackerContext.startCycle();
12657 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12658 runCurrentTest(redirectedCout, redirectedCerr);
12659 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12667 m_totals.testCases += deltaTotals.
testCases;
12668 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12674 m_activeTestCase =
nullptr;
12675 m_testCaseTracker =
nullptr;
12677 return deltaTotals;
12684 IStreamingReporter& RunContext::reporter()
const {
12685 return *m_reporter;
12688 void RunContext::assertionEnded(AssertionResult
const & result) {
12691 m_lastAssertionPassed =
true;
12692 }
else if (!result.isOk()) {
12693 m_lastAssertionPassed =
false;
12694 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12695 m_totals.assertions.failedButOk++;
12697 m_totals.assertions.failed++;
12700 m_lastAssertionPassed =
true;
12705 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12708 m_messageScopes.clear();
12711 resetAssertionInfo();
12712 m_lastResult = result;
12714 void RunContext::resetAssertionInfo() {
12715 m_lastAssertionInfo.macroName =
StringRef();
12716 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12719 bool RunContext::sectionStarted(
SectionInfo const & sectionInfo,
Counts & assertions) {
12720 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.
name, sectionInfo.
lineInfo));
12721 if (!sectionTracker.isOpen())
12723 m_activeSections.push_back(§ionTracker);
12725 m_lastAssertionInfo.lineInfo = sectionInfo.
lineInfo;
12727 m_reporter->sectionStarting(sectionInfo);
12729 assertions = m_totals.assertions;
12734 using namespace Generators;
12735 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12736 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12737 m_lastAssertionInfo.lineInfo = lineInfo;
12741 bool RunContext::testForMissingAssertions(
Counts& assertions) {
12742 if (assertions.
total() != 0)
12744 if (!m_config->warnAboutMissingAssertions())
12746 if (m_trackerContext.currentTracker().hasChildren())
12748 m_totals.assertions.failed++;
12755 bool missingAssertions = testForMissingAssertions(assertions);
12757 if (!m_activeSections.empty()) {
12758 m_activeSections.back()->close();
12759 m_activeSections.pop_back();
12763 m_messages.clear();
12764 m_messageScopes.clear();
12767 void RunContext::sectionEndedEarly(
SectionEndInfo const & endInfo) {
12768 if (m_unfinishedSections.empty())
12769 m_activeSections.back()->fail();
12771 m_activeSections.back()->close();
12772 m_activeSections.pop_back();
12774 m_unfinishedSections.push_back(endInfo);
12777 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 12778 void RunContext::benchmarkPreparing(std::string
const& name) {
12779 m_reporter->benchmarkPreparing(name);
12781 void RunContext::benchmarkStarting( BenchmarkInfo
const& info ) {
12782 m_reporter->benchmarkStarting( info );
12784 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12785 m_reporter->benchmarkEnded( stats );
12787 void RunContext::benchmarkFailed(std::string
const & error) {
12788 m_reporter->benchmarkFailed(error);
12790 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 12792 void RunContext::pushScopedMessage(
MessageInfo const & message) {
12793 m_messages.push_back(message);
12796 void RunContext::popScopedMessage(
MessageInfo const & message) {
12797 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12800 void RunContext::emplaceUnscopedMessage(
MessageBuilder const& builder ) {
12801 m_messageScopes.emplace_back( builder );
12804 std::string RunContext::getCurrentTestName()
const {
12805 return m_activeTestCase
12806 ? m_activeTestCase->getTestCaseInfo().name
12810 const AssertionResult * RunContext::getLastResult()
const {
12811 return &(*m_lastResult);
12814 void RunContext::exceptionEarlyReported() {
12815 m_shouldReportUnexpected =
false;
12818 void RunContext::handleFatalErrorCondition(
StringRef message ) {
12820 m_reporter->fatalErrorEncountered(message);
12825 tempResult.message =
static_cast<std::string
>(message);
12826 AssertionResult result(m_lastAssertionInfo, tempResult);
12828 assertionEnded(result);
12830 handleUnfinishedSections();
12833 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12834 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12838 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12839 m_reporter->sectionEnded(testCaseSectionStats);
12841 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12846 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12851 m_totals.testCases.failed++;
12852 testGroupEnded(std::string(), m_totals, 1, 1);
12853 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12856 bool RunContext::lastAssertionPassed() {
12857 return m_lastAssertionPassed;
12860 void RunContext::assertionPassed() {
12861 m_lastAssertionPassed =
true;
12862 ++m_totals.assertions.passed;
12863 resetAssertionInfo();
12864 m_messageScopes.clear();
12867 bool RunContext::aborting()
const {
12868 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12871 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12872 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12873 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12874 m_reporter->sectionStarting(testCaseSection);
12875 Counts prevAssertions = m_totals.assertions;
12876 double duration = 0;
12877 m_shouldReportUnexpected =
true;
12880 seedRng(*m_config);
12884 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12885 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 12886 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12889 invokeActiveTestCase();
12891 OutputRedirect r(redirectedCout, redirectedCerr);
12893 invokeActiveTestCase();
12897 invokeActiveTestCase();
12905 if( m_shouldReportUnexpected ) {
12910 Counts assertions = m_totals.assertions - prevAssertions;
12911 bool missingAssertions = testForMissingAssertions(assertions);
12913 m_testCaseTracker->close();
12914 handleUnfinishedSections();
12915 m_messages.clear();
12916 m_messageScopes.clear();
12918 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
12919 m_reporter->sectionEnded(testCaseSectionStats);
12922 void RunContext::invokeActiveTestCase() {
12923 FatalConditionHandler fatalConditionHandler;
12924 m_activeTestCase->invoke();
12925 fatalConditionHandler.reset();
12928 void RunContext::handleUnfinishedSections() {
12931 for (
auto it = m_unfinishedSections.rbegin(),
12932 itEnd = m_unfinishedSections.rend();
12936 m_unfinishedSections.clear();
12939 void RunContext::handleExpr(
12944 m_reporter->assertionStarting( info );
12947 bool result = expr.
getResult() != negated;
12950 if (!m_includeSuccessfulResults) {
12959 populateReaction( reaction );
12962 void RunContext::reportExpr(
12968 m_lastAssertionInfo = info;
12969 AssertionResultData data( resultType,
LazyExpression( negated ) );
12971 AssertionResult assertionResult{ info, data };
12972 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
12974 assertionEnded( assertionResult );
12977 void RunContext::handleMessage(
12983 m_reporter->assertionStarting( info );
12985 m_lastAssertionInfo = info;
12987 AssertionResultData data( resultType,
LazyExpression(
false ) );
12988 data.message =
static_cast<std::string
>(message);
12989 AssertionResult assertionResult{ m_lastAssertionInfo, data };
12990 assertionEnded( assertionResult );
12991 if( !assertionResult.isOk() )
12992 populateReaction( reaction );
12994 void RunContext::handleUnexpectedExceptionNotThrown(
13001 void RunContext::handleUnexpectedInflightException(
13003 std::string
const& message,
13006 m_lastAssertionInfo = info;
13009 data.message = message;
13010 AssertionResult assertionResult{ info, data };
13011 assertionEnded( assertionResult );
13012 populateReaction( reaction );
13020 void RunContext::handleIncomplete(
13023 m_lastAssertionInfo = info;
13026 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13027 AssertionResult assertionResult{ info, data };
13028 assertionEnded( assertionResult );
13030 void RunContext::handleNonExpr(
13035 m_lastAssertionInfo = info;
13037 AssertionResultData data( resultType,
LazyExpression(
false ) );
13038 AssertionResult assertionResult{ info, data };
13039 assertionEnded( assertionResult );
13041 if( !assertionResult.isOk() )
13042 populateReaction( reaction );
13052 void seedRng(
IConfig const& config) {
13054 std::srand(config.
rngSeed());
13071 m_sectionIncluded(
getResultCapture().sectionStarted( m_info, m_assertions ) )
13077 if( m_sectionIncluded ) {
13078 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13079 if( uncaught_exceptions() )
13087 Section::operator bool()
const {
13088 return m_sectionIncluded;
13099 std::string
const& _name )
13101 lineInfo( _lineInfo )
13118 ~Session()
override;
13120 void showHelp()
const;
13121 void libIdentify();
13123 int applyCommandLine(
int argc,
char const *
const * argv );
13124 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13125 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13128 void useConfigData( ConfigData
const& configData );
13130 template<
typename CharT>
13131 int run(
int argc, CharT
const *
const argv[]) {
13132 if (m_startupExceptions)
13134 int returnCode = applyCommandLine(argc, argv);
13135 if (returnCode == 0)
13136 returnCode = run();
13142 clara::Parser
const& cli()
const;
13143 void cli( clara::Parser
const& newParser );
13144 ConfigData& configData();
13149 clara::Parser m_cli;
13150 ConfigData m_configData;
13151 std::shared_ptr<Config> m_config;
13152 bool m_startupExceptions =
false;
13166 Version( Version
const& ) =
delete;
13167 Version& operator=( Version
const& ) =
delete;
13168 Version(
unsigned int _majorVersion,
13169 unsigned int _minorVersion,
13170 unsigned int _patchNumber,
13171 char const *
const _branchName,
13172 unsigned int _buildNumber );
13174 unsigned int const majorVersion;
13175 unsigned int const minorVersion;
13176 unsigned int const patchNumber;
13179 char const *
const branchName;
13180 unsigned int const buildNumber;
13182 friend std::ostream&
operator << ( std::ostream& os, Version
const& version );
13185 Version
const& libraryVersion();
13192 #include <iterator> 13197 const int MaxExitCode = 255;
13199 IStreamingReporterPtr createReporter(std::string
const& reporterName,
IConfigPtr const& config) {
13201 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13206 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13208 return createReporter(config->getReporterName(), config);
13216 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13217 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13219 for (
auto const& listener : listeners) {
13220 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13222 multi.addReporter(createReporter(config->getReporterName(), config));
13228 explicit TestGroup(std::shared_ptr<Config>
const& config)
13230 , m_context{config, makeReporter(config)}
13233 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13234 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13236 if (m_matches.empty() && invalidArgs.empty()) {
13237 for (
auto const& test : allTestCases)
13238 if (!test.isHidden())
13239 m_tests.emplace(&test);
13241 for (
auto const& match : m_matches)
13242 m_tests.insert(match.tests.begin(), match.tests.end());
13247 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13249 m_context.testGroupStarting(m_config->name(), 1, 1);
13250 for (
auto const& testCase : m_tests) {
13251 if (!m_context.aborting())
13252 totals += m_context.runTest(*testCase);
13254 m_context.reporter().skipTest(*testCase);
13257 for (
auto const& match : m_matches) {
13258 if (match.tests.empty()) {
13259 m_context.reporter().noMatchingTestCases(match.name);
13264 if (!invalidArgs.empty()) {
13265 for (
auto const& invalidArg: invalidArgs)
13266 m_context.reporter().reportInvalidArguments(invalidArg);
13269 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13274 using Tests = std::set<TestCase const*>;
13276 std::shared_ptr<Config> m_config;
13277 RunContext m_context;
13284 for (
auto& testCase : tests) {
13285 auto tags = testCase.tags;
13287 std::string filename = testCase.lineInfo.file;
13288 auto lastSlash = filename.find_last_of(
"\\/");
13289 if (lastSlash != std::string::npos) {
13290 filename.erase(0, lastSlash);
13294 auto lastDot = filename.find_last_of(
'.');
13295 if (lastDot != std::string::npos) {
13296 filename.erase(lastDot);
13299 tags.push_back(std::move(filename));
13300 setTags(testCase, tags);
13306 Session::Session() {
13307 static bool alreadyInstantiated =
false;
13308 if( alreadyInstantiated ) {
13314 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13320 m_startupExceptions =
true;
13321 Colour colourGuard( Colour::Red );
13322 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13326 std::rethrow_exception(ex_ptr);
13327 }
catch ( std::exception
const& ex ) {
13328 Catch::cerr() << Column( ex.what() ).indent(2) <<
'\n';
13334 alreadyInstantiated =
true;
13335 m_cli = makeCommandLineParser( m_configData );
13337 Session::~Session() {
13341 void Session::showHelp()
const {
13343 <<
"\nCatch v" << libraryVersion() <<
"\n" 13344 << m_cli << std::endl
13345 <<
"For more detailed usage please see the project docs\n" << std::endl;
13347 void Session::libIdentify() {
13349 << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n" 13350 << std::left << std::setw(16) <<
"category: " <<
"testframework\n" 13351 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n" 13352 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13355 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13356 if( m_startupExceptions )
13359 auto result = m_cli.parse( clara::Args( argc, argv ) );
13364 << Colour( Colour::Red )
13365 <<
"\nError(s) in input:\n" 13366 << Column( result.errorMessage() ).indent( 2 )
13368 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13369 return MaxExitCode;
13372 if( m_configData.showHelp )
13374 if( m_configData.libIdentify )
13380 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13381 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13383 char **utf8Argv =
new char *[ argc ];
13385 for (
int i = 0; i < argc; ++i ) {
13386 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr );
13388 utf8Argv[ i ] =
new char[ bufSize ];
13390 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13393 int returnCode = applyCommandLine( argc, utf8Argv );
13395 for (
int i = 0; i < argc; ++i )
13396 delete [] utf8Argv[ i ];
13398 delete [] utf8Argv;
13404 void Session::useConfigData( ConfigData
const& configData ) {
13405 m_configData = configData;
13409 int Session::run() {
13411 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13412 static_cast<void>(std::getchar());
13414 int exitCode = runInternal();
13416 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13417 static_cast<void>(std::getchar());
13422 clara::Parser
const& Session::cli()
const {
13425 void Session::cli( clara::Parser
const& newParser ) {
13428 ConfigData& Session::configData() {
13429 return m_configData;
13431 Config& Session::config() {
13433 m_config = std::make_shared<Config>( m_configData );
13437 int Session::runInternal() {
13438 if( m_startupExceptions )
13441 if (m_configData.showHelp || m_configData.libIdentify) {
13448 seedRng( *m_config );
13450 if( m_configData.filenamesAsTags )
13451 applyFilenamesAsTags( *m_config );
13455 return static_cast<int>( *listed );
13457 TestGroup tests { m_config };
13458 auto const totals = tests.execute();
13460 if( m_config->warnAboutNoTests() && totals.error == -1 )
13466 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13468 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13469 catch( std::exception& ex ) {
13471 return MaxExitCode;
13485 static auto getSingletons() -> std::vector<ISingleton*>*& {
13486 static std::vector<ISingleton*>* g_singletons =
nullptr;
13487 if( !g_singletons )
13488 g_singletons =
new std::vector<ISingleton*>();
13489 return g_singletons;
13493 ISingleton::~ISingleton() {}
13495 void addSingleton(ISingleton* singleton ) {
13496 getSingletons()->push_back( singleton );
13498 void cleanupSingletons() {
13499 auto& singletons = getSingletons();
13500 for(
auto singleton : *singletons )
13503 singletons =
nullptr;
13510 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13514 m_exceptions.push_back(exception);
13521 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions()
const noexcept {
13522 return m_exceptions;
13531 #include <iostream> 13541 namespace Detail {
namespace {
13542 template<
typename WriterF, std::
size_t bufferSize=256>
13543 class StreamBufImpl :
public std::streambuf {
13544 char data[bufferSize];
13549 setp( data, data +
sizeof(data) );
13552 ~StreamBufImpl() noexcept {
13553 StreamBufImpl::sync();
13557 int overflow(
int c )
override {
13561 if( pbase() == epptr() )
13562 m_writer( std::string( 1, static_cast<char>( c ) ) );
13564 sputc( static_cast<char>( c ) );
13569 int sync()
override {
13570 if( pbase() != pptr() ) {
13571 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13572 setp( pbase(), epptr() );
13580 struct OutputDebugWriter {
13582 void operator()( std::string
const&
str ) {
13583 writeToDebugConsole( str );
13589 class FileStream :
public IStream {
13590 mutable std::ofstream m_ofs;
13593 m_ofs.open( filename.
c_str() );
13594 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13596 ~FileStream()
override =
default;
13598 std::ostream& stream()
const override {
13605 class CoutStream :
public IStream {
13606 mutable std::ostream m_os;
13611 ~CoutStream()
override =
default;
13614 std::ostream& stream()
const override {
return m_os; }
13619 class DebugOutStream :
public IStream {
13620 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13621 mutable std::ostream m_os;
13624 : m_streamBuf(
new StreamBufImpl<OutputDebugWriter>() ),
13625 m_os( m_streamBuf.get() )
13628 ~DebugOutStream()
override =
default;
13631 std::ostream& stream()
const override {
return m_os; }
13639 if( filename.
empty() )
13640 return new Detail::CoutStream();
13641 else if( filename[0] ==
'%' ) {
13642 if( filename ==
"%debug" )
13643 return new Detail::DebugOutStream();
13645 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13648 return new Detail::FileStream( filename );
13652 struct StringStreams {
13653 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13654 std::vector<std::size_t> m_unused;
13655 std::ostringstream m_referenceStream;
13657 auto add() -> std::size_t {
13658 if( m_unused.empty() ) {
13659 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13660 return m_streams.size()-1;
13663 auto index = m_unused.back();
13664 m_unused.pop_back();
13669 void release( std::size_t index ) {
13670 m_streams[index]->copyfmt( m_referenceStream );
13671 m_unused.push_back(index);
13676 : m_index( Singleton<StringStreams>::getMutable().
add() ),
13677 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].
get() )
13681 static_cast<std::ostringstream*
>( m_oss )->
str(
"");
13683 Singleton<StringStreams>::getMutable().release( m_index );
13687 return static_cast<std::ostringstream*
>( m_oss )->
str();
13692 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions 13701 #include <algorithm> 13710 char toLowerCh(
char c) {
13711 return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13715 bool startsWith( std::string
const& s, std::string
const& prefix ) {
13716 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13718 bool startsWith( std::string
const& s,
char prefix ) {
13719 return !s.empty() && s[0] == prefix;
13721 bool endsWith( std::string
const& s, std::string
const& suffix ) {
13722 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13724 bool endsWith( std::string
const& s,
char suffix ) {
13725 return !s.empty() && s[s.size()-1] == suffix;
13727 bool contains( std::string
const& s, std::string
const& infix ) {
13728 return s.find( infix ) != std::string::npos;
13731 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13733 std::string
toLower( std::string
const& s ) {
13734 std::string lc = s;
13738 std::string
trim( std::string
const&
str ) {
13739 static char const* whitespaceChars =
"\n\r\t ";
13740 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13741 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13743 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13747 const auto is_ws = [](
char c) {
13748 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r';
13750 size_t real_begin = 0;
13751 while (real_begin < ref.
size() && is_ws(ref[real_begin])) { ++real_begin; }
13752 size_t real_end = ref.
size();
13753 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13755 return ref.
substr(real_begin, real_end - real_begin);
13758 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
13759 bool replaced =
false;
13760 std::size_t i = str.find( replaceThis );
13761 while( i != std::string::npos ) {
13763 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13764 if( i < str.size()-withThis.size() )
13765 i = str.find( replaceThis, i+withThis.size() );
13767 i = std::string::npos;
13773 std::vector<StringRef> subStrings;
13774 std::size_t start = 0;
13775 for(std::size_t pos = 0; pos < str.
size(); ++pos ) {
13776 if( str[pos] == delimiter ) {
13777 if( pos - start > 1 )
13778 subStrings.push_back( str.
substr( start, pos-start ) );
13782 if( start < str.
size() )
13783 subStrings.push_back( str.
substr( start, str.
size()-start ) );
13788 : m_count( count ),
13794 if( pluraliser.
m_count != 1 )
13803 #include <algorithm> 13810 :
StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13814 CATCH_ENFORCE(isNullTerminated(),
"Called StringRef::c_str() on a non-null-terminated instance");
13822 if (start < m_size) {
13823 return StringRef(m_start + start, (std::min)(m_size - start, size));
13829 return m_size == other.m_size
13830 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13834 return os.write(str.
data(), str.
size());
13838 lhs.append(rhs.
data(), rhs.
size());
13847 TagAlias::TagAlias(std::string
const & _tag,
SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13871 TagAliasRegistry::~TagAliasRegistry() {}
13873 TagAlias
const* TagAliasRegistry::find( std::string
const& alias )
const {
13874 auto it = m_registry.find( alias );
13875 if( it != m_registry.end() )
13876 return &(it->second);
13881 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
13882 std::string expandedTestSpec = unexpandedTestSpec;
13883 for(
auto const& registryKvp : m_registry ) {
13884 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13885 if( pos != std::string::npos ) {
13886 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13887 registryKvp.second.tag +
13888 expandedTestSpec.substr( pos + registryKvp.first.size() );
13891 return expandedTestSpec;
13896 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
13898 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13899 "error: tag alias, '" << alias <<
"' already registered.\n" 13900 <<
"\tFirst seen at: " << find(alias)->lineInfo <<
"\n" 13901 <<
"\tRedefined at: " << lineInfo );
13904 ITagAliasRegistry::~ITagAliasRegistry() {}
13906 ITagAliasRegistry
const& ITagAliasRegistry::get() {
13915 #include <exception> 13916 #include <algorithm> 13926 else if( tag ==
"!throws" )
13928 else if( tag ==
"!shouldfail" )
13930 else if( tag ==
"!mayfail" )
13932 else if( tag ==
"!nonportable" )
13934 else if( tag ==
"!benchmark" )
13939 bool isReservedTag( std::string
const& tag ) {
13940 return parseSpecialTag( tag ) ==
TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
13942 void enforceNotReservedTag( std::string
const& tag,
SourceLineInfo const& _lineInfo ) {
13944 "Tag name: [" << tag <<
"] is not allowed.\n" 13945 <<
"Tag names starting with non alphanumeric characters are reserved\n" 13951 std::string
const& _className,
13955 bool isHidden =
false;
13958 std::vector<std::string> tags;
13959 std::string desc, tag;
13960 bool inTag =
false;
13961 for (
char c : nameAndTags.
tags) {
13974 enforceNotReservedTag( tag, _lineInfo );
13979 if (
startsWith(tag,
'.') && tag.size() > 1) {
13982 tags.push_back( tag );
13992 tags.insert( tags.end(), {
".",
"!hide" } );
13995 TestCaseInfo info( static_cast<std::string>(nameAndTags.
name), _className, desc, tags, _lineInfo );
13996 return TestCase( _testCase, std::move(info) );
13999 void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14000 std::sort(begin(tags), end(tags));
14001 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14004 for(
auto const& tag : tags ) {
14005 std::string lcaseTag =
toLower( tag );
14007 testCaseInfo.
lcaseTags.push_back( lcaseTag );
14009 testCaseInfo.
tags = std::move(tags);
14013 std::string
const& _className,
14014 std::string
const& _description,
14015 std::vector<std::string>
const& _tags,
14018 className( _className ),
14019 description( _description ),
14020 lineInfo( _lineInfo ),
14023 setTags( *
this, _tags );
14027 return ( properties & IsHidden ) != 0;
14030 return ( properties & Throws ) != 0;
14033 return ( properties & (ShouldFail | MayFail ) ) != 0;
14036 return ( properties & (ShouldFail ) ) != 0;
14042 std::size_t full_size = 2 * tags.size();
14043 for (
const auto& tag : tags) {
14044 full_size += tag.size();
14046 ret.reserve(full_size);
14047 for (
const auto& tag : tags) {
14048 ret.push_back(
'[');
14050 ret.push_back(
']');
14060 other.
name = _newName;
14069 return test.get() == other.test.get() &&
14070 name == other.
name &&
14075 return name < other.
name;
14087 #include <algorithm> 14093 struct TestHasher {
14102 uint64_t operator()(
TestCase const& t)
const {
14104 static constexpr uint64_t prime = 1099511628211;
14105 uint64_t hash = basis;
14106 for (
const char c : t.
name) {
14115 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases ) {
14122 std::vector<TestCase> sorted = unsortedTestCases;
14123 std::sort( sorted.begin(), sorted.end() );
14129 TestHasher h(
rng() );
14131 using hashedTest = std::pair<uint64_t, TestCase const*>;
14132 std::vector<hashedTest> indexed_tests;
14133 indexed_tests.reserve( unsortedTestCases.size() );
14135 for (
auto const& testCase : unsortedTestCases) {
14136 indexed_tests.emplace_back(h(testCase), &testCase);
14139 std::sort(indexed_tests.begin(), indexed_tests.end(),
14140 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14141 if (lhs.first == rhs.first) {
14142 return lhs.second->name < rhs.second->name;
14144 return lhs.first < rhs.first;
14147 std::vector<TestCase> sorted;
14148 sorted.reserve( indexed_tests.size() );
14150 for (
auto const& hashed : indexed_tests) {
14151 sorted.emplace_back(*hashed.second);
14157 return unsortedTestCases;
14165 return testSpec.matches( testCase ) &&
isThrowSafe( testCase, config );
14168 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14169 std::set<TestCase> seenFunctions;
14170 for(
auto const&
function : functions ) {
14171 auto prev = seenFunctions.insert(
function );
14173 "error: TEST_CASE( \"" <<
function.name <<
"\" ) already defined.\n" 14174 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n" 14175 <<
"\tRedefined at " <<
function.getTestCaseInfo().lineInfo );
14179 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config ) {
14180 std::vector<TestCase> filtered;
14181 filtered.reserve( testCases.size() );
14182 for (
auto const& testCase : testCases) {
14183 if ((!testSpec.hasFilters() && !testCase.
isHidden()) ||
14184 (testSpec.hasFilters() &&
matchTest(testCase, testSpec, config))) {
14185 filtered.push_back(testCase);
14194 void TestRegistry::registerTest(
TestCase const& testCase ) {
14196 if( name.empty() ) {
14198 rss <<
"Anonymous test case " << ++m_unnamedCount;
14199 return registerTest( testCase.
withName( rss.
str() ) );
14201 m_functions.push_back( testCase );
14204 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14205 return m_functions;
14207 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted(
IConfig const& config )
const {
14208 if( m_sortedFunctions.empty() )
14209 enforceNoDuplicateTestCases( m_functions );
14211 if( m_currentSortOrder != config.
runOrder() || m_sortedFunctions.empty() ) {
14212 m_sortedFunctions = sortTests( config, m_functions );
14213 m_currentSortOrder = config.
runOrder();
14215 return m_sortedFunctions;
14219 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14221 void TestInvokerAsFunction::invoke()
const {
14222 m_testAsFunction();
14225 std::string extractClassName(
StringRef const& classOrQualifiedMethodName ) {
14226 std::string className(classOrQualifiedMethodName);
14229 std::size_t lastColons = className.rfind(
"::" );
14230 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14231 if( penultimateColons == std::string::npos )
14232 penultimateColons = 1;
14233 className = className.substr( penultimateColons, lastColons-penultimateColons );
14242 #include <algorithm> 14244 #include <stdexcept> 14248 #if defined(__clang__) 14249 # pragma clang diagnostic push 14250 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14254 namespace TestCaseTracking {
14256 NameAndLocation::NameAndLocation( std::string
const& _name,
SourceLineInfo const& _location )
14258 location( _location )
14261 ITracker::~ITracker() =
default;
14263 ITracker& TrackerContext::startRun() {
14264 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}",
CATCH_INTERNAL_LINEINFO ), *
this, nullptr );
14265 m_currentTracker =
nullptr;
14266 m_runState = Executing;
14267 return *m_rootTracker;
14270 void TrackerContext::endRun() {
14271 m_rootTracker.reset();
14272 m_currentTracker =
nullptr;
14273 m_runState = NotStarted;
14276 void TrackerContext::startCycle() {
14277 m_currentTracker = m_rootTracker.get();
14278 m_runState = Executing;
14280 void TrackerContext::completeCycle() {
14281 m_runState = CompletedCycle;
14284 bool TrackerContext::completedCycle()
const {
14285 return m_runState == CompletedCycle;
14287 ITracker& TrackerContext::currentTracker() {
14288 return *m_currentTracker;
14290 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14291 m_currentTracker = tracker;
14294 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14295 ITracker(nameAndLocation),
14300 bool TrackerBase::isComplete()
const {
14301 return m_runState == CompletedSuccessfully || m_runState == Failed;
14303 bool TrackerBase::isSuccessfullyCompleted()
const {
14304 return m_runState == CompletedSuccessfully;
14306 bool TrackerBase::isOpen()
const {
14307 return m_runState != NotStarted && !isComplete();
14309 bool TrackerBase::hasChildren()
const {
14310 return !m_children.empty();
14313 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14314 m_children.push_back( child );
14317 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14318 auto it = std::find_if( m_children.begin(), m_children.end(),
14319 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14321 tracker->nameAndLocation().location == nameAndLocation.location &&
14322 tracker->nameAndLocation().name == nameAndLocation.name;
14324 return( it != m_children.end() )
14328 ITracker& TrackerBase::parent() {
14329 assert( m_parent );
14333 void TrackerBase::openChild() {
14334 if( m_runState != ExecutingChildren ) {
14335 m_runState = ExecutingChildren;
14337 m_parent->openChild();
14341 bool TrackerBase::isSectionTracker()
const {
return false; }
14342 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14344 void TrackerBase::open() {
14345 m_runState = Executing;
14348 m_parent->openChild();
14351 void TrackerBase::close() {
14354 while( &m_ctx.currentTracker() != this )
14355 m_ctx.currentTracker().close();
14357 switch( m_runState ) {
14358 case NeedsAnotherRun:
14362 m_runState = CompletedSuccessfully;
14364 case ExecutingChildren:
14365 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const& t){
return t->isComplete(); }) )
14366 m_runState = CompletedSuccessfully;
14370 case CompletedSuccessfully:
14378 m_ctx.completeCycle();
14380 void TrackerBase::fail() {
14381 m_runState = Failed;
14383 m_parent->markAsNeedingAnotherRun();
14385 m_ctx.completeCycle();
14387 void TrackerBase::markAsNeedingAnotherRun() {
14388 m_runState = NeedsAnotherRun;
14391 void TrackerBase::moveToParent() {
14392 assert( m_parent );
14393 m_ctx.setCurrentTracker( m_parent );
14395 void TrackerBase::moveToThis() {
14396 m_ctx.setCurrentTracker(
this );
14399 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14400 : TrackerBase( nameAndLocation, ctx, parent ),
14401 m_trimmed_name(
trim(nameAndLocation.name))
14404 while( !parent->isSectionTracker() )
14405 parent = &parent->parent();
14407 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14408 addNextFilters( parentSection.m_filters );
14412 bool SectionTracker::isComplete()
const {
14413 bool complete =
true;
14415 if (m_filters.empty()
14416 || m_filters[0] ==
"" 14417 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14418 complete = TrackerBase::isComplete();
14423 bool SectionTracker::isSectionTracker()
const {
return true; }
14425 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14426 std::shared_ptr<SectionTracker> section;
14428 ITracker& currentTracker = ctx.currentTracker();
14429 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14430 assert( childTracker );
14431 assert( childTracker->isSectionTracker() );
14432 section = std::static_pointer_cast<SectionTracker>( childTracker );
14435 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14436 currentTracker.addChild( section );
14438 if( !ctx.completedCycle() )
14439 section->tryOpen();
14443 void SectionTracker::tryOpen() {
14444 if( !isComplete() )
14448 void SectionTracker::addInitialFilters( std::vector<std::string>
const& filters ) {
14449 if( !filters.empty() ) {
14450 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14451 m_filters.emplace_back(
"");
14452 m_filters.emplace_back(
"");
14453 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14456 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14457 if( filters.size() > 1 )
14458 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14463 using TestCaseTracking::ITracker;
14464 using TestCaseTracking::TrackerContext;
14465 using TestCaseTracking::SectionTracker;
14469 #if defined(__clang__) 14470 # pragma clang diagnostic pop 14478 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14489 extractClassName( classOrMethod ),
14503 #include <algorithm> 14510 TestSpec::Pattern::Pattern( std::string
const& name )
14514 TestSpec::Pattern::~Pattern() =
default;
14516 std::string
const& TestSpec::Pattern::name()
const {
14520 TestSpec::NamePattern::NamePattern( std::string
const& name, std::string
const& filterString )
14521 : Pattern( filterString )
14525 bool TestSpec::NamePattern::matches(
TestCaseInfo const& testCase )
const {
14526 return m_wildcardPattern.matches( testCase.
name );
14529 TestSpec::TagPattern::TagPattern( std::string
const& tag, std::string
const& filterString )
14530 : Pattern( filterString )
14534 bool TestSpec::TagPattern::matches(
TestCaseInfo const& testCase )
const {
14535 return std::find(begin(testCase.
lcaseTags),
14540 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14541 : Pattern( underlyingPattern->name() )
14542 , m_underlyingPattern( underlyingPattern )
14545 bool TestSpec::ExcludedPattern::matches(
TestCaseInfo const& testCase )
const {
14546 return !m_underlyingPattern->matches( testCase );
14549 bool TestSpec::Filter::matches(
TestCaseInfo const& testCase )
const {
14550 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const& p ){
return p->matches( testCase ); } );
14553 std::string TestSpec::Filter::name()
const {
14555 for(
auto const& p : m_patterns )
14560 bool TestSpec::hasFilters()
const {
14561 return !m_filters.empty();
14564 bool TestSpec::matches(
TestCaseInfo const& testCase )
const {
14565 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const& f ){
return f.matches( testCase ); } );
14568 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const 14570 Matches matches( m_filters.size() );
14571 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter
const&
filter ){
14572 std::vector<TestCase const*> currentMatches;
14573 for(
auto const& test : testCases )
14575 currentMatches.emplace_back( &test );
14576 return FilterMatch{
filter.name(), currentMatches };
14581 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14582 return (m_invalidArgs);
14591 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14595 m_exclusion =
false;
14596 m_arg = m_tagAliases->expandAliases( arg );
14597 m_escapeChars.clear();
14598 m_substring.reserve(m_arg.size());
14599 m_patternName.reserve(m_arg.size());
14600 m_realPatternPos = 0;
14602 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14604 if( !visitChar( m_arg[m_pos] ) ){
14605 m_testSpec.m_invalidArgs.push_back(arg);
14611 TestSpec TestSpecParser::testSpec() {
14615 bool TestSpecParser::visitChar(
char c ) {
14616 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14618 addCharToPattern(c);
14620 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14626 if( processNoneChar( c ) )
14630 processNameChar( c );
14634 addCharToPattern(c);
14639 if( processOtherChar( c ) )
14645 if( !isControlChar( c ) ) {
14646 m_patternName += c;
14647 m_realPatternPos++;
14653 bool TestSpecParser::processNoneChar(
char c ) {
14658 m_exclusion =
true;
14661 startNewMode( Tag );
14664 startNewMode( QuotedName );
14667 startNewMode( Name );
14671 void TestSpecParser::processNameChar(
char c ) {
14673 if( m_substring ==
"exclude:" )
14674 m_exclusion =
true;
14677 startNewMode( Tag );
14680 bool TestSpecParser::processOtherChar(
char c ) {
14681 if( !isControlChar( c ) )
14687 void TestSpecParser::startNewMode( Mode mode ) {
14690 void TestSpecParser::endMode() {
14694 return addNamePattern();
14696 return addTagPattern();
14698 revertBackToLastMode();
14702 return startNewMode( None );
14705 void TestSpecParser::escape() {
14707 m_mode = EscapedName;
14708 m_escapeChars.push_back(m_realPatternPos);
14710 bool TestSpecParser::isControlChar(
char c )
const {
14723 return c ==
'[' || c ==
']';
14727 void TestSpecParser::addFilter() {
14728 if( !m_currentFilter.m_patterns.empty() ) {
14729 m_testSpec.m_filters.push_back( m_currentFilter );
14730 m_currentFilter = TestSpec::Filter();
14734 void TestSpecParser::saveLastMode() {
14738 void TestSpecParser::revertBackToLastMode() {
14742 bool TestSpecParser::separate() {
14743 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14746 m_pos = m_arg.size();
14747 m_substring.clear();
14748 m_patternName.clear();
14749 m_realPatternPos = 0;
14757 std::string TestSpecParser::preprocessPattern() {
14758 std::string token = m_patternName;
14759 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14760 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14761 m_escapeChars.clear();
14763 m_exclusion =
true;
14764 token = token.substr(8);
14767 m_patternName.clear();
14768 m_realPatternPos = 0;
14773 void TestSpecParser::addNamePattern() {
14774 auto token = preprocessPattern();
14776 if (!token.empty()) {
14777 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14779 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14780 m_currentFilter.m_patterns.push_back(pattern);
14782 m_substring.clear();
14783 m_exclusion =
false;
14787 void TestSpecParser::addTagPattern() {
14788 auto token = preprocessPattern();
14790 if (!token.empty()) {
14793 if (token.size() > 1 && token[0] ==
'.') {
14794 token.erase(token.begin());
14795 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14797 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14799 m_currentFilter.m_patterns.push_back(pattern);
14802 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14805 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14807 m_currentFilter.m_patterns.push_back(pattern);
14809 m_substring.clear();
14810 m_exclusion =
false;
14814 TestSpec parseTestSpec( std::string
const& arg ) {
14815 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14824 static const uint64_t nanosecondsInSecond = 1000000000;
14829 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14833 auto estimateClockResolution() -> uint64_t {
14835 static const uint64_t iterations = 1000000;
14839 for( std::size_t i = 0; i < iterations; ++i ) {
14845 }
while( ticks == baseTicks );
14847 auto delta = ticks - baseTicks;
14853 if (ticks > startTime + 3 * nanosecondsInSecond) {
14854 return sum / ( i + 1u );
14860 return sum/iterations;
14864 static auto s_resolution = estimateClockResolution();
14865 return s_resolution;
14875 return getElapsedNanoseconds()/1000;
14878 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14881 return getElapsedMicroseconds()/1000000.0;
14888 #if defined(__clang__) 14889 # pragma clang diagnostic push 14890 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14891 # pragma clang diagnostic ignored "-Wglobal-constructors" 14895 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 14896 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 14906 const std::string unprintableString =
"{?}";
14909 const int hexThreshold = 255;
14911 struct Endianness {
14912 enum Arch { Big, Little };
14914 static Arch which() {
14918 auto value = *
reinterpret_cast<char*
>(&one);
14919 return value ? Little : Big;
14926 int i = 0, end =
static_cast<int>( size ), inc = 1;
14927 if( Endianness::which() == Endianness::Little ) {
14932 unsigned char const *bytes =
static_cast<unsigned char const *
>(object);
14934 rss <<
"0x" << std::setfill(
'0') << std::hex;
14935 for( ; i != end; i += inc )
14936 rss << std::setw(2) <<
static_cast<unsigned>(bytes[i]);
14941 template<
typename T>
14942 std::string fpToString( T
value,
int precision ) {
14943 if (Catch::isnan(value)) {
14948 rss << std::setprecision( precision )
14951 std::string d = rss.
str();
14952 std::size_t i = d.find_last_not_of(
'0' );
14953 if( i != std::string::npos && i != d.size()-1 ) {
14956 d = d.substr( 0, i+1 );
14969 return '"' + str +
'"';
14972 std::string s(
"\"");
14973 for (
char c : str) {
14990 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 15000 return{
"{null string}" };
15007 return{
"{null string}" };
15011 #ifdef CATCH_CONFIG_WCHAR 15014 s.reserve(wstr.size());
15015 for (
auto c : wstr) {
15016 s += (c <= 0xff) ? static_cast<char>(c) :
'?';
15021 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 15031 return{
"{null string}" };
15038 return{
"{null string}" };
15043 #if defined(CATCH_CONFIG_CPP17_BYTE) 15048 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 15059 if (value > Detail::hexThreshold) {
15060 rss <<
" (0x" << std::hex << value <<
')';
15074 if (value > Detail::hexThreshold) {
15075 rss <<
" (0x" << std::hex << value <<
')';
15081 return b ?
"true" :
"false";
15085 if (value ==
'\r') {
15087 }
else if (value ==
'\f') {
15089 }
else if (value ==
'\n') {
15091 }
else if (value ==
'\t') {
15093 }
else if (
'\0' <= value && value <
' ') {
15096 char chstr[] =
"' '";
15115 return fpToString(value, precision) +
'f';
15121 return fpToString(value, precision);
15124 std::string ratio_string<std::atto>::symbol() {
return "a"; }
15125 std::string ratio_string<std::femto>::symbol() {
return "f"; }
15126 std::string ratio_string<std::pico>::symbol() {
return "p"; }
15127 std::string ratio_string<std::nano>::symbol() {
return "n"; }
15128 std::string ratio_string<std::micro>::symbol() {
return "u"; }
15129 std::string ratio_string<std::milli>::symbol() {
return "m"; }
15133 #if defined(__clang__) 15134 # pragma clang diagnostic pop 15158 return passed + failed + failedButOk;
15161 return failed == 0 && failedButOk == 0;
15164 return failed == 0;
15181 Totals diff = *
this - prevTotals;
15195 #include <exception> 15198 bool uncaught_exceptions() {
15199 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 15201 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15202 return std::uncaught_exceptions() > 0;
15204 return std::uncaught_exception();
15216 (
unsigned int _majorVersion,
15217 unsigned int _minorVersion,
15218 unsigned int _patchNumber,
15219 char const *
const _branchName,
15220 unsigned int _buildNumber )
15221 : majorVersion( _majorVersion ),
15222 minorVersion( _minorVersion ),
15223 patchNumber( _patchNumber ),
15224 branchName( _branchName ),
15225 buildNumber( _buildNumber )
15228 std::ostream&
operator << ( std::ostream& os, Version
const& version ) {
15229 os << version.majorVersion <<
'.' 15230 << version.minorVersion <<
'.' 15231 << version.patchNumber;
15233 if (version.branchName[0]) {
15234 os <<
'-' << version.branchName
15235 <<
'.' << version.buildNumber;
15240 Version
const& libraryVersion() {
15241 static Version version( 2, 13, 0,
"", 0 );
15251 WildcardPattern::WildcardPattern( std::string
const& pattern,
15253 : m_caseSensitivity( caseSensitivity ),
15254 m_pattern( normaliseString( pattern ) )
15257 m_pattern = m_pattern.substr( 1 );
15258 m_wildcard = WildcardAtStart;
15260 if(
endsWith( m_pattern,
'*' ) ) {
15261 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15262 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15266 bool WildcardPattern::matches( std::string
const&
str )
const {
15267 switch( m_wildcard ) {
15269 return m_pattern == normaliseString( str );
15270 case WildcardAtStart:
15271 return endsWith( normaliseString( str ), m_pattern );
15272 case WildcardAtEnd:
15273 return startsWith( normaliseString( str ), m_pattern );
15274 case WildcardAtBothEnds:
15275 return contains( normaliseString( str ), m_pattern );
15281 std::string WildcardPattern::normaliseString( std::string
const& str )
const {
15289 #include <type_traits> 15295 size_t trailingBytes(
unsigned char c) {
15296 if ((c & 0xE0) == 0xC0) {
15299 if ((c & 0xF0) == 0xE0) {
15302 if ((c & 0xF8) == 0xF0) {
15308 uint32_t headerValue(
unsigned char c) {
15309 if ((c & 0xE0) == 0xC0) {
15312 if ((c & 0xF0) == 0xE0) {
15315 if ((c & 0xF8) == 0xF0) {
15321 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15322 std::ios_base::fmtflags f(os.flags());
15324 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15325 <<
static_cast<int>(c);
15329 bool shouldNewline(XmlFormatting fmt) {
15330 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15333 bool shouldIndent(XmlFormatting fmt) {
15334 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15339 XmlFormatting
operator | (XmlFormatting lhs, XmlFormatting rhs) {
15340 return static_cast<XmlFormatting
>(
15341 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15342 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15346 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15347 return static_cast<XmlFormatting
>(
15348 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15349 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15353 XmlEncode::XmlEncode( std::string
const&
str, ForWhat forWhat )
15355 m_forWhat( forWhat )
15358 void XmlEncode::encodeTo( std::ostream& os )
const {
15362 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15363 unsigned char c = m_str[idx];
15365 case '<': os <<
"<";
break;
15366 case '&': os <<
"&";
break;
15370 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15377 if (m_forWhat == ForAttributes)
15388 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15389 hexEscapeChar(os, c);
15407 hexEscapeChar(os, c);
15411 auto encBytes = trailingBytes(c);
15413 if (idx + encBytes - 1 >= m_str.size()) {
15414 hexEscapeChar(os, c);
15421 uint32_t
value = headerValue(c);
15422 for (std::size_t n = 1; n < encBytes; ++n) {
15423 unsigned char nc = m_str[idx + n];
15424 valid &= ((nc & 0xC0) == 0x80);
15425 value = (value << 6) | (nc & 0x3F);
15433 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15434 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15436 (value >= 0x110000)
15438 hexEscapeChar(os, c);
15443 for (std::size_t n = 0; n < encBytes; ++n) {
15444 os << m_str[idx + n];
15446 idx += encBytes - 1;
15452 std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15453 xmlEncode.encodeTo( os );
15457 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15458 : m_writer( writer ),
15462 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15463 : m_writer( other.m_writer ),
15466 other.m_writer =
nullptr;
15467 other.m_fmt = XmlFormatting::None;
15469 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15471 m_writer->endElement();
15473 m_writer = other.m_writer;
15474 other.m_writer =
nullptr;
15475 m_fmt = other.m_fmt;
15476 other.m_fmt = XmlFormatting::None;
15480 XmlWriter::ScopedElement::~ScopedElement() {
15482 m_writer->endElement(m_fmt);
15486 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string
const& text, XmlFormatting fmt ) {
15487 m_writer->writeText( text, fmt );
15491 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15493 writeDeclaration();
15496 XmlWriter::~XmlWriter() {
15497 while (!m_tags.empty()) {
15500 newlineIfNecessary();
15503 XmlWriter& XmlWriter::startElement( std::string
const& name, XmlFormatting fmt ) {
15505 newlineIfNecessary();
15506 if (shouldIndent(fmt)) {
15510 m_os <<
'<' << name;
15511 m_tags.push_back( name );
15512 m_tagIsOpen =
true;
15513 applyFormatting(fmt);
15517 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string
const& name, XmlFormatting fmt ) {
15518 ScopedElement scoped(
this, fmt );
15519 startElement( name, fmt );
15523 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15524 m_indent = m_indent.substr(0, m_indent.size() - 2);
15526 if( m_tagIsOpen ) {
15528 m_tagIsOpen =
false;
15530 newlineIfNecessary();
15531 if (shouldIndent(fmt)) {
15534 m_os <<
"</" << m_tags.back() <<
">";
15536 m_os << std::flush;
15537 applyFormatting(fmt);
15542 XmlWriter& XmlWriter::writeAttribute( std::string
const& name, std::string
const& attribute ) {
15543 if( !name.empty() && !attribute.empty() )
15544 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15548 XmlWriter& XmlWriter::writeAttribute( std::string
const& name,
bool attribute ) {
15549 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15553 XmlWriter& XmlWriter::writeText( std::string
const& text, XmlFormatting fmt) {
15554 if( !text.empty() ){
15555 bool tagWasOpen = m_tagIsOpen;
15557 if (tagWasOpen && shouldIndent(fmt)) {
15560 m_os << XmlEncode( text );
15561 applyFormatting(fmt);
15566 XmlWriter& XmlWriter::writeComment( std::string
const& text, XmlFormatting fmt) {
15568 if (shouldIndent(fmt)) {
15571 m_os <<
"<!--" << text <<
"-->";
15572 applyFormatting(fmt);
15576 void XmlWriter::writeStylesheetRef( std::string
const& url ) {
15577 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15580 XmlWriter& XmlWriter::writeBlankLine() {
15586 void XmlWriter::ensureTagClosed() {
15587 if( m_tagIsOpen ) {
15588 m_os << '>
' << std::flush; 15589 newlineIfNecessary(); 15590 m_tagIsOpen = false; 15594 void XmlWriter::applyFormatting(XmlFormatting fmt) { 15595 m_needsNewline = shouldNewline(fmt); 15598 void XmlWriter::writeDeclaration() { 15599 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; 15602 void XmlWriter::newlineIfNecessary() { 15603 if( m_needsNewline ) { 15605 m_needsNewline = false; 15609 // end catch_xmlwriter.cpp 15610 // start catch_reporter_bases.cpp 15619 void prepareExpandedExpression(AssertionResult& result) { 15620 result.getExpandedExpression(); 15623 // Because formatting using c++ streams is stateful, drop down to C is required 15624 // Alternatively we could use stringstream, but its performance is... not good. 15625 std::string getFormattedDuration( double duration ) { 15626 // Max exponent + 1 is required to represent the whole part 15627 // + 1 for decimal point 15628 // + 3 for the 3 decimal places 15629 // + 1 for null terminator 15630 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; 15631 char buffer[maxDoubleSize]; 15633 // Save previous errno, to prevent sprintf from overwriting it 15636 sprintf_s(buffer, "%.3f", duration); 15638 std::sprintf(buffer, "%.3f", duration); 15640 return std::string(buffer); 15643 bool shouldShowDuration( IConfig const& config, double duration ) { 15644 if ( config.showDurations() == ShowDurations::Always ) { 15647 if ( config.showDurations() == ShowDurations::Never ) { 15650 const double min = config.minDuration(); 15651 return min >= 0 && duration >= min; 15654 std::string serializeFilters( std::vector<std::string> const& container ) { 15655 ReusableStringStream oss; 15657 for (auto&& filter : container) 15669 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) 15670 :StreamingReporterBase(_config) {} 15672 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() { 15673 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; 15676 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} 15678 bool TestEventListenerBase::assertionEnded(AssertionStats const &) { 15682 } // end namespace Catch 15683 // end catch_reporter_bases.cpp 15684 // start catch_reporter_compact.cpp 15688 #ifdef CATCH_PLATFORM_MAC 15689 const char* failedString() { return "FAILED"; } 15690 const char* passedString() { return "PASSED"; } 15692 const char* failedString() { return "failed"; } 15693 const char* passedString() { return "passed"; } 15696 // Colour::LightGrey 15697 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } 15699 std::string bothOrAll( std::size_t count ) { 15700 return count == 1 ? std::string() : 15701 count == 2 ? "both " : "all " ; 15704 } // anon namespace 15708 // Colour, message variants: 15709 // - white: No tests ran. 15710 // - red: Failed [both/all] N test cases, failed [both/all] M assertions. 15711 // - white: Passed [both/all] N test cases (no assertions). 15712 // - red: Failed N tests cases, failed M assertions. 15713 // - green: Passed [both/all] N tests cases with M assertions. 15714 void printTotals(std::ostream& out, const Totals& totals) { 15715 if (totals.testCases.total() == 0) { 15716 out << "No tests ran."; 15717 } else if (totals.testCases.failed == totals.testCases.total()) { 15718 Colour colour(Colour::ResultError); 15719 const std::string qualify_assertions_failed = 15720 totals.assertions.failed == totals.assertions.total() ? 15721 bothOrAll(totals.assertions.failed) : std::string(); 15723 "Failed " << bothOrAll(totals.testCases.failed) 15724 << pluralise(totals.testCases.failed, "test case") << ", " 15725 "failed " << qualify_assertions_failed << 15726 pluralise(totals.assertions.failed, "assertion") << '.
'; 15727 } else if (totals.assertions.total() == 0) { 15729 "Passed " << bothOrAll(totals.testCases.total()) 15730 << pluralise(totals.testCases.total(), "test case") 15731 << " (no assertions)."; 15732 } else if (totals.assertions.failed) { 15733 Colour colour(Colour::ResultError); 15735 "Failed " << pluralise(totals.testCases.failed, "test case") << ", " 15736 "failed " << pluralise(totals.assertions.failed, "assertion") << '.
'; 15738 Colour colour(Colour::ResultSuccess); 15740 "Passed " << bothOrAll(totals.testCases.passed) 15741 << pluralise(totals.testCases.passed, "test case") << 15742 " with " << pluralise(totals.assertions.passed, "assertion") << '.
'; 15746 // Implementation of CompactReporter formatting 15747 class AssertionPrinter { 15749 AssertionPrinter& operator= (AssertionPrinter const&) = delete; 15750 AssertionPrinter(AssertionPrinter const&) = delete; 15751 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) 15753 , result(_stats.assertionResult) 15754 , messages(_stats.infoMessages) 15755 , itMessage(_stats.infoMessages.begin()) 15756 , printInfoMessages(_printInfoMessages) {} 15761 itMessage = messages.begin(); 15763 switch (result.getResultType()) { 15764 case ResultWas::Ok: 15765 printResultType(Colour::ResultSuccess, passedString()); 15766 printOriginalExpression(); 15767 printReconstructedExpression(); 15768 if (!result.hasExpression()) 15769 printRemainingMessages(Colour::None); 15771 printRemainingMessages(); 15773 case ResultWas::ExpressionFailed: 15775 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); 15777 printResultType(Colour::Error, failedString()); 15778 printOriginalExpression(); 15779 printReconstructedExpression(); 15780 printRemainingMessages(); 15782 case ResultWas::ThrewException: 15783 printResultType(Colour::Error, failedString()); 15784 printIssue("unexpected exception with message:"); 15786 printExpressionWas(); 15787 printRemainingMessages(); 15789 case ResultWas::FatalErrorCondition: 15790 printResultType(Colour::Error, failedString()); 15791 printIssue("fatal error condition with message:"); 15793 printExpressionWas(); 15794 printRemainingMessages(); 15796 case ResultWas::DidntThrowException: 15797 printResultType(Colour::Error, failedString()); 15798 printIssue("expected exception, got none"); 15799 printExpressionWas(); 15800 printRemainingMessages(); 15802 case ResultWas::Info: 15803 printResultType(Colour::None, "info"); 15805 printRemainingMessages(); 15807 case ResultWas::Warning: 15808 printResultType(Colour::None, "warning"); 15810 printRemainingMessages(); 15812 case ResultWas::ExplicitFailure: 15813 printResultType(Colour::Error, failedString()); 15814 printIssue("explicitly"); 15815 printRemainingMessages(Colour::None); 15817 // These cases are here to prevent compiler warnings 15818 case ResultWas::Unknown: 15819 case ResultWas::FailureBit: 15820 case ResultWas::Exception: 15821 printResultType(Colour::Error, "** internal error **"); 15827 void printSourceInfo() const { 15828 Colour colourGuard(Colour::FileName); 15829 stream << result.getSourceInfo() << ':
'; 15832 void printResultType(Colour::Code colour, std::string const& passOrFail) const { 15833 if (!passOrFail.empty()) { 15835 Colour colourGuard(colour); 15836 stream << ' ' << passOrFail; 15842 void printIssue(std::string const& issue) const { 15843 stream << ' ' << issue; 15846 void printExpressionWas() { 15847 if (result.hasExpression()) { 15850 Colour colour(dimColour()); 15851 stream << " expression was:"; 15853 printOriginalExpression(); 15857 void printOriginalExpression() const { 15858 if (result.hasExpression()) { 15859 stream << ' ' << result.getExpression(); 15863 void printReconstructedExpression() const { 15864 if (result.hasExpandedExpression()) { 15866 Colour colour(dimColour()); 15867 stream << " for: "; 15869 stream << result.getExpandedExpression(); 15873 void printMessage() { 15874 if (itMessage != messages.end()) { 15875 stream << " '" << itMessage->message << '\''; 15880 void printRemainingMessages(Colour::Code colour = dimColour()) { 15881 if (itMessage == messages.end()) 15884 const auto itEnd = messages.cend(); 15885 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd)); 15888 Colour colourGuard(colour); 15889 stream << " with
" << pluralise(N, "message
") << ':'; 15892 while (itMessage != itEnd) { 15893 // If this assertion is a warning ignore any INFO messages 15894 if (printInfoMessages || itMessage->type != ResultWas::Info) { 15896 if (itMessage != itEnd) { 15897 Colour colourGuard(dimColour()); 15907 std::ostream& stream; 15908 AssertionResult const& result; 15909 std::vector<MessageInfo> messages; 15910 std::vector<MessageInfo>::const_iterator itMessage; 15911 bool printInfoMessages; 15914 } // anon namespace 15916 std::string CompactReporter::getDescription() { 15917 return "Reports test results on a single line, suitable
for IDEs
"; 15920 void CompactReporter::noMatchingTestCases( std::string const& spec ) { 15921 stream << "No test cases matched
'" << spec << '\
'' << std::endl;
15924 void CompactReporter::assertionStarting(
AssertionInfo const& ) {}
15926 bool CompactReporter::assertionEnded( AssertionStats
const& _assertionStats ) {
15927 AssertionResult
const& result = _assertionStats.assertionResult;
15929 bool printInfoMessages =
true;
15932 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
15935 printInfoMessages =
false;
15938 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
15941 stream << std::endl;
15945 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
15946 double dur = _sectionStats.durationInSeconds;
15947 if ( shouldShowDuration( *m_config, dur ) ) {
15948 stream << getFormattedDuration( dur ) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
15952 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
15953 printTotals( stream, _testRunStats.totals );
15954 stream <<
'\n' << std::endl;
15955 StreamingReporterBase::testRunEnded( _testRunStats );
15958 CompactReporter::~CompactReporter() {}
15960 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
15969 #if defined(_MSC_VER) 15970 #pragma warning(push) 15971 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 15975 #if defined(__clang__) 15976 # pragma clang diagnostic push 15978 # pragma clang diagnostic ignored "-Wunused-function" 15986 class ConsoleAssertionPrinter {
15988 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter
const&) =
delete;
15989 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
15990 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
15993 result(_stats.assertionResult),
15994 colour(Colour::None),
15995 message(result.getMessage()),
15996 messages(_stats.infoMessages),
15997 printInfoMessages(_printInfoMessages) {
15998 switch (result.getResultType()) {
16000 colour = Colour::Success;
16001 passOrFail =
"PASSED";
16003 if (_stats.infoMessages.size() == 1)
16004 messageLabel =
"with message";
16005 if (_stats.infoMessages.size() > 1)
16006 messageLabel =
"with messages";
16009 if (result.isOk()) {
16010 colour = Colour::Success;
16011 passOrFail =
"FAILED - but was ok";
16013 colour = Colour::Error;
16014 passOrFail =
"FAILED";
16016 if (_stats.infoMessages.size() == 1)
16017 messageLabel =
"with message";
16018 if (_stats.infoMessages.size() > 1)
16019 messageLabel =
"with messages";
16022 colour = Colour::Error;
16023 passOrFail =
"FAILED";
16024 messageLabel =
"due to unexpected exception with ";
16025 if (_stats.infoMessages.size() == 1)
16026 messageLabel +=
"message";
16027 if (_stats.infoMessages.size() > 1)
16028 messageLabel +=
"messages";
16031 colour = Colour::Error;
16032 passOrFail =
"FAILED";
16033 messageLabel =
"due to a fatal error condition";
16036 colour = Colour::Error;
16037 passOrFail =
"FAILED";
16038 messageLabel =
"because no exception was thrown where one was expected";
16041 messageLabel =
"info";
16044 messageLabel =
"warning";
16047 passOrFail =
"FAILED";
16048 colour = Colour::Error;
16049 if (_stats.infoMessages.size() == 1)
16050 messageLabel =
"explicitly with message";
16051 if (_stats.infoMessages.size() > 1)
16052 messageLabel =
"explicitly with messages";
16058 passOrFail =
"** internal error **";
16059 colour = Colour::Error;
16064 void print()
const {
16066 if (stats.totals.assertions.total() > 0) {
16068 printOriginalExpression();
16069 printReconstructedExpression();
16077 void printResultType()
const {
16078 if (!passOrFail.empty()) {
16079 Colour colourGuard(colour);
16080 stream << passOrFail <<
":\n";
16083 void printOriginalExpression()
const {
16084 if (result.hasExpression()) {
16085 Colour colourGuard(Colour::OriginalExpression);
16087 stream << result.getExpressionInMacro();
16091 void printReconstructedExpression()
const {
16092 if (result.hasExpandedExpression()) {
16093 stream <<
"with expansion:\n";
16094 Colour colourGuard(Colour::ReconstructedExpression);
16095 stream << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16098 void printMessage()
const {
16099 if (!messageLabel.empty())
16100 stream << messageLabel <<
':' <<
'\n';
16101 for (
auto const& msg : messages) {
16104 stream << Column(msg.message).indent(2) <<
'\n';
16107 void printSourceInfo()
const {
16108 Colour colourGuard(Colour::FileName);
16109 stream << result.getSourceInfo() <<
": ";
16112 std::ostream& stream;
16113 AssertionStats
const& stats;
16114 AssertionResult
const& result;
16115 Colour::Code colour;
16116 std::string passOrFail;
16117 std::string messageLabel;
16118 std::string message;
16119 std::vector<MessageInfo> messages;
16120 bool printInfoMessages;
16123 std::size_t makeRatio(std::size_t number, std::size_t total) {
16125 return (ratio == 0 && number > 0) ? 1 : ratio;
16128 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16129 if (i > j && i > k)
16137 struct ColumnInfo {
16138 enum Justification { Left, Right };
16141 Justification justification;
16143 struct ColumnBreak {};
16144 struct RowBreak {};
16155 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16156 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16157 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16158 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16160 double m_inNanoseconds;
16164 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16165 : m_inNanoseconds(inNanoseconds),
16167 if (m_units == Unit::Auto) {
16168 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16169 m_units = Unit::Nanoseconds;
16170 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16171 m_units = Unit::Microseconds;
16172 else if (m_inNanoseconds < s_nanosecondsInASecond)
16173 m_units = Unit::Milliseconds;
16174 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16175 m_units = Unit::Seconds;
16177 m_units = Unit::Minutes;
16182 auto value()
const ->
double {
16184 case Unit::Microseconds:
16185 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16186 case Unit::Milliseconds:
16187 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16188 case Unit::Seconds:
16189 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16190 case Unit::Minutes:
16191 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16193 return m_inNanoseconds;
16196 auto unitsAsString()
const -> std::string {
16198 case Unit::Nanoseconds:
16200 case Unit::Microseconds:
16202 case Unit::Milliseconds:
16204 case Unit::Seconds:
16206 case Unit::Minutes:
16209 return "** internal error **";
16213 friend auto operator << (std::ostream& os, Duration
const& duration) -> std::ostream& {
16214 return os << duration.value() <<
' ' << duration.unitsAsString();
16219 class TablePrinter {
16220 std::ostream& m_os;
16221 std::vector<ColumnInfo> m_columnInfos;
16222 std::ostringstream m_oss;
16223 int m_currentColumn = -1;
16224 bool m_isOpen =
false;
16227 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16229 m_columnInfos( std::move( columnInfos ) ) {}
16231 auto columnInfos()
const -> std::vector<ColumnInfo>
const& {
16232 return m_columnInfos;
16238 *
this << RowBreak();
16240 Columns headerCols;
16242 for (
auto const& info : m_columnInfos) {
16243 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16244 headerCols += spacer;
16246 m_os << headerCols <<
'\n';
16248 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16253 *
this << RowBreak();
16259 template<
typename T>
16265 friend TablePrinter&
operator << (TablePrinter& tp, ColumnBreak) {
16266 auto colStr = tp.m_oss.str();
16267 const auto strSize = colStr.size();
16270 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16271 tp.m_currentColumn = -1;
16274 tp.m_currentColumn++;
16276 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16277 auto padding = (strSize + 1 <
static_cast<std::size_t
>(colInfo.width))
16278 ? std::string(colInfo.width - (strSize + 1),
' ')
16280 if (colInfo.justification == ColumnInfo::Left)
16281 tp.m_os << colStr << padding <<
' ';
16283 tp.m_os << padding << colStr <<
' ';
16287 friend TablePrinter&
operator << (TablePrinter& tp, RowBreak) {
16288 if (tp.m_currentColumn > 0) {
16290 tp.m_currentColumn = -1;
16296 ConsoleReporter::ConsoleReporter(ReporterConfig
const& config)
16297 : StreamingReporterBase(config),
16298 m_tablePrinter(
new TablePrinter(config.stream(),
16299 [&config]() -> std::vector<ColumnInfo> {
16300 if (config.fullConfig()->benchmarkNoAnalysis())
16304 {
" samples", 14, ColumnInfo::Right },
16305 {
" iterations", 14, ColumnInfo::Right },
16306 {
" mean", 14, ColumnInfo::Right }
16313 {
"samples mean std dev", 14, ColumnInfo::Right },
16314 {
"iterations low mean low std dev", 14, ColumnInfo::Right },
16315 {
"estimated high mean high std dev", 14, ColumnInfo::Right }
16319 ConsoleReporter::~ConsoleReporter() =
default;
16321 std::string ConsoleReporter::getDescription() {
16322 return "Reports test results as plain lines of text";
16325 void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16326 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16329 void ConsoleReporter::reportInvalidArguments(std::string
const&arg){
16330 stream <<
"Invalid Filter: " << arg << std::endl;
16333 void ConsoleReporter::assertionStarting(
AssertionInfo const&) {}
16335 bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16336 AssertionResult
const& result = _assertionStats.assertionResult;
16338 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16346 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16348 stream << std::endl;
16352 void ConsoleReporter::sectionStarting(
SectionInfo const& _sectionInfo) {
16353 m_tablePrinter->close();
16354 m_headerPrinted =
false;
16355 StreamingReporterBase::sectionStarting(_sectionInfo);
16357 void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16358 m_tablePrinter->close();
16359 if (_sectionStats.missingAssertions) {
16361 Colour colour(Colour::ResultError);
16362 if (m_sectionStack.size() > 1)
16363 stream <<
"\nNo assertions in section";
16365 stream <<
"\nNo assertions in test case";
16366 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16368 double dur = _sectionStats.durationInSeconds;
16369 if (shouldShowDuration(*m_config, dur)) {
16370 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16372 if (m_headerPrinted) {
16373 m_headerPrinted =
false;
16375 StreamingReporterBase::sectionEnded(_sectionStats);
16378 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 16379 void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16380 lazyPrintWithoutClosingBenchmarkTable();
16382 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16384 bool firstLine =
true;
16385 for (
auto line : nameCol) {
16387 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16391 (*m_tablePrinter) << line << ColumnBreak();
16395 void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16396 (*m_tablePrinter) << info.samples << ColumnBreak()
16397 << info.iterations << ColumnBreak();
16398 if (!m_config->benchmarkNoAnalysis())
16399 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16401 void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16402 if (m_config->benchmarkNoAnalysis())
16404 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16408 (*m_tablePrinter) << ColumnBreak()
16409 << Duration(stats.mean.point.count()) << ColumnBreak()
16410 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16411 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16412 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16413 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16414 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16418 void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16419 Colour colour(Colour::Red);
16421 <<
"Benchmark failed (" << error <<
')' 16422 << ColumnBreak() << RowBreak();
16424 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 16426 void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16427 m_tablePrinter->close();
16428 StreamingReporterBase::testCaseEnded(_testCaseStats);
16429 m_headerPrinted =
false;
16431 void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16432 if (currentGroupInfo.used) {
16433 printSummaryDivider();
16434 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16435 printTotals(_testGroupStats.totals);
16436 stream <<
'\n' << std::endl;
16438 StreamingReporterBase::testGroupEnded(_testGroupStats);
16440 void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16441 printTotalsDivider(_testRunStats.totals);
16442 printTotals(_testRunStats.totals);
16443 stream << std::endl;
16444 StreamingReporterBase::testRunEnded(_testRunStats);
16446 void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16447 StreamingReporterBase::testRunStarting(_testInfo);
16448 printTestFilters();
16451 void ConsoleReporter::lazyPrint() {
16453 m_tablePrinter->close();
16454 lazyPrintWithoutClosingBenchmarkTable();
16457 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16459 if (!currentTestRunInfo.used)
16460 lazyPrintRunInfo();
16461 if (!currentGroupInfo.used)
16462 lazyPrintGroupInfo();
16464 if (!m_headerPrinted) {
16465 printTestCaseAndSectionHeader();
16466 m_headerPrinted =
true;
16469 void ConsoleReporter::lazyPrintRunInfo() {
16470 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16471 Colour colour(Colour::SecondaryText);
16472 stream << currentTestRunInfo->name
16473 <<
" is a Catch v" << libraryVersion() <<
" host application.\n" 16474 <<
"Run with -? for options\n\n";
16476 if (m_config->rngSeed() != 0)
16477 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16479 currentTestRunInfo.used =
true;
16481 void ConsoleReporter::lazyPrintGroupInfo() {
16482 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16483 printClosedHeader(
"Group: " + currentGroupInfo->name);
16484 currentGroupInfo.used =
true;
16487 void ConsoleReporter::printTestCaseAndSectionHeader() {
16488 assert(!m_sectionStack.empty());
16489 printOpenHeader(currentTestCaseInfo->name);
16491 if (m_sectionStack.size() > 1) {
16492 Colour colourGuard(Colour::Headers);
16495 it = m_sectionStack.begin() + 1,
16496 itEnd = m_sectionStack.end();
16497 for (; it != itEnd; ++it)
16498 printHeaderString(it->name, 2);
16503 stream << getLineOfChars<
'-'>() <<
'\n';
16504 Colour colourGuard(Colour::FileName);
16505 stream << lineInfo <<
'\n';
16506 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16509 void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16510 printOpenHeader(_name);
16511 stream << getLineOfChars<
'.'>() <<
'\n';
16513 void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16514 stream << getLineOfChars<
'-'>() <<
'\n';
16516 Colour colourGuard(Colour::Headers);
16517 printHeaderString(_name);
16523 void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16524 std::size_t i = _string.find(
": ");
16525 if (i != std::string::npos)
16529 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16532 struct SummaryColumn {
16534 SummaryColumn( std::string _label, Colour::Code _colour )
16535 : label( std::move( _label ) ),
16536 colour( _colour ) {}
16537 SummaryColumn addRow( std::size_t count ) {
16540 std::string row = rss.
str();
16541 for (
auto& oldRow : rows) {
16542 while (oldRow.size() < row.size())
16543 oldRow =
' ' + oldRow;
16544 while (oldRow.size() > row.size())
16547 rows.push_back(row);
16552 Colour::Code colour;
16553 std::vector<std::string> rows;
16557 void ConsoleReporter::printTotals(
Totals const& totals ) {
16559 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16561 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16568 std::vector<SummaryColumn> columns;
16569 columns.push_back(SummaryColumn(
"", Colour::None)
16572 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16575 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16578 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16582 printSummaryRow(
"test cases", columns, 0);
16583 printSummaryRow(
"assertions", columns, 1);
16586 void ConsoleReporter::printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row) {
16587 for (
auto col : cols) {
16588 std::string
value = col.rows[row];
16589 if (col.label.empty()) {
16590 stream << label <<
": ";
16594 stream << Colour(Colour::Warning) <<
"- none -";
16595 }
else if (value !=
"0") {
16596 stream << Colour(Colour::LightGrey) <<
" | ";
16597 stream << Colour(col.colour)
16598 << value <<
' ' << col.label;
16604 void ConsoleReporter::printTotalsDivider(
Totals const& totals) {
16610 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16612 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16614 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16615 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16617 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16619 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16625 void ConsoleReporter::printSummaryDivider() {
16626 stream << getLineOfChars<
'-'>() <<
'\n';
16629 void ConsoleReporter::printTestFilters() {
16630 if (m_config->testSpec().hasFilters()) {
16631 Colour guard(Colour::BrightYellow);
16632 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16636 CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16640 #if defined(_MSC_VER) 16641 #pragma warning(pop) 16644 #if defined(__clang__) 16645 # pragma clang diagnostic pop 16653 #include <algorithm> 16658 std::string getCurrentTimestamp() {
16662 std::time(&rawtime);
16663 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16666 std::tm timeInfo = {};
16667 gmtime_s(&timeInfo, &rawtime);
16670 timeInfo = std::gmtime(&rawtime);
16673 char timeStamp[timeStampSize];
16674 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16677 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16679 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16681 return std::string(timeStamp);
16684 std::string fileNameTag(
const std::vector<std::string> &tags) {
16685 auto it = std::find_if(begin(tags),
16687 [] (std::string
const& tag) {
return tag.front() ==
'#'; });
16688 if (it != tags.end())
16689 return it->substr(1);
16690 return std::string();
16694 JunitReporter::JunitReporter( ReporterConfig
const& _config )
16695 : CumulativeReporterBase( _config ),
16696 xml( _config.stream() )
16698 m_reporterPrefs.shouldRedirectStdOut =
true;
16699 m_reporterPrefs.shouldReportAllAssertions =
true;
16702 JunitReporter::~JunitReporter() {}
16704 std::string JunitReporter::getDescription() {
16705 return "Reports test results in an XML format that looks like Ant's junitreport target";
16708 void JunitReporter::noMatchingTestCases( std::string
const& ) {}
16710 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16711 CumulativeReporterBase::testRunStarting( runInfo );
16712 xml.startElement(
"testsuites" );
16715 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16716 suiteTimer.start();
16717 stdOutForSuite.clear();
16718 stdErrForSuite.clear();
16719 unexpectedExceptions = 0;
16720 CumulativeReporterBase::testGroupStarting( groupInfo );
16723 void JunitReporter::testCaseStarting(
TestCaseInfo const& testCaseInfo ) {
16724 m_okToFail = testCaseInfo.
okToFail();
16727 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16729 unexpectedExceptions++;
16730 return CumulativeReporterBase::assertionEnded( assertionStats );
16733 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16734 stdOutForSuite += testCaseStats.stdOut;
16735 stdErrForSuite += testCaseStats.stdErr;
16736 CumulativeReporterBase::testCaseEnded( testCaseStats );
16739 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16740 double suiteTime = suiteTimer.getElapsedSeconds();
16741 CumulativeReporterBase::testGroupEnded( testGroupStats );
16742 writeGroup( *m_testGroups.back(), suiteTime );
16745 void JunitReporter::testRunEndedCumulative() {
16749 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16750 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
16752 TestGroupStats
const& stats = groupNode.value;
16753 xml.writeAttribute(
"name", stats.groupInfo.name );
16754 xml.writeAttribute(
"errors", unexpectedExceptions );
16755 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16756 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16757 xml.writeAttribute(
"hostname",
"tbd" );
16759 xml.writeAttribute(
"time",
"" );
16761 xml.writeAttribute(
"time", suiteTime );
16762 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16765 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16766 auto properties = xml.scopedElement(
"properties");
16767 if (m_config->hasTestFilters()) {
16768 xml.scopedElement(
"property")
16769 .writeAttribute(
"name",
"filters")
16770 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16772 if (m_config->rngSeed() != 0) {
16773 xml.scopedElement(
"property")
16774 .writeAttribute(
"name",
"random-seed")
16775 .writeAttribute(
"value", m_config->rngSeed());
16780 for(
auto const& child : groupNode.children )
16781 writeTestCase( *child );
16783 xml.scopedElement(
"system-out" ).writeText(
trim( stdOutForSuite ), XmlFormatting::Newline );
16784 xml.scopedElement(
"system-err" ).writeText(
trim( stdErrForSuite ), XmlFormatting::Newline );
16787 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16788 TestCaseStats
const& stats = testCaseNode.value;
16792 assert( testCaseNode.children.size() == 1 );
16793 SectionNode
const& rootSection = *testCaseNode.children.front();
16795 std::string className = stats.testInfo.className;
16797 if( className.empty() ) {
16798 className = fileNameTag(stats.testInfo.tags);
16799 if ( className.empty() )
16800 className =
"global";
16803 if ( !m_config->name().empty() )
16804 className = m_config->name() +
"." + className;
16806 writeSection( className,
"", rootSection );
16809 void JunitReporter::writeSection( std::string
const& className,
16810 std::string
const& rootName,
16811 SectionNode
const& sectionNode ) {
16812 std::string name =
trim( sectionNode.stats.sectionInfo.name );
16813 if( !rootName.empty() )
16814 name = rootName +
'/' + name;
16816 if( !sectionNode.assertions.empty() ||
16817 !sectionNode.stdOut.empty() ||
16818 !sectionNode.stdErr.empty() ) {
16819 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
16820 if( className.empty() ) {
16821 xml.writeAttribute(
"classname", name );
16822 xml.writeAttribute(
"name",
"root" );
16825 xml.writeAttribute(
"classname", className );
16826 xml.writeAttribute(
"name", name );
16833 xml.writeAttribute(
"status",
"run" );
16835 writeAssertions( sectionNode );
16837 if( !sectionNode.stdOut.empty() )
16838 xml.scopedElement(
"system-out" ).writeText(
trim( sectionNode.stdOut ), XmlFormatting::Newline );
16839 if( !sectionNode.stdErr.empty() )
16840 xml.scopedElement(
"system-err" ).writeText(
trim( sectionNode.stdErr ), XmlFormatting::Newline );
16842 for(
auto const& childNode : sectionNode.childSections )
16843 if( className.empty() )
16844 writeSection( name,
"", *childNode );
16846 writeSection( className, name, *childNode );
16849 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
16850 for(
auto const& assertion : sectionNode.assertions )
16851 writeAssertion( assertion );
16854 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
16855 AssertionResult
const& result = stats.assertionResult;
16856 if( !result.isOk() ) {
16857 std::string elementName;
16858 switch( result.getResultType() ) {
16861 elementName =
"error";
16866 elementName =
"failure";
16876 elementName =
"internalError";
16880 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
16882 xml.writeAttribute(
"message", result.getExpression() );
16883 xml.writeAttribute(
"type", result.getTestMacroName() );
16886 if (stats.totals.assertions.total() > 0) {
16887 rss <<
"FAILED" <<
":\n";
16888 if (result.hasExpression()) {
16890 rss << result.getExpressionInMacro();
16893 if (result.hasExpandedExpression()) {
16894 rss <<
"with expansion:\n";
16895 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16901 if( !result.getMessage().empty() )
16902 rss << result.getMessage() <<
'\n';
16903 for(
auto const& msg : stats.infoMessages )
16905 rss << msg.message <<
'\n';
16907 rss <<
"at " << result.getSourceInfo();
16908 xml.writeText( rss.
str(), XmlFormatting::Newline );
16912 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
16922 ListeningReporter::ListeningReporter() {
16924 m_preferences.shouldReportAllAssertions =
true;
16927 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
16928 m_listeners.push_back( std::move( listener ) );
16931 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
16932 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
16933 m_reporter = std::move( reporter );
16934 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
16937 ReporterPreferences ListeningReporter::getPreferences()
const {
16938 return m_preferences;
16941 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
16942 return std::set<Verbosity>{ };
16945 void ListeningReporter::noMatchingTestCases( std::string
const& spec ) {
16946 for (
auto const& listener : m_listeners ) {
16947 listener->noMatchingTestCases( spec );
16949 m_reporter->noMatchingTestCases( spec );
16952 void ListeningReporter::reportInvalidArguments(std::string
const&arg){
16953 for (
auto const& listener : m_listeners ) {
16954 listener->reportInvalidArguments( arg );
16956 m_reporter->reportInvalidArguments( arg );
16959 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 16960 void ListeningReporter::benchmarkPreparing( std::string
const& name ) {
16961 for (
auto const& listener : m_listeners) {
16962 listener->benchmarkPreparing(name);
16964 m_reporter->benchmarkPreparing(name);
16966 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
16967 for (
auto const& listener : m_listeners ) {
16968 listener->benchmarkStarting( benchmarkInfo );
16970 m_reporter->benchmarkStarting( benchmarkInfo );
16972 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
16973 for (
auto const& listener : m_listeners ) {
16974 listener->benchmarkEnded( benchmarkStats );
16976 m_reporter->benchmarkEnded( benchmarkStats );
16979 void ListeningReporter::benchmarkFailed( std::string
const& error ) {
16980 for (
auto const& listener : m_listeners) {
16981 listener->benchmarkFailed(error);
16983 m_reporter->benchmarkFailed(error);
16985 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 16987 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
16988 for (
auto const& listener : m_listeners ) {
16989 listener->testRunStarting( testRunInfo );
16991 m_reporter->testRunStarting( testRunInfo );
16994 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16995 for (
auto const& listener : m_listeners ) {
16996 listener->testGroupStarting( groupInfo );
16998 m_reporter->testGroupStarting( groupInfo );
17001 void ListeningReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17002 for (
auto const& listener : m_listeners ) {
17003 listener->testCaseStarting( testInfo );
17005 m_reporter->testCaseStarting( testInfo );
17008 void ListeningReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17009 for (
auto const& listener : m_listeners ) {
17010 listener->sectionStarting( sectionInfo );
17012 m_reporter->sectionStarting( sectionInfo );
17015 void ListeningReporter::assertionStarting(
AssertionInfo const& assertionInfo ) {
17016 for (
auto const& listener : m_listeners ) {
17017 listener->assertionStarting( assertionInfo );
17019 m_reporter->assertionStarting( assertionInfo );
17023 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17024 for(
auto const& listener : m_listeners ) {
17025 static_cast<void>( listener->assertionEnded( assertionStats ) );
17027 return m_reporter->assertionEnded( assertionStats );
17030 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
17031 for (
auto const& listener : m_listeners ) {
17032 listener->sectionEnded( sectionStats );
17034 m_reporter->sectionEnded( sectionStats );
17037 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17038 for (
auto const& listener : m_listeners ) {
17039 listener->testCaseEnded( testCaseStats );
17041 m_reporter->testCaseEnded( testCaseStats );
17044 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17045 for (
auto const& listener : m_listeners ) {
17046 listener->testGroupEnded( testGroupStats );
17048 m_reporter->testGroupEnded( testGroupStats );
17051 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17052 for (
auto const& listener : m_listeners ) {
17053 listener->testRunEnded( testRunStats );
17055 m_reporter->testRunEnded( testRunStats );
17058 void ListeningReporter::skipTest(
TestCaseInfo const& testInfo ) {
17059 for (
auto const& listener : m_listeners ) {
17060 listener->skipTest( testInfo );
17062 m_reporter->skipTest( testInfo );
17065 bool ListeningReporter::isMulti()
const {
17073 #if defined(_MSC_VER) 17074 #pragma warning(push) 17075 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 17081 XmlReporter::XmlReporter( ReporterConfig
const& _config )
17082 : StreamingReporterBase( _config ),
17083 m_xml(_config.stream())
17085 m_reporterPrefs.shouldRedirectStdOut =
true;
17086 m_reporterPrefs.shouldReportAllAssertions =
true;
17089 XmlReporter::~XmlReporter() =
default;
17091 std::string XmlReporter::getDescription() {
17092 return "Reports test results as an XML document";
17095 std::string XmlReporter::getStylesheetRef()
const {
17096 return std::string();
17099 void XmlReporter::writeSourceInfo(
SourceLineInfo const& sourceInfo ) {
17101 .writeAttribute(
"filename", sourceInfo.
file )
17102 .writeAttribute(
"line", sourceInfo.
line );
17105 void XmlReporter::noMatchingTestCases( std::string
const& s ) {
17106 StreamingReporterBase::noMatchingTestCases( s );
17109 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17110 StreamingReporterBase::testRunStarting( testInfo );
17111 std::string stylesheetRef = getStylesheetRef();
17112 if( !stylesheetRef.empty() )
17113 m_xml.writeStylesheetRef( stylesheetRef );
17114 m_xml.startElement(
"Catch" );
17115 if( !m_config->name().empty() )
17116 m_xml.writeAttribute(
"name", m_config->name() );
17117 if (m_config->testSpec().hasFilters())
17118 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17119 if( m_config->rngSeed() != 0 )
17120 m_xml.scopedElement(
"Randomness" )
17121 .writeAttribute(
"seed", m_config->rngSeed() );
17124 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17125 StreamingReporterBase::testGroupStarting( groupInfo );
17126 m_xml.startElement(
"Group" )
17127 .writeAttribute(
"name", groupInfo.name );
17130 void XmlReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17131 StreamingReporterBase::testCaseStarting(testInfo);
17132 m_xml.startElement(
"TestCase" )
17133 .writeAttribute(
"name",
trim( testInfo.
name ) )
17134 .writeAttribute(
"description", testInfo.
description )
17137 writeSourceInfo( testInfo.
lineInfo );
17140 m_testCaseTimer.start();
17141 m_xml.ensureTagClosed();
17144 void XmlReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17145 StreamingReporterBase::sectionStarting( sectionInfo );
17146 if( m_sectionDepth++ > 0 ) {
17147 m_xml.startElement(
"Section" )
17148 .writeAttribute(
"name",
trim( sectionInfo.
name ) );
17149 writeSourceInfo( sectionInfo.
lineInfo );
17150 m_xml.ensureTagClosed();
17154 void XmlReporter::assertionStarting(
AssertionInfo const& ) { }
17156 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17158 AssertionResult
const& result = assertionStats.assertionResult;
17160 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17164 for(
auto const& msg : assertionStats.infoMessages ) {
17166 m_xml.scopedElement(
"Info" )
17167 .writeText( msg.message );
17169 m_xml.scopedElement(
"Warning" )
17170 .writeText( msg.message );
17180 if( result.hasExpression() ) {
17181 m_xml.startElement(
"Expression" )
17182 .writeAttribute(
"success", result.succeeded() )
17183 .writeAttribute(
"type", result.getTestMacroName() );
17185 writeSourceInfo( result.getSourceInfo() );
17187 m_xml.scopedElement(
"Original" )
17188 .writeText( result.getExpression() );
17189 m_xml.scopedElement(
"Expanded" )
17190 .writeText( result.getExpandedExpression() );
17194 switch( result.getResultType() ) {
17196 m_xml.startElement(
"Exception" );
17197 writeSourceInfo( result.getSourceInfo() );
17198 m_xml.writeText( result.getMessage() );
17199 m_xml.endElement();
17202 m_xml.startElement(
"FatalErrorCondition" );
17203 writeSourceInfo( result.getSourceInfo() );
17204 m_xml.writeText( result.getMessage() );
17205 m_xml.endElement();
17208 m_xml.scopedElement(
"Info" )
17209 .writeText( result.getMessage() );
17215 m_xml.startElement(
"Failure" );
17216 writeSourceInfo( result.getSourceInfo() );
17217 m_xml.writeText( result.getMessage() );
17218 m_xml.endElement();
17224 if( result.hasExpression() )
17225 m_xml.endElement();
17230 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17231 StreamingReporterBase::sectionEnded( sectionStats );
17232 if( --m_sectionDepth > 0 ) {
17233 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
17234 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17235 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17236 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17239 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17241 m_xml.endElement();
17245 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17246 StreamingReporterBase::testCaseEnded( testCaseStats );
17247 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
17248 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17251 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17253 if( !testCaseStats.stdOut.empty() )
17254 m_xml.scopedElement(
"StdOut" ).writeText(
trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17255 if( !testCaseStats.stdErr.empty() )
17256 m_xml.scopedElement(
"StdErr" ).writeText(
trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17258 m_xml.endElement();
17261 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17262 StreamingReporterBase::testGroupEnded( testGroupStats );
17264 m_xml.scopedElement(
"OverallResults" )
17265 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17266 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17267 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17268 m_xml.scopedElement(
"OverallResultsCases")
17269 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed )
17270 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed )
17271 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk );
17272 m_xml.endElement();
17275 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17276 StreamingReporterBase::testRunEnded( testRunStats );
17277 m_xml.scopedElement(
"OverallResults" )
17278 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17279 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17280 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17281 m_xml.scopedElement(
"OverallResultsCases")
17282 .writeAttribute(
"successes", testRunStats.totals.testCases.passed )
17283 .writeAttribute(
"failures", testRunStats.totals.testCases.failed )
17284 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk );
17285 m_xml.endElement();
17288 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17289 void XmlReporter::benchmarkPreparing(std::string
const& name) {
17290 m_xml.startElement(
"BenchmarkResults")
17291 .writeAttribute(
"name", name);
17294 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &info) {
17295 m_xml.writeAttribute(
"samples", info.samples)
17296 .writeAttribute(
"resamples", info.resamples)
17297 .writeAttribute(
"iterations", info.iterations)
17298 .writeAttribute(
"clockResolution", info.clockResolution)
17299 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17300 .writeComment(
"All values in nano seconds");
17303 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17304 m_xml.startElement(
"mean")
17305 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17306 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17307 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17308 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17309 m_xml.endElement();
17310 m_xml.startElement(
"standardDeviation")
17311 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17312 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17313 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17314 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17315 m_xml.endElement();
17316 m_xml.startElement(
"outliers")
17317 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17318 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17319 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17320 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17321 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17322 m_xml.endElement();
17323 m_xml.endElement();
17326 void XmlReporter::benchmarkFailed(std::string
const &error) {
17327 m_xml.scopedElement(
"failed").
17328 writeAttribute(
"message", error);
17329 m_xml.endElement();
17331 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17333 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17337 #if defined(_MSC_VER) 17338 #pragma warning(pop) 17343 LeakDetector leakDetector;
17347 #pragma clang diagnostic pop 17353 #ifdef CATCH_CONFIG_MAIN 17358 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) 17360 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17363 int main (
int argc,
char * argv[]) {
17366 return Catch::Session().run( argc, argv );
17372 int main (
int argc,
char *
const argv[]) {
17373 #if !CATCH_ARC_ENABLED 17374 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17377 Catch::registerTestMethods();
17378 int result = Catch::Session().run( argc, (
char**)argv );
17380 #if !CATCH_ARC_ENABLED 17392 #if !defined(CATCH_CONFIG_IMPL_ONLY) 17394 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED 17395 # undef CLARA_CONFIG_MAIN 17398 #if !defined(CATCH_CONFIG_DISABLE) 17401 #ifdef CATCH_CONFIG_PREFIX_ALL 17403 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17404 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17406 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17407 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17408 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17409 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17410 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17411 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17412 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17414 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17415 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17416 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17417 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17418 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17420 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17421 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17422 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17423 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17424 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17425 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17426 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17428 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17429 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17431 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17432 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17434 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) 17435 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg ) 17436 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17437 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) 17439 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17440 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17441 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17442 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17443 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17444 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17445 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17446 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17447 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17449 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17451 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17452 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17453 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17454 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17455 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17456 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17457 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17458 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17459 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17461 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17462 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17463 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17464 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17465 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17466 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17467 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17468 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17471 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17472 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) 17473 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) 17475 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) 17476 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) 17480 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) 17481 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17482 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17483 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17484 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17485 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17486 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17487 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17489 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17490 #define CATCH_BENCHMARK(...) \ 17491 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__,,)) 17492 #define CATCH_BENCHMARK_ADVANCED(name) \ 17493 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) 17494 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17499 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17500 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17502 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17503 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17504 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17505 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17506 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17507 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17508 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17510 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17511 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17512 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17513 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17514 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17516 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17517 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17518 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17519 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17520 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17521 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17522 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17524 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17525 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17527 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17528 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17530 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) 17531 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) 17532 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17533 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) 17535 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17536 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17537 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17538 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17539 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17540 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17541 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17542 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17543 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17544 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17546 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17547 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17548 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17549 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17550 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17551 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17552 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17553 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17554 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17555 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) 17556 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17558 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17559 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17560 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17561 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17562 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17563 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17564 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17565 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17566 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) 17567 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17570 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17571 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) 17572 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) 17574 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) 17575 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) 17580 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) 17583 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) 17584 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17586 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17587 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17588 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17589 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17590 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17591 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17593 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17594 #define BENCHMARK(...) \ 17595 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__,,)) 17596 #define BENCHMARK_ADVANCED(name) \ 17597 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name) 17598 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17602 #else // CATCH_CONFIG_DISABLE 17606 #ifdef CATCH_CONFIG_PREFIX_ALL 17608 #define CATCH_REQUIRE( ... ) (void)(0) 17609 #define CATCH_REQUIRE_FALSE( ... ) (void)(0) 17611 #define CATCH_REQUIRE_THROWS( ... ) (void)(0) 17612 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17613 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17614 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17615 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17616 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17617 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) 17619 #define CATCH_CHECK( ... ) (void)(0) 17620 #define CATCH_CHECK_FALSE( ... ) (void)(0) 17621 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) 17622 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17623 #define CATCH_CHECK_NOFAIL( ... ) (void)(0) 17625 #define CATCH_CHECK_THROWS( ... ) (void)(0) 17626 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17627 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17628 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17629 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17630 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17631 #define CATCH_CHECK_NOTHROW( ... ) (void)(0) 17633 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17634 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0) 17636 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) 17637 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17639 #define CATCH_INFO( msg ) (void)(0) 17640 #define CATCH_UNSCOPED_INFO( msg ) (void)(0) 17641 #define CATCH_WARN( msg ) (void)(0) 17642 #define CATCH_CAPTURE( msg ) (void)(0) 17644 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17645 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17646 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) 17647 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) 17648 #define CATCH_SECTION( ... ) 17649 #define CATCH_DYNAMIC_SECTION( ... ) 17650 #define CATCH_FAIL( ... ) (void)(0) 17651 #define CATCH_FAIL_CHECK( ... ) (void)(0) 17652 #define CATCH_SUCCEED( ... ) (void)(0) 17654 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17656 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17657 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17658 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17659 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17660 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17661 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17662 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17663 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17664 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17666 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17667 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17668 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17669 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17670 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17671 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17672 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17673 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17677 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17678 #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 ) 17679 #define CATCH_GIVEN( desc ) 17680 #define CATCH_AND_GIVEN( desc ) 17681 #define CATCH_WHEN( desc ) 17682 #define CATCH_AND_WHEN( desc ) 17683 #define CATCH_THEN( desc ) 17684 #define CATCH_AND_THEN( desc ) 17686 #define CATCH_STATIC_REQUIRE( ... ) (void)(0) 17687 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) 17692 #define REQUIRE( ... ) (void)(0) 17693 #define REQUIRE_FALSE( ... ) (void)(0) 17695 #define REQUIRE_THROWS( ... ) (void)(0) 17696 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17697 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17698 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17699 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17700 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17701 #define REQUIRE_NOTHROW( ... ) (void)(0) 17703 #define CHECK( ... ) (void)(0) 17704 #define CHECK_FALSE( ... ) (void)(0) 17705 #define CHECKED_IF( ... ) if (__VA_ARGS__) 17706 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17707 #define CHECK_NOFAIL( ... ) (void)(0) 17709 #define CHECK_THROWS( ... ) (void)(0) 17710 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17711 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17712 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17713 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17714 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17715 #define CHECK_NOTHROW( ... ) (void)(0) 17717 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17718 #define CHECK_THAT( arg, matcher ) (void)(0) 17720 #define REQUIRE_THAT( arg, matcher ) (void)(0) 17721 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17723 #define INFO( msg ) (void)(0) 17724 #define UNSCOPED_INFO( msg ) (void)(0) 17725 #define WARN( msg ) (void)(0) 17726 #define CAPTURE( msg ) (void)(0) 17728 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17729 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17730 #define METHOD_AS_TEST_CASE( method, ... ) 17731 #define REGISTER_TEST_CASE( Function, ... ) (void)(0) 17732 #define SECTION( ... ) 17733 #define DYNAMIC_SECTION( ... ) 17734 #define FAIL( ... ) (void)(0) 17735 #define FAIL_CHECK( ... ) (void)(0) 17736 #define SUCCEED( ... ) (void)(0) 17737 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) 17739 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17740 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17741 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17742 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17743 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17744 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17745 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17746 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17747 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17749 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17750 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17751 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17752 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17753 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17754 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17755 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17756 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17759 #define STATIC_REQUIRE( ... ) (void)(0) 17760 #define STATIC_REQUIRE_FALSE( ... ) (void)(0) 17764 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 17767 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) 17768 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) 17770 #define GIVEN( desc ) 17771 #define AND_GIVEN( desc ) 17772 #define WHEN( desc ) 17773 #define AND_WHEN( desc ) 17774 #define THEN( desc ) 17775 #define AND_THEN( desc ) 17781 #endif // ! CATCH_CONFIG_IMPL_ONLY 17787 # ifdef __ICC // icpc defines the __clang__ macro 17788 # pragma warning(pop) 17790 # pragma clang diagnostic pop 17792 #elif defined __GNUC__ 17793 # pragma GCC diagnostic pop 17798 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED T const & m_comparator
Definition: catch.hpp:3628
IntWrapper< double > Double
Definition: IntWrapper.h:140
#define CATCH_INTERNAL_ERROR(...)
Definition: catch.hpp:3901
Definition: catch.hpp:3266
virtual T const & get() const =0
Definition: catch.hpp:492
Definition: catch.hpp:2304
Definition: catch.hpp:4557
const char * const_iterator
Definition: catch.hpp:613
virtual void setGenerator(Generators::GeneratorBasePtr &&generator)=0
Definition: catch.hpp:3568
Definition: catch.hpp:1373
virtual ~IGeneratorTracker()
T valueOr(T const &defaultValue) const
Definition: catch.hpp:4447
Definition: catch.hpp:3945
void handleExpression(ITransientExpression const &expr)
What
Definition: catch.hpp:4481
bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config)
SourceLineInfo lineInfo
Definition: catch.hpp:2610
GeneratorWrapper< T > values(std::initializer_list< T > values)
Definition: catch.hpp:4009
auto operator==(StringRef const &other) const noexcept -> bool
std::size_t m_count
Definition: catch.hpp:3225
auto getResult() const -> bool
Definition: catch.hpp:2208
unsigned int sequence
Definition: catch.hpp:2612
Totals & operator+=(Totals const &other)
ChunkGenerator(size_t size, GeneratorWrapper< T > generator)
Definition: catch.hpp:4302
Option(Option const &_other)
Definition: catch.hpp:4414
std::vector< MatcherBase< ArgT > const * > m_matchers
Definition: catch.hpp:3322
std::string rawMemoryToString(const T &object)
Definition: catch.hpp:1563
std::unique_ptr< GeneratorUntypedBase > GeneratorBasePtr
Definition: catch.hpp:3859
CONSTCD11 bool operator==(const day &x, const day &y) NOEXCEPT
Definition: date.h:1274
MessageInfo m_info
Definition: catch.hpp:2642
FixedValuesGenerator(std::initializer_list< T > values)
Definition: catch.hpp:3978
const char * what() const noexcept override final
bool isFalseTest(int flags)
Definition: catch.hpp:1392
IteratorGenerator(InputIterator first, InputSentinel last)
Definition: catch.hpp:4720
ExceptionTranslatorRegistrar(std::string(*translateFunction)(T &))
Definition: catch.hpp:3056
IntWrapper< float > Float
Definition: IntWrapper.h:139
TestCase(ITestInvoker *testCase, TestCaseInfo &&info)
Option()
Definition: catch.hpp:4410
Counts testCases
Definition: catch.hpp:2855
Counts assertions
Definition: catch.hpp:2854
EqualsMatcher(std::vector< T, AllocComp > const &comparator)
Definition: catch.hpp:3664
static std::enable_if<!::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
Definition: catch.hpp:1634
Definition: catch.hpp:4666
virtual void registerTest(TestCase const &testInfo)=0
Definition: catch.hpp:1400
Definition: catch.hpp:1363
Option & operator=(Option const &_other)
Definition: catch.hpp:4422
Definition: catch.hpp:4014
void toLowerInPlace(std::string &s)
virtual StartupExceptionRegistry const & getStartupExceptionRegistry() const =0
Definition: catch.hpp:4602
std::vector< std::unique_ptr< IExceptionTranslator const > > ExceptionTranslators
Definition: catch.hpp:3012
bool m_moved
Definition: catch.hpp:2653
bool next() override
Definition: catch.hpp:3983
void handleMessage(ResultWas::OfType resultType, StringRef const &message)
std::string name
Definition: catch.hpp:4797
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)
Definition: catch.hpp:2530
constexpr const_iterator begin() const
Definition: catch.hpp:677
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
bool next() override
Definition: catch.hpp:4138
GeneratorWrapper< std::tuple< Ts... > > table(std::initializer_list< std::tuple< typename std::decay< Ts >::type... >> tuples)
Definition: catch.hpp:4058
bool contains(std::string const &s, std::string const &infix)
Exception::ExceptionMessageMatcher Message(std::string const &message)
bool match(T const &item) const override
Definition: catch.hpp:3509
CaseSensitive::Choice m_caseSensitivity
Definition: catch.hpp:3548
Verbosity
Definition: catch.hpp:4475
Definition: catch.hpp:2525
Definition: catch.hpp:490
int error
Definition: catch.hpp:2853
PredicateMatcher(std::function< bool(T const &)> const &elem, std::string const &descr)
Definition: catch.hpp:3504
auto makeUnaryExpr() const -> UnaryExpr< LhsT >
Definition: catch.hpp:2406
std::string describe() const override
Definition: catch.hpp:3678
Definition: catch.hpp:2228
CONSTCD11 day operator-(const day &x, const days &y) NOEXCEPT
Definition: date.h:1347
std::vector< StringRef > splitStringRef(StringRef str, char delimiter)
Definition: catch.hpp:2980
virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory)=0
Definition: catch.hpp:4505
#define CATCH_TRY
Definition: catch.hpp:458
virtual IConfigPtr const & getConfig() const =0
auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool
Definition: catch.hpp:2331
std::vector< std::pair< int, StringRef > > m_values
Definition: catch.hpp:1472
auto getCurrentNanosecondsSinceEpoch() -> uint64_t
T const & operator+(T const &value, StreamEndStop)
Definition: catch.hpp:542
auto getEstimatedClockResolution() -> uint64_t
std::string describe() const override
Definition: catch.hpp:3624
Definition: catch.hpp:2620
#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
Definition: catch.hpp:423
SpecialProperties properties
Definition: catch.hpp:4803
bool match(ArgT const &arg) const override
Definition: catch.hpp:3293
Definition: catch.hpp:553
std::size_t failedButOk
Definition: catch.hpp:2843
bool shouldDebugBreak
Definition: catch.hpp:2548
GeneratorWrapper(std::unique_ptr< IGenerator< T >> generator)
Definition: catch.hpp:3993
std::string toString() const
Detail::EnumInfo const & registerEnum(StringRef enumName, StringRef allEnums, std::initializer_list< E > values)
Definition: catch.hpp:1486
auto makeGenerators(as< T >, U &&val, Gs &&... moreGenerators) -> Generators< T >
Definition: catch.hpp:4079
Definition: catch.hpp:3863
TestInvokerAsMethod(void(C::*testAsMethod)()) noexcept
Definition: catch.hpp:969
Definition: catch.hpp:4773
Definition: catch.hpp:4490
SourceLineInfo(char const *_file, std::size_t _line) noexcept
Definition: catch.hpp:509
CONSTCD14 To ceil(const std::chrono::duration< Rep, Period > &d)
Definition: date.h:1186
Definition: catch.hpp:2552
virtual void popScopedMessage(MessageInfo const &message)=0
Definition: catch.hpp:3990
Definition: catch.hpp:1619
Definition: catch.hpp:4124
Definition: catch.hpp:4483
IResultCapture & getResultCapture()
std::string(*)() exceptionTranslateFunction
Definition: catch.hpp:3009
Approx & epsilon(T const &newEpsilon)
Definition: catch.hpp:3154
Capturer(StringRef macroName, SourceLineInfo const &lineInfo, ResultWas::OfType resultType, StringRef names)
static std::string convert(T const(&arr)[SZ])
Definition: catch.hpp:2052
Definition: catch.hpp:3611
std::vector< std::string > lcaseTags
Definition: catch.hpp:4801
Definition: catch.hpp:1371
GeneratorWrapper< T > value(T &&value)
Definition: catch.hpp:4005
Definition: catch.hpp:4777
StdString::RegexMatcher Matches(std::string const ®ex, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
Definition: catch.hpp:3971
std::string describe() const override
Definition: catch.hpp:3730
std::chrono::time_point< Clock, Duration > time_point
Definition: tz.h:2265
GeneratorWrapper< std::vector< T > > chunk(size_t size, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4332
double durationInSeconds
Definition: catch.hpp:2883
virtual auto hasGenerator() const -> bool=0
SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name)
virtual RunTests::InWhatOrder runOrder() const =0
Definition: catch.hpp:2656
bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis)
Definition: catch.hpp:2462
Definition: catch.hpp:3499
Definition: catch.hpp:4489
Definition: catch.hpp:4502
virtual std::vector< TestCase > const & getAllTestsSorted(IConfig const &config) const =0
bool shouldThrow
Definition: catch.hpp:2549
std::string finalizeDescription(const std::string &desc)
bool operator==(SourceLineInfo const &other) const noexcept
Definition: catch.hpp:3245
Approx operator()(T const &value)
Definition: catch.hpp:3100
SectionInfo sectionInfo
Definition: catch.hpp:2881
Definition: catch.hpp:610
virtual void handleFatalErrorCondition(StringRef message)=0
Definition: catch.hpp:1381
Flags
Definition: catch.hpp:1381
std::enable_if< std::is_floating_point< T >::value, GeneratorWrapper< T > >::type random(T a, T b)
Definition: catch.hpp:4659
UnaryExpr(LhsT lhs)
Definition: catch.hpp:2312
bool next()
Definition: catch.hpp:3999
T * operator->()
Definition: catch.hpp:4444
virtual auto getGenerator() const -> Generators::GeneratorBasePtr const &=0
StringRef(std::string const &stdString) noexcept
Definition: catch.hpp:631
Definition: catch.hpp:1365
Definition: catch.hpp:990
std::vector< std::string > tags
Definition: catch.hpp:4800
CONSTCD11 bool operator>(const day &x, const day &y) NOEXCEPT
Definition: date.h:1298
auto substr(size_type start, size_type length) const noexcept -> StringRef
std::string operator+() const
ExprLhs(LhsT lhs)
Definition: catch.hpp:2345
static std::string convert(signed char const *str)
Definition: catch.hpp:1722
IMutableRegistryHub & getMutableRegistryHub()
Counts & operator+=(Counts const &other)
#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
Definition: catch.hpp:426
void formatReconstructedExpression(std::ostream &os, std::string const &lhs, StringRef op, std::string const &rhs)
bool empty() const noexcept
Definition: catch.hpp:519
Definition: catch.hpp:3019
ITransientExpression(bool isBinaryExpression, bool result)
Definition: catch.hpp:2211
GeneratorWrapper< ResultType > from_range(Container const &cnt)
Definition: catch.hpp:4745
bool none() const
Definition: catch.hpp:4452
ScopedMessage(MessageBuilder const &builder)
std::string stringify(const T &e)
Definition: catch.hpp:1648
constexpr auto empty() const noexcept -> bool
Definition: catch.hpp:652
Definition: catch.hpp:3244
StdString::EqualsMatcher Equals(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
virtual auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const &lineInfo) -> IGeneratorTracker &=0
Definition: catch.hpp:4779
virtual ~IMutableEnumValuesRegistry()
bool next() override
Definition: catch.hpp:4617
static std::string convert(U *p)
Definition: catch.hpp:1802
virtual void registerStartupException() noexcept=0
auto generate(StringRef generatorName, SourceLineInfo const &lineInfo, L const &generatorExpression) -> decltype(std::declval< decltype(generatorExpression())>().get())
Definition: catch.hpp:4089
Definition: catch.hpp:2898
bool next() override
Definition: catch.hpp:4224
virtual void pushScopedMessage(MessageInfo const &message)=0
virtual ~ITestCaseRegistry()
ApproxMatcher(std::vector< T, AllocComp > const &comparator)
Definition: catch.hpp:3687
Vector::EqualsMatcher< T, AllocComp, AllocMatch > Equals(std::vector< T, AllocComp > const &comparator)
Definition: catch.hpp:3753
bool next() override
Definition: catch.hpp:4692
Definition: catch.hpp:2547
Vector::ContainsElementMatcher< T, Alloc > VectorContains(T const &comparator)
Definition: catch.hpp:3748
Definition: catch.hpp:4064
Definition: catch.hpp:966
auto getElapsedSeconds() const -> double
GeneratorWrapper< T > filter(Predicate &&pred, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4194
bool some() const
Definition: catch.hpp:4451
ResultDisposition::Flags resultDisposition
Definition: catch.hpp:1405
std::vector< TestCase > const & getAllTestCasesSorted(IConfig const &config)
Definition: catch.hpp:3560
auto data() const noexcept -> char const *
std::string m_operation
Definition: catch.hpp:3557
bool shouldContinueOnFailure(int flags)
Definition: catch.hpp:1358
Definition: catch.hpp:932
bool expectedToFail() const
auto str() const -> std::string
UnorderedEqualsMatcher(std::vector< T, AllocComp > const &target)
Definition: catch.hpp:3722
std::unique_ptr< T > make_unique(Args &&... args)
Definition: catch.hpp:3939
bool isJustInfo(int flags)
Definition: catch.hpp:538
Definition: catch.hpp:4488
CONSTCD11 std::chrono::duration< Rep, Period > abs(std::chrono::duration< Rep, Period > d)
Definition: date.h:1201
GeneratorException(const char *msg)
Definition: catch.hpp:3927
bool next() override
Definition: catch.hpp:4730
AutoReg(ITestInvoker *invoker, SourceLineInfo const &lineInfo, StringRef const &classOrMethod, NameAndTags const &nameAndTags) noexcept
Definition: catch.hpp:491
Definition: catch.hpp:2880
static std::string convert(R const &range)
Definition: catch.hpp:2045
GeneratorWrapper< T > range(T const &start, T const &end)
Definition: catch.hpp:4705
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
Definition: catch.hpp:3666
TestCase withName(std::string const &_newName) const
Definition: catch.hpp:4296
OrNot
Definition: catch.hpp:4487
Vector::ContainsMatcher< T, AllocComp, AllocMatch > Contains(std::vector< T, AllocComp > const &comparator)
Definition: catch.hpp:3743
Definition: catch.hpp:3243
Approx(T const &value)
Definition: catch.hpp:3109
T const & operator*() const
Definition: catch.hpp:4443
Definition: catch.hpp:929
std::string description
Definition: catch.hpp:2876
ApproxMatcher & margin(T const &newMargin)
Definition: catch.hpp:3706
Definition: catch.hpp:4497
void handleUnexpectedInflightException()
Floating::WithinAbsMatcher WithinAbs(double target, double margin)
Definition: catch.hpp:4484
int main(int argc, char *argv[])
Definition: testKaml.cpp:5
Approx & scale(T const &newScale)
Definition: catch.hpp:3168
Definition: catch.hpp:1361
Definition: catch.hpp:1360
static std::string convert(R C::*p)
Definition: catch.hpp:1813
Definition: catch.hpp:3403
Definition: catch.hpp:2342
Definition: catch.hpp:584
std::size_t failed
Definition: catch.hpp:2842
Option(T const &_value)
Definition: catch.hpp:4411
BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
Definition: catch.hpp:2239
Definition: catch.hpp:2846
static int precision
Definition: catch.hpp:1790
auto makeTestInvoker(void(*testAsFunction)()) noexcept -> ITestInvoker *
AssertionHandler(StringRef const ¯oName, SourceLineInfo const &lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition)
StringRef capturedExpression
Definition: catch.hpp:1404
Definition: catch.hpp:4160
Definition: catch.hpp:3572
Definition: catch.hpp:4778
bool shouldSuppressFailure(int flags)
signed short int sb2
Definition: standard.h:32
std::shared_ptr< IReporterFactory > IReporterFactoryPtr
Definition: catch.hpp:2967
StdString::EndsWithMatcher EndsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::string describe() const override
Definition: catch.hpp:3513
Definition: catch.hpp:3442
Definition: catch.hpp:4774
virtual ~IExceptionTranslatorRegistry()
ContainsMatcher(std::vector< T, AllocComp > const &comparator)
Definition: catch.hpp:3634
virtual bool allowThrows() const =0
bool isOk(ResultWas::OfType resultType)
ResultWas::OfType type
Definition: catch.hpp:2611
Definition: catch.hpp:3957
virtual void registerTranslator(const IExceptionTranslator *translator)=0
bool match(std::vector< T, Alloc > const &v) const override
Definition: catch.hpp:3615
ReusableStringStream m_stream
Definition: catch.hpp:2628
Definition: catch.hpp:4776
virtual int benchmarkSamples() const =0
bool operator<(MessageInfo const &other) const
Definition: catch.hpp:4494
virtual ~ITransientExpression()
Definition: catch.hpp:1366
SourceLineInfo lineInfo
Definition: catch.hpp:4802
StringRef macroName
Definition: catch.hpp:2608
Definition: catch.hpp:4500
#define CATCH_CONFIG_CONSOLE_WIDTH
Definition: TestUtilsMain.cpp:6
Definition: catch.hpp:4775
TestCaseInfo const & getTestCaseInfo() const
bool operator<(SourceLineInfo const &other) const noexcept
void handleThrowingCallSkipped()
void handleExceptionThrownAsExpected()
Definition: catch.hpp:2969
Totals operator-(Totals const &other) const
bool match(std::vector< T, AllocMatch > const &v) const override
Definition: catch.hpp:3689
Definition: catch.hpp:4481
Definition: catch.hpp:506
virtual std::string translateActiveException() const =0
Definition: catch.hpp:4493
Definition: catch.hpp:4495
std::string className
Definition: catch.hpp:4798
std::string m_label
Definition: catch.hpp:3226
Definition: catch.hpp:3662
Definition: catch.hpp:1382
constexpr const_iterator end() const
Definition: catch.hpp:678
void captureValues(size_t index, T const &value)
Definition: catch.hpp:2667
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)
Definition: catch.hpp:4408
#define CATCH_INTERNAL_LINEINFO
Definition: catch.hpp:547
Definition: catch.hpp:1437
static std::string convert(char const *str)
Definition: catch.hpp:1716
std::vector< T, AllocComp > const & m_comparator
Definition: catch.hpp:3658
#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
Definition: catch.hpp:432
CONSTCD11 bool operator>=(const day &x, const day &y) NOEXCEPT
Definition: date.h:1314
bool next() override
Definition: catch.hpp:4045
Definition: catch.hpp:3552
SingleValueGenerator(T &&value)
Definition: catch.hpp:3960
StringRef macroName
Definition: catch.hpp:1402
Definition: catch.hpp:3014
Definition: catch.hpp:1470
std::string toLower(std::string const &s)
~AssertionHandler()
Definition: catch.hpp:2564
YesOrNo
Definition: catch.hpp:4497
Definition: catch.hpp:4482
void captureValues(size_t index, T const &value, Ts const &... values)
Definition: catch.hpp:2672
Definition: catch.hpp:495
char const * file
Definition: catch.hpp:523
SpecialProperties
Definition: catch.hpp:4772
bool match(std::vector< T, AllocMatch > const &vec) const override
Definition: catch.hpp:3723
bool isThrowSafe(TestCase const &testCase, IConfig const &config)
Definition: catch.hpp:3685
std::string translateActiveException()
#define CATCH_CATCH_ALL
Definition: catch.hpp:459
Definition: catch.hpp:1444
virtual ~IMutableContext()
virtual void streamReconstructedExpression(std::ostream &os) const =0
bool next() override
Definition: catch.hpp:4319
Definition: catch.hpp:3458
std::vector< T, AllocComp > const & m_comparator
Definition: catch.hpp:3716
Definition: catch.hpp:2915
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 &)
Definition: catch.hpp:1586
Definition: catch.hpp:4487
virtual ITestCaseRegistry const & getTestCaseRegistry() const =0
void handleExpr(ExprLhs< T > const &expr)
Definition: catch.hpp:2571
CONSTCD11 bool operator!=(const day &x, const day &y) NOEXCEPT
Definition: date.h:1282
Definition: catch.hpp:1370
bool match(ArgT const &arg) const override
Definition: catch.hpp:3364
bool next() override
Definition: catch.hpp:3965
ContainsElementMatcher(T const &comparator)
Definition: catch.hpp:3613
std::string name
Definition: catch.hpp:2875
bool operator<(TestCase const &other) const
void discard(uint64_t skip)
std::size_t total() const
Definition: catch.hpp:4511
int add(int code, T value)
Definition: HashCoder.h:34
Definition: catch.hpp:4504
IContext & getCurrentContext()
Definition: catch.hpp:4388
Definition: catch.hpp:4839
Definition: catch.hpp:3284
Definition: catch.hpp:3542
void throw_logic_error(std::string const &msg)
bool match(ArgT const &arg) const override
Definition: catch.hpp:3327
auto operator+=(std::string &lhs, StringRef const &sr) -> std::string &
GeneratorWrapper< T > repeat(size_t repeats, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4250
RegistrarForTagAliases(char const *alias, char const *tag, SourceLineInfo const &lineInfo)
RangeGenerator(T const &start, T const &end, T const &step)
Definition: catch.hpp:4673
std::string m_str
Definition: catch.hpp:3549
CONSTDATA date::last_spec last
Definition: date.h:1834
virtual double benchmarkConfidenceInterval() const =0
void type
Definition: catch.hpp:1998
std::string to_string(std::uint64_t x)
Definition: date.h:7722
virtual ~IMutableRegistryHub()
Definition: catch.hpp:1385
MessageBuilder(StringRef const ¯oName, SourceLineInfo const &lineInfo, ResultWas::OfType type)
Definition: catch.hpp:940
std::string describe() const override
Definition: catch.hpp:3654
void throw_exception(std::exception const &e)
Definition: catch.hpp:4711
Definition: catch.hpp:3774
Definition: catch.hpp:1357
constexpr auto size() const noexcept -> size_type
Definition: catch.hpp:655
ApproxMatcher & epsilon(T const &newEpsilon)
Definition: catch.hpp:3701
Definition: catch.hpp:3632
StringRef m_name
Definition: catch.hpp:1471
auto getElapsedNanoseconds() const -> uint64_t
virtual void registerListener(IReporterFactoryPtr const &factory)=0
Definition: catch.hpp:4492
void streamReconstructedExpression(std::ostream &os) const override
Definition: catch.hpp:3786
void seed(result_type seed_)
When
Definition: catch.hpp:4502
typename std::remove_reference< typename std::remove_cv< typename std::result_of< Func(U...)>::type >::type >::type FunctionReturnType
Definition: catch.hpp:953
auto getElapsedMicroseconds() const -> uint64_t
SourceLineInfo lineInfo
Definition: catch.hpp:1403
MapGenerator(F2 &&function, GeneratorWrapper< U > &&generator)
Definition: catch.hpp:4263
bool operator==(TestCase const &other) const
const std::string unprintableString
Definition: catch.hpp:4771
const T * operator->() const
Definition: catch.hpp:4445
static std::enable_if<::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
Definition: catch.hpp:1623
#define CATCH_ENFORCE(condition,...)
Definition: catch.hpp:3910
virtual void handleIncomplete(AssertionInfo const &info)=0
auto parse(const std::basic_string< CharT, Traits, Alloc > &format, Parsable &tp) -> decltype(from_stream(std::declval< std::basic_istream< CharT, Traits > &>(), format.c_str(), tp), parse_manip< Parsable, CharT, Traits, Alloc >
Definition: date.h:7239
std::string rangeToString(std::vector< bool, Allocator > const &v)
Definition: catch.hpp:2028
Definition: catch.hpp:3923
auto isBinaryExpression() const -> bool
Definition: catch.hpp:2207
Definition: catch.hpp:1480
ApproxMatcher & scale(T const &newScale)
Definition: catch.hpp:3711
Definition: Exception.h:13
virtual std::chrono::milliseconds benchmarkWarmupTime() const =0
Definition: catch.hpp:576
MessageInfo(StringRef const &_macroName, SourceLineInfo const &_lineInfo, ResultWas::OfType _type)
bool next() override
Definition: catch.hpp:4639
std::string m_cachedToString
Definition: catch.hpp:3257
bool match(std::vector< T, AllocMatch > const &v) const override
Definition: catch.hpp:3636
Definition: catch.hpp:958
Section(SectionInfo const &info)
Definition: catch.hpp:4498
Definition: catch.hpp:3247
virtual IReporterRegistry const & getReporterRegistry() const =0
Definition: catch.hpp:2206
Definition: catch.hpp:3577
std::vector< MatcherBase< ArgT > const * > m_matchers
Definition: catch.hpp:3356
Counts prevAssertions
Definition: catch.hpp:2882
Definition: catch.hpp:4624
virtual IResultCapture * getResultCapture()=0
std::string describe() const override
Definition: catch.hpp:3697
MatchAllOf< T > operator&&(MatcherBase const &other) const
constexpr auto isNullTerminated() const noexcept -> bool
Definition: catch.hpp:672
bool next() override
Definition: catch.hpp:4183
Definition: catch.hpp:4806
FilterGenerator(P &&pred, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4165
Definition: catch.hpp:4255
Definition: catch.hpp:4199
virtual unsigned int rngSeed() const =0
Definition: catch.hpp:3721
MessageInfo m_info
Definition: catch.hpp:2652
Totals delta(Totals const &prevTotals) const
auto makeMatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString) -> MatchExpr< ArgT, MatcherT >
Definition: catch.hpp:3801
RandomIntegerGenerator(Integer a, Integer b)
Definition: catch.hpp:4630
std::size_t passed
Definition: catch.hpp:2841
StdString::StartsWithMatcher StartsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::enable_if< std::is_enum< T >::value, std::string >::type convertUnstreamable(T const &value)
Definition: catch.hpp:1599
std::size_t line
Definition: catch.hpp:524
Approx & margin(T const &newMargin)
Definition: catch.hpp:3161
std::string convertUnknownEnumToString(E e)
Definition: catch.hpp:1653
Definition: catch.hpp:1386
ExceptionMessageMatcher(std::string const &message)
Definition: catch.hpp:3407
std::string describe() const override
Definition: catch.hpp:3334
RepeatGenerator(size_t repeats, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4209
MatchNotOf< T > operator!() const
Definition: catch.hpp:3383
Definition: catch.hpp:2864
Definition: catch.hpp:3849
virtual void sectionEnded(SectionEndInfo const &endInfo)=0
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff)
void throw_domain_error(std::string const &msg)
Definition: catch.hpp:2603
Definition: catch.hpp:2011
void handleExceptionMatchExpr(AssertionHandler &handler, std::string const &str, StringRef const &matcherString)
Definition: catch.hpp:4506
MatcherBase< ArgT > const & m_underlyingMatcher
Definition: catch.hpp:3371
auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const &lineInfo) -> IGeneratorTracker &
#define CATCH_RUNTIME_ERROR(...)
Definition: catch.hpp:3907
Definition: catch.hpp:3082
virtual IExceptionTranslatorRegistry const & getExceptionTranslatorRegistry() const =0
Definition: catch.hpp:3220
Definition: catch.hpp:4503
IMutableContext & getCurrentMutableContext()
Definition: catch.hpp:4380
bool next() override
Definition: catch.hpp:4272
T & operator*()
Definition: catch.hpp:4442
IRegistryHub const & getRegistryHub()
Definition: catch.hpp:4366
virtual ~IExceptionTranslator()
std::uint32_t result_type
Definition: catch.hpp:4560
CONSTCD11 bool operator<(const day &x, const day &y) NOEXCEPT
Definition: date.h:1290
std::size_t size_type
Definition: catch.hpp:612
Generic::PredicateMatcher< T > Predicate(std::function< bool(T const &)> const &predicate, std::string const &description="")
Definition: catch.hpp:3525
Definition: catch.hpp:4499
void reset()
Definition: catch.hpp:4436
void handleUnexpectedExceptionNotThrown()
Definition: catch.hpp:2631
Definition: catch.hpp:1568
virtual bool benchmarkNoAnalysis() const =0
MatchAnyOf< T > operator||(MatcherBase const &other) const
Definition: catch.hpp:3379
std::string description
Definition: catch.hpp:4799
auto compareEqual(LhsT const &lhs, RhsT const &rhs) -> bool
Definition: catch.hpp:2320
Definition: catch.hpp:3564
void captureValue(size_t index, std::string const &value)
SourceLineInfo lineInfo
Definition: catch.hpp:2877
std::shared_ptr< IConfig const > IConfigPtr
Definition: catch.hpp:4355
Definition: catch.hpp:2002
MatchNotOf(MatcherBase< ArgT > const &underlyingMatcher)
Definition: catch.hpp:3362
virtual void sectionEndedEarly(SectionEndInfo const &endInfo)=0
std::string message
Definition: catch.hpp:2609
std::string describe() const override
Definition: catch.hpp:3368
Definition: catch.hpp:485
Choice
Definition: catch.hpp:490
~Option()
Definition: catch.hpp:4418
Definition: catch.hpp:3433
virtual ~IResultCapture()
OfType
Definition: catch.hpp:1357
CasedString m_comparator
Definition: catch.hpp:3556
Generators(Gs &&... moreGenerators)
Definition: catch.hpp:4036
std::string describe() const override
Definition: catch.hpp:3300
MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
Definition: catch.hpp:3779
RandomFloatingGenerator(Float a, Float b)
Definition: catch.hpp:4608
virtual void setConfig(IConfigPtr const &config)=0
Definition: catch.hpp:1997
virtual unsigned int benchmarkResamples() const =0
std::string rangeToString(Range const &range)
Definition: catch.hpp:2022
void invoke() const override
Definition: catch.hpp:971
os exceptions(std::ios::failbit|std::ios::badbit)
Vector::ApproxMatcher< T, AllocComp, AllocMatch > Approx(std::vector< T, AllocComp > const &comparator)
Definition: catch.hpp:3758
SimplePcg32()
Definition: catch.hpp:4569
bool m_result
Definition: catch.hpp:2221
auto makeStream(StringRef const &filename) -> IStream const *
static std::string convert(unsigned char const *str)
Definition: catch.hpp:1728
Definition: catch.hpp:2418
GeneratorWrapper< T > map(Func &&function, GeneratorWrapper< U > &&generator)
Definition: catch.hpp:4282
Definition: catch.hpp:3025
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)
Definition: catch.hpp:2833
virtual ITagAliasRegistry const & getTagAliasRegistry() const =0
static int precision
Definition: catch.hpp:1796
std::vector< T, AllocComp > const & m_comparator
Definition: catch.hpp:3681
constexpr StringRef() noexcept=default
Definition: catch.hpp:1384
#define CATCH_CATCH_ANON(type)
Definition: catch.hpp:460
T const & get() const
Definition: catch.hpp:3996
pluralise(std::size_t count, std::string const &label)
bool m_isBinaryExpression
Definition: catch.hpp:2220
auto get() -> std::ostream &
Definition: catch.hpp:1458
Definition: catch.hpp:1368
GeneratorWrapper< T > take(size_t target, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4155
Definition: catch.hpp:4357
Definition: catch.hpp:2645
Definition: catch.hpp:1359
#define CATCH_ERROR(...)
Definition: catch.hpp:3904
Vector::UnorderedEqualsMatcher< T, AllocComp, AllocMatch > UnorderedEquals(std::vector< T, AllocComp > const &target)
Definition: catch.hpp:3763
InWhatOrder
Definition: catch.hpp:4492
KAML::Manager Config
Definition: testKaml.cpp:3
TakeGenerator(size_t target, GeneratorWrapper< T > &&generator)
Definition: catch.hpp:4129
bool startsWith(std::string const &s, std::string const &prefix)
Floating::WithinRelMatcher WithinRel(float target)
CONSTCD11 bool operator<=(const day &x, const day &y) NOEXCEPT
Definition: date.h:1306
RangeGenerator(T const &start, T const &end)
Definition: catch.hpp:4684
bool operator==(MessageInfo const &other) const
Definition: catch.hpp:931
auto getElapsedMilliseconds() const -> unsigned int