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 9 21 # pragma clang system_header 22 #elif defined __GNUC__ 23 # pragma GCC system_header 29 # ifdef __ICC // icpc defines the __clang__ macro 30 # pragma warning(push) 31 # pragma warning(disable: 161 1682) 33 # pragma clang diagnostic push 34 # pragma clang diagnostic ignored "-Wpadded" 35 # pragma clang diagnostic ignored "-Wswitch-enum" 36 # pragma clang diagnostic ignored "-Wcovered-switch-default" 38 #elif defined __GNUC__ 42 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details 44 # pragma GCC diagnostic push 45 # pragma GCC diagnostic ignored "-Wunused-variable" 46 # pragma GCC diagnostic ignored "-Wpadded" 49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) 51 # define CATCH_CONFIG_ALL_PARTS 56 #if defined(CATCH_CONFIG_ALL_PARTS) 57 # define CATCH_CONFIG_EXTERNAL_INTERFACES 58 # if defined(CATCH_CONFIG_DISABLE_MATCHERS) 59 # undef CATCH_CONFIG_DISABLE_MATCHERS 61 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 62 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 66 #if !defined(CATCH_CONFIG_IMPL_ONLY) 72 # include <TargetConditionals.h> 73 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ 74 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) 75 # define CATCH_PLATFORM_MAC 76 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) 77 # define CATCH_PLATFORM_IPHONE 80 #elif defined(linux) || defined(__linux) || defined(__linux__) 81 # define CATCH_PLATFORM_LINUX 83 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) 84 # define CATCH_PLATFORM_WINDOWS 90 # ifndef CLARA_CONFIG_MAIN 91 # define CLARA_CONFIG_MAIN_NOT_DEFINED 92 # define CLARA_CONFIG_MAIN 99 unsigned int rngSeed();
128 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) 129 # define CATCH_CPP14_OR_GREATER 132 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) 133 # define CATCH_CPP17_OR_GREATER 140 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) 141 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) 142 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) 144 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) 148 #if defined(__clang__) 150 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) 151 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) 164 # if !defined(__ibmxl__) && !defined(__CUDACC__) 165 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) 168 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 169 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ 170 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") 172 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 173 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) 175 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 176 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) 178 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 179 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) 181 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 182 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) 188 #if !defined(CATCH_PLATFORM_WINDOWS) 189 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS 194 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) 195 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS 199 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS 200 # define CATCH_CONFIG_COLOUR_NONE 205 #if defined(__ANDROID__) 206 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING 207 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE 212 #if defined(__MINGW32__) 213 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH 218 #if defined(__ORBIS__) 219 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE 231 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ 232 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) 234 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING 241 #if defined(_MSC_VER) 245 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) 246 # define CATCH_CONFIG_COLOUR_NONE 248 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH 251 # if !defined(__clang__) // Handle Clang masquerading for msvc 256 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) 257 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 258 # endif // MSVC_TRADITIONAL 261 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) 262 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) 267 #if defined(_REENTRANT) || defined(_MSC_VER) 269 # define CATCH_INTERNAL_CONFIG_USE_ASYNC 274 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) 275 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED 281 # define CATCH_INTERNAL_CONFIG_NO_WCHAR 286 #if defined(__BORLANDC__) 287 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN 297 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) 298 #define CATCH_INTERNAL_CONFIG_COUNTER 306 #if defined(UNDER_RTSS) || defined(RTX64_BUILD) 307 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH 308 #define CATCH_INTERNAL_CONFIG_NO_ASYNC 309 #define CATCH_CONFIG_COLOUR_NONE 312 #if !defined(_GLIBCXX_USE_C99_MATH_TR1) 313 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER 317 #if defined(__has_include) 319 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER) 320 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW 324 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 325 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL 326 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER) 329 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER) 331 # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) 332 # 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_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) 377 # define CATCH_CONFIG_CPP17_STRING_VIEW 380 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) 381 # define CATCH_CONFIG_CPP17_VARIANT 384 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) 385 # define CATCH_CONFIG_CPP17_BYTE 388 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 389 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE 392 #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) 393 # define CATCH_CONFIG_NEW_CAPTURE 396 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 397 # define CATCH_CONFIG_DISABLE_EXCEPTIONS 400 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) 401 # define CATCH_CONFIG_POLYFILL_ISNAN 404 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) 405 # define CATCH_CONFIG_USE_ASYNC 408 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) 409 # define CATCH_CONFIG_ANDROID_LOGWRITE 412 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 413 # define CATCH_CONFIG_GLOBAL_NEXTAFTER 418 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) 419 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION 421 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) 422 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 424 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) 425 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS 427 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) 428 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS 430 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) 431 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS 433 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) 434 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS 439 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) 440 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) 443 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) 444 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 445 #elif defined(__clang__) && (__clang_major__ < 5) 446 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 449 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) 450 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS 453 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 454 #define CATCH_TRY if ((true)) 455 #define CATCH_CATCH_ALL if ((false)) 456 #define CATCH_CATCH_ANON(type) if ((false)) 458 #define CATCH_TRY try 459 #define CATCH_CATCH_ALL catch (...) 460 #define CATCH_CATCH_ANON(type) catch (type) 463 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) 464 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 468 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line 469 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) 470 #ifdef CATCH_CONFIG_COUNTER 471 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) 473 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) 515 bool empty()
const noexcept {
return file[0] ==
'\0'; }
523 std::ostream& operator << ( std::ostream& os,
SourceLineInfo const& info );
535 std::string operator+()
const;
543 #define CATCH_INTERNAL_LINEINFO \ 544 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) 555 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ 556 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 557 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 558 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ 559 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 573 virtual void invoke ()
const = 0;
582 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
583 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const = 0;
587 bool matchTest(
TestCase const& testCase, TestSpec
const& testSpec,
IConfig const& config );
588 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
589 std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config );
608 using size_type = std::size_t;
609 using const_iterator =
const char*;
612 static constexpr
char const*
const s_empty =
"";
614 char const* m_start = s_empty;
615 size_type m_size = 0;
618 constexpr
StringRef() noexcept =
default;
620 StringRef(
char const* rawChars ) noexcept;
622 constexpr
StringRef(
char const* rawChars, size_type size ) noexcept
623 : m_start( rawChars ),
627 StringRef( std::string
const& stdString ) noexcept
628 : m_start( stdString.c_str() ),
629 m_size( stdString.size() )
632 explicit operator std::string()
const {
633 return std::string(m_start, m_size);
637 auto operator == (
StringRef const& other )
const noexcept -> bool;
638 auto operator != (
StringRef const& other)
const noexcept ->
bool {
639 return !(*
this == other);
642 auto operator[] ( size_type index )
const noexcept ->
char {
643 assert(index < m_size);
644 return m_start[index];
648 constexpr
auto empty()
const noexcept ->
bool {
651 constexpr
auto size()
const noexcept -> size_type {
657 auto c_str()
const ->
char const*;
663 auto substr( size_type start, size_type length )
const noexcept ->
StringRef;
666 auto data()
const noexcept ->
char const*;
668 constexpr
auto isNullTerminated()
const noexcept ->
bool {
669 return m_start[m_size] ==
'\0';
673 constexpr const_iterator begin()
const {
return m_start; }
674 constexpr const_iterator end()
const {
return m_start + m_size; }
677 auto operator += ( std::string& lhs,
StringRef const& sr ) -> std::string&;
678 auto operator << ( std::ostream& os,
StringRef const& sr ) -> std::ostream&;
680 constexpr
auto operator "" _sr(
char const* rawChars, std::size_t size ) noexcept ->
StringRef {
685 constexpr
auto operator "" _catch_sr(
char const* rawChars, std::size_t size ) noexcept ->
Catch::StringRef {
693 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ 694 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) 695 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) 696 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) 697 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) 698 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) 700 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 701 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ 703 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) 704 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) 706 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) 709 #define CATCH_REC_END(...) 710 #define CATCH_REC_OUT 712 #define CATCH_EMPTY() 713 #define CATCH_DEFER(id) id CATCH_EMPTY() 715 #define CATCH_REC_GET_END2() 0, CATCH_REC_END 716 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 717 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 718 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT 719 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) 720 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) 722 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 723 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) 724 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) 726 #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__ ) 727 #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__ ) 728 #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__ ) 733 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 735 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) 737 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) 738 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ 739 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ 740 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF 741 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) 742 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 743 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ 744 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) 747 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) 748 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ 749 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) 752 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ 753 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) 755 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) 757 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 758 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()) 759 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) 761 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())) 762 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) 765 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ 766 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) 768 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) 769 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) 770 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) 771 #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) 772 #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) 773 #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) 774 #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) 775 #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) 776 #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) 777 #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) 778 #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) 780 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N 782 #define INTERNAL_CATCH_TYPE_GEN\ 783 template<typename...> struct TypeList {};\ 784 template<typename...Ts>\ 785 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\ 786 template<template<typename...> class...> struct TemplateTypeList{};\ 787 template<template<typename...> class...Cs>\ 788 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\ 789 template<typename...>\ 791 template<typename...>\ 793 template<template<typename...> class, typename...>\ 795 template<template<typename...> class, typename>\ 798 template<typename T> \ 799 struct append<T> { using type = T; };\ 800 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\ 801 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\ 802 template< template<typename...> class L1, typename...E1, typename...Rest>\ 803 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\ 805 template< template<typename...> class Container, template<typename...> class List, typename...elems>\ 806 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\ 807 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\ 808 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\ 810 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\ 811 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\ 812 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\ 813 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; }; 815 #define INTERNAL_CATCH_NTTP_1(signature, ...)\ 816 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\ 817 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 818 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \ 819 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\ 820 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\ 821 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \ 823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 824 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\ 825 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\ 826 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\ 827 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\ 828 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; }; 830 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName) 831 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\ 832 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 833 static void TestName() 834 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\ 835 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 836 static void TestName() 838 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName) 839 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\ 840 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 841 static void TestName() 842 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\ 843 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 844 static void TestName() 846 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\ 847 template<typename Type>\ 848 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\ 850 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 853 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\ 854 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 855 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\ 857 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\ 860 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\ 861 template<typename Type>\ 862 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 864 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 867 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\ 868 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\ 869 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\ 871 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\ 874 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName) 875 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\ 876 template<typename TestType> \ 877 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \ 881 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\ 882 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 883 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \ 887 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName) 888 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\ 889 template<typename TestType> \ 890 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test() 891 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\ 892 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \ 893 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test() 895 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 896 #define INTERNAL_CATCH_NTTP_0 897 #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) 898 #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__) 899 #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__) 900 #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__) 901 #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__) 902 #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__) 903 #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__) 904 #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__) 906 #define INTERNAL_CATCH_NTTP_0(signature) 907 #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__)) 908 #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__)) 909 #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__)) 910 #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__)) 911 #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__)) 912 #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__)) 913 #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__)) 914 #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__)) 921 #include <type_traits> 929 template <
typename Fun,
typename... Args>
931 template <
typename...>
932 std::false_type
static test(...);
935 template <
typename T>
938 template <
typename Fun,
typename... Args>
939 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
941 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703 944 template <
typename Func,
typename... U>
945 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
948 template <
typename Func,
typename... U>
949 using FunctionReturnType =
typename std::remove_reference<
typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
963 void (C::*m_testAsMethod)();
965 TestInvokerAsMethod(
void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
967 void invoke()
const override {
969 (obj.*m_testAsMethod)();
973 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept ->
ITestInvoker*;
976 auto makeTestInvoker(
void (C::*testAsMethod)() ) noexcept ->
ITestInvoker* {
993 #if defined(CATCH_CONFIG_DISABLE) 994 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ 995 static void TestName() 996 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ 998 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1002 void TestName::test() 1003 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \ 1004 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1005 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1007 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1008 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1011 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1013 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1014 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1015 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__ ) 1017 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \ 1018 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__ ) ) 1021 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1022 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1023 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__ ) 1025 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \ 1026 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__ ) ) 1029 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1030 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1031 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__ ) 1033 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \ 1034 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__ ) ) 1037 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1038 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1039 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__ ) 1041 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \ 1042 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__ ) ) 1047 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ 1048 static void TestName(); \ 1049 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1050 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1051 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1052 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1053 static void TestName() 1054 #define INTERNAL_CATCH_TESTCASE( ... ) \ 1055 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), __VA_ARGS__ ) 1058 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ 1059 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1060 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1061 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } \ 1062 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1065 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ 1066 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1067 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1069 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ 1072 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \ 1074 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1075 void TestName::test() 1076 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ 1077 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), ClassName, __VA_ARGS__ ) 1080 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ 1081 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1082 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1083 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \ 1084 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 1087 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\ 1088 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1089 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1090 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1091 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1092 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1094 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1095 INTERNAL_CATCH_TYPE_GEN\ 1096 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1097 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1098 template<typename...Types> \ 1102 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1103 using expander = int[];\ 1104 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... }; \ 1107 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1108 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1113 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1114 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1116 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1117 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1118 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__ ) 1120 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ 1121 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__ ) ) 1124 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1125 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1126 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__ ) 1128 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \ 1129 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__ ) ) 1132 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \ 1133 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1134 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1135 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1136 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1137 template<typename TestType> static void TestFuncName(); \ 1139 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \ 1140 INTERNAL_CATCH_TYPE_GEN \ 1141 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \ 1142 template<typename... Types> \ 1144 void reg_tests() { \ 1146 using expander = int[]; \ 1147 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1148 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1149 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1150 (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++)... };\ 1153 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1154 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; \ 1161 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1162 template<typename TestType> \ 1163 static void TestFuncName() 1165 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1166 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1167 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__) 1169 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ 1170 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__ ) ) 1173 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1174 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1175 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__) 1177 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\ 1178 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__ ) ) 1181 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\ 1182 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1183 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1184 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1185 template<typename TestType> static void TestFunc(); \ 1187 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\ 1188 INTERNAL_CATCH_TYPE_GEN\ 1189 template<typename... Types> \ 1191 void reg_tests() { \ 1193 using expander = int[]; \ 1194 (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++)... };\ 1197 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ 1198 using TestInit = typename convert<TestName, TmplList>::type; \ 1204 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1205 template<typename TestType> \ 1206 static void TestFunc() 1208 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \ 1209 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 ) 1211 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \ 1212 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1213 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1214 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1215 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1217 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1218 INTERNAL_CATCH_TYPE_GEN\ 1219 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1220 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\ 1221 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1222 template<typename...Types> \ 1223 struct TestNameClass{\ 1226 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\ 1227 using expander = int[];\ 1228 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... }; \ 1231 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1232 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\ 1237 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1238 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) 1240 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1241 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1242 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__ ) 1244 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ 1245 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__ ) ) 1248 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1249 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1250 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__ ) 1252 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \ 1253 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__ ) ) 1256 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\ 1257 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1258 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1259 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ 1260 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1261 template<typename TestType> \ 1262 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1266 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\ 1267 INTERNAL_CATCH_TYPE_GEN \ 1268 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\ 1269 template<typename...Types>\ 1270 struct TestNameClass{\ 1273 using expander = int[];\ 1274 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ 1275 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ 1276 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ 1277 (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++)... }; \ 1280 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1281 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;\ 1288 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1289 template<typename TestType> \ 1290 void TestName<TestType>::test() 1292 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1293 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1294 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__ ) 1296 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ 1297 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__ ) ) 1300 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 1301 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1302 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__ ) 1304 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\ 1305 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__ ) ) 1308 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \ 1309 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 1310 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 1311 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ 1312 template<typename TestType> \ 1313 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \ 1317 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \ 1318 INTERNAL_CATCH_TYPE_GEN\ 1319 template<typename...Types>\ 1320 struct TestNameClass{\ 1323 using expander = int[];\ 1324 (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++)... }; \ 1327 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ 1328 using TestInit = typename convert<TestNameClass, TmplList>::type;\ 1334 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 1335 template<typename TestType> \ 1336 void TestName<TestType>::test() 1338 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \ 1339 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 ) 1361 ExpressionFailed = FailureBit | 1,
1362 ExplicitFailure = FailureBit | 2,
1364 Exception = 0x100 | FailureBit,
1366 ThrewException = Exception | 1,
1367 DidntThrowException = Exception | 2,
1369 FatalErrorCondition = 0x200 | FailureBit
1373 bool isOk( ResultWas::OfType resultType );
1374 bool isJustInfo(
int flags );
1380 ContinueOnFailure = 0x02,
1385 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1387 bool shouldContinueOnFailure(
int flags );
1388 inline bool isFalseTest(
int flags ) {
return ( flags & ResultDisposition::FalseTest ) != 0; }
1389 bool shouldSuppressFailure(
int flags );
1401 ResultDisposition::Flags resultDisposition;
1417 #include <type_traits> 1427 std::ostream& cout();
1428 std::ostream& cerr();
1429 std::ostream& clog();
1435 virtual std::ostream& stream()
const = 0;
1441 std::size_t m_index;
1442 std::ostream* m_oss;
1447 auto str()
const -> std::string;
1449 template<
typename T>
1454 auto get() -> std::ostream& {
return *m_oss; }
1468 std::vector<std::pair<int, StringRef>> m_values;
1481 template<
typename E>
1483 static_assert(
sizeof(
int) >=
sizeof(E),
"Cannot serialize enum to int");
1484 std::vector<int> intValues;
1485 intValues.reserve( values.size() );
1486 for(
auto enumValue : values )
1487 intValues.push_back( static_cast<int>( enumValue ) );
1488 return registerEnum( enumName, allEnums, intValues );
1496 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1497 #include <string_view> 1503 #import <Foundation/Foundation.h> 1505 #ifdef __has_feature 1506 #define CATCH_ARC_ENABLED __has_feature(objc_arc) 1508 #define CATCH_ARC_ENABLED 0 1511 void arcSafeRelease( NSObject* obj );
1512 id performOptionalSelector(
id obj,
SEL sel );
1514 #if !CATCH_ARC_ENABLED 1515 inline void arcSafeRelease( NSObject* obj ) {
1518 inline id performOptionalSelector(
id obj,
SEL sel ) {
1519 if( [obj respondsToSelector: sel] )
1520 return [obj performSelector: sel];
1523 #define CATCH_UNSAFE_UNRETAINED 1524 #define CATCH_ARC_STRONG 1526 inline void arcSafeRelease( NSObject* ){}
1527 inline id performOptionalSelector(
id obj,
SEL sel ) {
1529 #pragma clang diagnostic push 1530 #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 1532 if( [obj respondsToSelector: sel] )
1533 return [obj performSelector: sel];
1535 #pragma clang diagnostic pop 1539 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained 1540 #define CATCH_ARC_STRONG __strong 1547 #pragma warning(push) 1548 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless 1554 extern const std::string unprintableString;
1556 std::string rawMemoryToString(
const void *
object, std::size_t size );
1558 template<
typename T>
1559 std::string rawMemoryToString(
const T&
object ) {
1560 return rawMemoryToString( &
object,
sizeof(
object) );
1563 template<
typename T>
1565 template<
typename Stream,
typename U>
1566 static auto test(
int)
1567 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1569 template<
typename,
typename>
1570 static auto test(...)->std::false_type;
1576 template<
typename E>
1577 std::string convertUnknownEnumToString( E e );
1579 template<
typename T>
1580 typename std::enable_if<
1581 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1582 std::string>::type convertUnstreamable( T
const& ) {
1583 return Detail::unprintableString;
1585 template<
typename T>
1586 typename std::enable_if<
1587 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1588 std::string>::type convertUnstreamable(T
const& ex) {
1592 template<
typename T>
1593 typename std::enable_if<
1594 std::is_enum<T>::value
1595 , std::string>::type convertUnstreamable( T
const& value ) {
1596 return convertUnknownEnumToString( value );
1599 #if defined(_MANAGED) 1600 template<
typename T>
1602 std::string clrReferenceToString( T^ ref ) {
1604 return std::string(
"null");
1605 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1606 cli::pin_ptr<System::Byte> p = &bytes[0];
1607 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1614 template <
typename T,
typename =
void>
1616 template <
typename Fake = T>
1618 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1619 convert(
const Fake& value) {
1623 rss.operator<<(value);
1627 template <
typename Fake = T>
1629 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1630 convert(
const Fake& value ) {
1631 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) 1632 return Detail::convertUnstreamable(value);
1634 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1643 template <
typename T>
1644 std::string stringify(
const T& e) {
1645 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1648 template<
typename E>
1649 std::string convertUnknownEnumToString( E e ) {
1650 return ::Catch::Detail::stringify(
static_cast<typename std::underlying_type<E>::type
>(e));
1653 #if defined(_MANAGED) 1654 template <
typename T>
1655 std::string stringify( T^ e ) {
1656 return ::Catch::StringMaker<T^>::convert(e);
1666 static std::string convert(
const std::string& str);
1669 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1672 static std::string convert(std::string_view str);
1678 static std::string convert(
char const * str);
1682 static std::string convert(
char * str);
1685 #ifdef CATCH_CONFIG_WCHAR 1688 static std::string convert(
const std::wstring& wstr);
1691 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 1694 static std::string convert(std::wstring_view str);
1700 static std::string convert(
wchar_t const * str);
1704 static std::string convert(
wchar_t * str);
1712 static std::string convert(
char const* str) {
1713 return ::Catch::Detail::stringify(std::string{ str });
1718 static std::string convert(
signed char const* str) {
1719 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const *
>(str) });
1724 static std::string convert(
unsigned char const* str) {
1725 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const *
>(str) });
1729 #if defined(CATCH_CONFIG_CPP17_BYTE) 1732 static std::string convert(std::byte value);
1734 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 1737 static std::string convert(
int value);
1741 static std::string convert(
long value);
1745 static std::string convert(
long long value);
1749 static std::string convert(
unsigned int value);
1753 static std::string convert(
unsigned long value);
1757 static std::string convert(
unsigned long long value);
1762 static std::string convert(
bool b);
1767 static std::string convert(
char c);
1771 static std::string convert(
signed char c);
1775 static std::string convert(
unsigned char c);
1780 static std::string convert(std::nullptr_t);
1785 static std::string convert(
float value);
1786 static int precision;
1791 static std::string convert(
double value);
1792 static int precision;
1795 template <
typename T>
1797 template <
typename U>
1798 static std::string convert(U* p) {
1800 return ::Catch::Detail::rawMemoryToString(p);
1807 template <
typename R,
typename C>
1809 static std::string convert(R C::* p) {
1811 return ::Catch::Detail::rawMemoryToString(p);
1818 #if defined(_MANAGED) 1819 template <
typename T>
1821 static std::string convert( T^ ref ) {
1822 return ::Catch::Detail::clrReferenceToString(ref);
1828 template<
typename InputIterator,
typename Sentinel = InputIterator>
1829 std::string rangeToString(InputIterator first, Sentinel last) {
1832 if (first != last) {
1833 rss << ::Catch::Detail::stringify(*first);
1834 for (++first; first != last; ++first)
1835 rss <<
", " << ::Catch::Detail::stringify(*first);
1845 static std::string convert(NSString * nsstring) {
1848 return std::string(
"@") + [nsstring UTF8String];
1853 static std::string convert(NSObject* nsObject) {
1854 return ::Catch::Detail::stringify([nsObject description]);
1859 inline std::string stringify( NSString* nsstring ) {
1872 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) 1873 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1874 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1875 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1876 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 1877 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1881 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) 1884 template<
typename T1,
typename T2>
1886 static std::string convert(
const std::pair<T1, T2>& pair) {
1889 << ::Catch::Detail::stringify(pair.first)
1891 << ::Catch::Detail::stringify(pair.second)
1897 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER 1899 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) 1902 template<
typename T>
1904 static std::string convert(
const std::optional<T>& optional) {
1906 if (optional.has_value()) {
1907 rss << ::Catch::Detail::stringify(*optional);
1915 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER 1918 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) 1925 bool = (N < std::tuple_size<Tuple>::value)
1927 struct TupleElementPrinter {
1928 static void print(
const Tuple& tuple, std::ostream& os) {
1929 os << (N ?
", " :
" ")
1930 << ::Catch::Detail::stringify(std::get<N>(tuple));
1931 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1939 struct TupleElementPrinter<Tuple, N, false> {
1940 static void print(
const Tuple&, std::ostream&) {}
1945 template<
typename ...Types>
1947 static std::string convert(
const std::tuple<Types...>& tuple) {
1950 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1956 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER 1958 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) 1963 static std::string convert(
const std::monostate&) {
1968 template<
typename... Elements>
1970 static std::string convert(
const std::variant<Elements...>& variant) {
1971 if (variant.valueless_by_exception()) {
1972 return "{valueless variant}";
1975 [](
const auto& value) {
1976 return ::Catch::Detail::stringify(value);
1984 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER 1992 template <
typename...>
1997 template <
typename T,
typename =
void>
2001 template <
typename T>
2006 template <
typename T>
2010 #if defined(_MANAGED) // Managed types are never ranges 2011 template <
typename T>
2013 static const bool value =
false;
2017 template<
typename Range>
2018 std::string rangeToString( Range
const& range ) {
2019 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2023 template<
typename Allocator>
2024 std::string rangeToString( std::vector<bool, Allocator>
const& v ) {
2033 rss << ::Catch::Detail::stringify( b );
2039 template<
typename R>
2041 static std::string convert( R
const& range ) {
2042 return rangeToString( range );
2046 template <
typename T,
int SZ>
2048 static std::string convert(T
const(&arr)[SZ]) {
2049 return rangeToString(arr);
2056 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 2063 template <
class Ratio>
2064 struct ratio_string {
2065 static std::string symbol();
2068 template <
class Ratio>
2069 std::string ratio_string<Ratio>::symbol() {
2071 rss <<
'[' << Ratio::num <<
'/' 2072 << Ratio::den <<
']';
2076 struct ratio_string<std::atto> {
2077 static std::string symbol();
2080 struct ratio_string<std::femto> {
2081 static std::string symbol();
2084 struct ratio_string<std::pico> {
2085 static std::string symbol();
2088 struct ratio_string<std::nano> {
2089 static std::string symbol();
2092 struct ratio_string<std::micro> {
2093 static std::string symbol();
2096 struct ratio_string<std::milli> {
2097 static std::string symbol();
2102 template<
typename Value,
typename Ratio>
2103 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2104 static std::string convert(std::chrono::duration<Value, Ratio>
const& duration) {
2106 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2110 template<
typename Value>
2111 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2112 static std::string convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2114 rss << duration.count() <<
" s";
2118 template<
typename Value>
2119 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2120 static std::string convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2122 rss << duration.count() <<
" m";
2126 template<
typename Value>
2127 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2128 static std::string convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2130 rss << duration.count() <<
" h";
2138 template<
typename Clock,
typename Duration>
2139 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2140 static std::string convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2141 return ::Catch::Detail::stringify(time_point.time_since_epoch()) +
" since epoch";
2145 template<
typename Duration>
2146 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2147 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2148 auto converted = std::chrono::system_clock::to_time_t(time_point);
2151 std::tm timeInfo = {};
2152 gmtime_s(&timeInfo, &converted);
2154 std::tm* timeInfo = std::gmtime(&converted);
2157 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2158 char timeStamp[timeStampSize];
2159 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2162 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2164 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2166 return std::string(timeStamp);
2170 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 2172 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \ 2174 template<> struct StringMaker<enumName> { \ 2175 static std::string convert( enumName value ) { \ 2176 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \ 2177 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \ 2182 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ ) 2185 #pragma warning(pop) 2192 #pragma warning(push) 2193 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch 2194 #pragma warning(disable:4018) // more "signed/unsigned mismatch" 2195 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) 2196 #pragma warning(disable:4180) // qualifier applied to function type has no meaning 2197 #pragma warning(disable:4800) // Forcing result to true or false 2203 auto isBinaryExpression()
const ->
bool {
return m_isBinaryExpression; }
2204 auto getResult()
const ->
bool {
return m_result; }
2205 virtual void streamReconstructedExpression( std::ostream &os )
const = 0;
2208 : m_isBinaryExpression( isBinaryExpression ),
2216 bool m_isBinaryExpression;
2221 void formatReconstructedExpression( std::ostream &os, std::string
const& lhs,
StringRef op, std::string
const& rhs );
2223 template<
typename LhsT,
typename RhsT>
2229 void streamReconstructedExpression( std::ostream &os )
const override {
2230 formatReconstructedExpression
2231 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2242 template<
typename T>
2245 "chained comparisons are not supported inside assertions, " 2246 "wrap the expression inside parentheses, or decompose it");
2249 template<
typename T>
2252 "chained comparisons are not supported inside assertions, " 2253 "wrap the expression inside parentheses, or decompose it");
2256 template<
typename T>
2259 "chained comparisons are not supported inside assertions, " 2260 "wrap the expression inside parentheses, or decompose it");
2263 template<
typename T>
2266 "chained comparisons are not supported inside assertions, " 2267 "wrap the expression inside parentheses, or decompose it");
2270 template<
typename T>
2273 "chained comparisons are not supported inside assertions, " 2274 "wrap the expression inside parentheses, or decompose it");
2277 template<
typename T>
2280 "chained comparisons are not supported inside assertions, " 2281 "wrap the expression inside parentheses, or decompose it");
2284 template<
typename T>
2287 "chained comparisons are not supported inside assertions, " 2288 "wrap the expression inside parentheses, or decompose it");
2291 template<
typename T>
2294 "chained comparisons are not supported inside assertions, " 2295 "wrap the expression inside parentheses, or decompose it");
2299 template<
typename LhsT>
2303 void streamReconstructedExpression( std::ostream &os )
const override {
2304 os << Catch::Detail::stringify( m_lhs );
2315 template<
typename LhsT,
typename RhsT>
2316 auto compareEqual( LhsT
const& lhs, RhsT
const& rhs ) ->
bool {
return static_cast<bool>(lhs == rhs); }
2317 template<
typename T>
2318 auto compareEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2319 template<
typename T>
2320 auto compareEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2321 template<
typename T>
2322 auto compareEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2323 template<
typename T>
2324 auto compareEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2326 template<
typename LhsT,
typename RhsT>
2327 auto compareNotEqual( LhsT
const& lhs, RhsT&& rhs ) ->
bool {
return static_cast<bool>(lhs != rhs); }
2328 template<
typename T>
2329 auto compareNotEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2330 template<
typename T>
2331 auto compareNotEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2332 template<
typename T>
2333 auto compareNotEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2334 template<
typename T>
2335 auto compareNotEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2337 template<
typename LhsT>
2341 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2343 template<
typename RhsT>
2345 return { compareEqual( m_lhs, rhs ), m_lhs,
"==", rhs };
2348 return { m_lhs == rhs, m_lhs,
"==", rhs };
2351 template<
typename RhsT>
2353 return { compareNotEqual( m_lhs, rhs ), m_lhs,
"!=", rhs };
2356 return { m_lhs != rhs, m_lhs,
"!=", rhs };
2359 template<
typename RhsT>
2361 return {
static_cast<bool>(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 };
2388 template<
typename RhsT>
2391 "operator&& is not supported inside assertions, " 2392 "wrap the expression inside parentheses, or decompose it");
2395 template<
typename RhsT>
2398 "operator|| is not supported inside assertions, " 2399 "wrap the expression inside parentheses, or decompose it");
2409 template<
typename T>
2410 void handleExpression(
ExprLhs<T> const& expr ) {
2411 handleExpression( expr.makeUnaryExpr() );
2415 template<
typename T>
2428 #pragma warning(pop) 2439 class AssertionResult;
2452 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2453 struct BenchmarkInfo;
2454 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2455 struct BenchmarkStats;
2456 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2462 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
2463 Counts& assertions ) = 0;
2465 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo ) = 0;
2469 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 2470 virtual void benchmarkPreparing( std::string
const& name ) = 0;
2471 virtual void benchmarkStarting( BenchmarkInfo
const& info ) = 0;
2472 virtual void benchmarkEnded( BenchmarkStats<>
const& stats ) = 0;
2473 virtual void benchmarkFailed( std::string
const& error ) = 0;
2474 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 2476 virtual void pushScopedMessage(
MessageInfo const& message ) = 0;
2477 virtual void popScopedMessage(
MessageInfo const& message ) = 0;
2479 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder ) = 0;
2481 virtual void handleFatalErrorCondition(
StringRef message ) = 0;
2483 virtual void handleExpr
2487 virtual void handleMessage
2489 ResultWas::OfType resultType,
2492 virtual void handleUnexpectedExceptionNotThrown
2495 virtual void handleUnexpectedInflightException
2497 std::string
const& message,
2499 virtual void handleIncomplete
2501 virtual void handleNonExpr
2503 ResultWas::OfType resultType,
2506 virtual bool lastAssertionPassed() = 0;
2507 virtual void assertionPassed() = 0;
2510 virtual std::string getCurrentTestName()
const = 0;
2511 virtual const AssertionResult* getLastResult()
const = 0;
2512 virtual void exceptionEarlyReported() = 0;
2522 struct AssertionResultData;
2528 friend struct AssertionStats;
2529 friend class RunContext;
2538 explicit operator bool()
const;
2540 friend auto operator << ( std::ostream& os,
LazyExpression const& lazyExpr ) -> std::ostream&;
2544 bool shouldDebugBreak =
false;
2545 bool shouldThrow =
false;
2551 bool m_completed =
false;
2559 ResultDisposition::Flags resultDisposition );
2561 if ( !m_completed ) {
2562 m_resultCapture.handleIncomplete( m_assertionInfo );
2566 template<
typename T>
2568 handleExpr( expr.makeUnaryExpr() );
2572 void handleMessage(ResultWas::OfType resultType,
StringRef const& message);
2574 void handleExceptionThrownAsExpected();
2575 void handleUnexpectedExceptionNotThrown();
2576 void handleExceptionNotThrownAsExpected();
2577 void handleThrowingCallSkipped();
2578 void handleUnexpectedInflightException();
2581 void setCompleted();
2584 auto allowThrows()
const -> bool;
2602 ResultWas::OfType _type );
2605 std::string message;
2607 ResultWas::OfType type;
2608 unsigned int sequence;
2610 bool operator == (
MessageInfo const& other )
const;
2611 bool operator < (
MessageInfo const& other )
const;
2613 static unsigned int globalCount;
2618 template<
typename T>
2630 ResultWas::OfType type );
2632 template<
typename T>
2653 std::vector<MessageInfo> m_messages;
2655 size_t m_captured = 0;
2660 void captureValue(
size_t index, std::string
const& value );
2662 template<
typename T>
2663 void captureValues(
size_t index, T
const& value ) {
2664 captureValue( index, Catch::Detail::stringify( value ) );
2667 template<
typename T,
typename... Ts>
2668 void captureValues(
size_t index, T
const& value, Ts
const&... values ) {
2669 captureValue( index, Catch::Detail::stringify(value) );
2670 captureValues( index+1, values... );
2677 #if !defined(CATCH_CONFIG_DISABLE) 2679 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) 2680 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ 2682 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" 2685 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 2690 #define INTERNAL_CATCH_TRY 2691 #define INTERNAL_CATCH_CATCH( capturer ) 2693 #else // CATCH_CONFIG_FAST_COMPILE 2695 #define INTERNAL_CATCH_TRY try 2696 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } 2700 #define INTERNAL_CATCH_REACT( handler ) handler.complete(); 2703 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ 2705 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \ 2706 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2707 INTERNAL_CATCH_TRY { \ 2708 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2709 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ 2710 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ 2711 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 2712 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 2713 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2714 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) 2717 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ 2718 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2719 if( Catch::getResultCapture().lastAssertionPassed() ) 2722 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ 2723 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ 2724 if( !Catch::getResultCapture().lastAssertionPassed() ) 2727 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ 2729 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ 2731 static_cast<void>(__VA_ARGS__); \ 2732 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ 2735 catchAssertionHandler.handleUnexpectedInflightException(); \ 2737 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2741 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ 2743 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ 2744 if( catchAssertionHandler.allowThrows() ) \ 2746 static_cast<void>(__VA_ARGS__); \ 2747 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2750 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2753 catchAssertionHandler.handleThrowingCallSkipped(); \ 2754 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2758 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ 2760 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ 2761 if( catchAssertionHandler.allowThrows() ) \ 2763 static_cast<void>(expr); \ 2764 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2766 catch( exceptionType const& ) { \ 2767 catchAssertionHandler.handleExceptionThrownAsExpected(); \ 2770 catchAssertionHandler.handleUnexpectedInflightException(); \ 2773 catchAssertionHandler.handleThrowingCallSkipped(); \ 2774 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2778 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ 2780 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ 2781 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ 2782 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2786 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ 2787 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ 2788 varName.captureValues( 0, __VA_ARGS__ ) 2791 #define INTERNAL_CATCH_INFO( macroName, log ) \ 2792 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); 2795 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ 2796 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) 2800 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ 2802 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 2803 if( catchAssertionHandler.allowThrows() ) \ 2805 static_cast<void>(__VA_ARGS__); \ 2806 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 2809 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ 2812 catchAssertionHandler.handleThrowingCallSkipped(); \ 2813 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 2816 #endif // CATCH_CONFIG_DISABLE 2833 std::size_t total()
const;
2834 bool allPassed()
const;
2837 std::size_t passed = 0;
2838 std::size_t failed = 0;
2839 std::size_t failedButOk = 0;
2863 std::string
const& _name );
2868 std::string
const& _name,
2869 std::string
const& ) :
SectionInfo( _lineInfo, _name ) {}
2872 std::string description;
2879 double durationInSeconds;
2891 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2892 auto getEstimatedClockResolution() -> uint64_t;
2895 uint64_t m_nanoseconds = 0;
2898 auto getElapsedNanoseconds()
const -> uint64_t;
2899 auto getElapsedMicroseconds()
const -> uint64_t;
2900 auto getElapsedMilliseconds()
const ->
unsigned int;
2901 auto getElapsedSeconds()
const -> double;
2917 explicit operator bool()
const;
2924 bool m_sectionIncluded;
2930 #define INTERNAL_CATCH_SECTION( ... ) \ 2931 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2932 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2933 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ 2934 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2936 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ 2937 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 2938 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ 2939 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ 2940 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 2956 struct IReporterRegistry;
2957 struct IReporterFactory;
2958 struct ITagAliasRegistry;
2961 class StartupExceptionRegistry;
2963 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2968 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2970 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2973 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
2978 virtual void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory ) = 0;
2979 virtual void registerListener( IReporterFactoryPtr
const& factory ) = 0;
2980 virtual void registerTest(
TestCase const& testInfo ) = 0;
2982 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) = 0;
2983 virtual void registerStartupException() noexcept = 0;
2990 std::string translateActiveException();
2995 #if defined(CATCH_CONFIG_DISABLE) 2996 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ 2997 static std::string translatorName( signature ) 3000 #include <exception> 3005 using exceptionTranslateFunction = std::string(*)();
3008 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3012 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3018 virtual std::string translateActiveException()
const = 0;
3022 template<
typename T>
3026 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3027 : m_translateFunction( translateFunction )
3030 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const override {
3031 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3036 std::rethrow_exception(std::current_exception());
3038 return (*it)->translate( it+1, itEnd );
3041 return m_translateFunction( ex );
3047 std::string(*m_translateFunction)( T& );
3051 template<
typename T>
3053 getMutableRegistryHub().registerTranslator
3054 (
new ExceptionTranslator<T>( translateFunction ) );
3060 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ 3061 static std::string translatorName( signature ); \ 3062 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 3063 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 3064 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ 3065 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \ 3066 static std::string translatorName( signature ) 3068 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 3073 #include <type_traits> 3080 bool equalityComparisonImpl(
double other)
const;
3083 void setMargin(
double margin);
3086 void setEpsilon(
double epsilon);
3089 explicit Approx (
double value );
3093 Approx operator-()
const;
3095 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3096 Approx operator()( T
const& value )
const {
3097 Approx approx( static_cast<double>(value) );
3098 approx.m_epsilon = m_epsilon;
3099 approx.m_margin = m_margin;
3100 approx.m_scale = m_scale;
3104 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3105 explicit Approx( T
const& value ): Approx(static_cast<double>(value))
3108 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3109 friend bool operator == (
const T& lhs, Approx
const& rhs ) {
3110 auto lhs_v =
static_cast<double>(lhs);
3111 return rhs.equalityComparisonImpl(lhs_v);
3114 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3115 friend bool operator == ( Approx
const& lhs,
const T& rhs ) {
3116 return operator==( rhs, lhs );
3119 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3120 friend bool operator != ( T
const& lhs, Approx
const& rhs ) {
3121 return !operator==( lhs, rhs );
3124 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3125 friend bool operator != ( Approx
const& lhs, T
const& rhs ) {
3126 return !operator==( rhs, lhs );
3129 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3130 friend bool operator <= ( T
const& lhs, Approx
const& rhs ) {
3131 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3134 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3135 friend bool operator <= ( Approx
const& lhs, T
const& rhs ) {
3136 return lhs.m_value <
static_cast<double>(rhs) || lhs == rhs;
3139 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3140 friend bool operator >= ( T
const& lhs, Approx
const& rhs ) {
3141 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3144 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3145 friend bool operator >= ( Approx
const& lhs, T
const& rhs ) {
3146 return lhs.m_value >
static_cast<double>(rhs) || lhs == rhs;
3149 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3150 Approx& epsilon( T
const& newEpsilon ) {
3151 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3152 setEpsilon(epsilonAsDouble);
3156 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3157 Approx& margin( T
const& newMargin ) {
3158 double marginAsDouble =
static_cast<double>(newMargin);
3159 setMargin(marginAsDouble);
3163 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3164 Approx& scale( T
const& newScale ) {
3165 m_scale =
static_cast<double>(newScale);
3169 std::string toString()
const;
3179 namespace literals {
3200 bool startsWith( std::string
const& s, std::string
const& prefix );
3201 bool startsWith( std::string
const& s,
char prefix );
3202 bool endsWith( std::string
const& s, std::string
const& suffix );
3203 bool endsWith( std::string
const& s,
char suffix );
3204 bool contains( std::string
const& s, std::string
const& infix );
3205 void toLowerInPlace( std::string& s );
3206 std::string toLower( std::string
const& s );
3208 std::string trim( std::string
const& str );
3213 std::vector<StringRef> splitStringRef(
StringRef str,
char delimiter );
3214 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
3217 pluralise( std::size_t count, std::string
const& label );
3219 friend std::ostream& operator << ( std::ostream& os,
pluralise const& pluraliser );
3221 std::size_t m_count;
3222 std::string m_label;
3227 #ifndef CATCH_CONFIG_DISABLE_MATCHERS 3236 namespace Matchers {
3248 std::string toString()
const;
3252 virtual std::string describe()
const = 0;
3253 mutable std::string m_cachedToString;
3257 # pragma clang diagnostic push 3258 # pragma clang diagnostic ignored "-Wnon-virtual-dtor" 3261 template<
typename ObjectT>
3263 virtual bool match( ObjectT
const& arg )
const = 0;
3266 #if defined(__OBJC__) 3271 virtual bool match( NSString* arg )
const = 0;
3276 # pragma clang diagnostic pop 3279 template<
typename T>
3287 template<
typename ArgT>
3289 bool match( ArgT
const& arg )
const override {
3290 for(
auto matcher : m_matchers ) {
3291 if (!matcher->match(arg))
3296 std::string describe()
const override {
3297 std::string description;
3298 description.reserve( 4 + m_matchers.size()*32 );
3299 description +=
"( ";
3301 for(
auto matcher : m_matchers ) {
3305 description +=
" and ";
3306 description += matcher->toString();
3308 description +=
" )";
3314 copy.m_matchers.push_back( &other );
3318 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3320 template<
typename ArgT>
3323 bool match( ArgT
const& arg )
const override {
3324 for(
auto matcher : m_matchers ) {
3325 if (matcher->match(arg))
3330 std::string describe()
const override {
3331 std::string description;
3332 description.reserve( 4 + m_matchers.size()*32 );
3333 description +=
"( ";
3335 for(
auto matcher : m_matchers ) {
3339 description +=
" or ";
3340 description += matcher->toString();
3342 description +=
" )";
3348 copy.m_matchers.push_back( &other );
3352 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3355 template<
typename ArgT>
3360 bool match( ArgT
const& arg )
const override {
3361 return !m_underlyingMatcher.match( arg );
3364 std::string describe()
const override {
3365 return "not " + m_underlyingMatcher.toString();
3370 template<
typename T>
3374 template<
typename T>
3378 template<
typename T>
3387 using namespace Matchers;
3396 namespace Matchers {
3397 namespace Exception {
3400 std::string m_message;
3407 bool match(std::exception
const& ex)
const override;
3409 std::string describe()
const override;
3423 namespace Matchers {
3425 namespace Floating {
3427 enum class FloatingPointKind : uint8_t;
3431 bool match(
double const& matchee)
const override;
3432 std::string describe()
const override;
3440 bool match(
double const& matchee)
const override;
3441 std::string describe()
const override;
3445 FloatingPointKind m_type;
3456 bool match(
double const& matchee)
const override;
3457 std::string describe()
const override;
3483 #include <functional> 3487 namespace Matchers {
3491 std::string finalizeDescription(
const std::string& desc);
3494 template <
typename T>
3496 std::function<bool(T const&)> m_predicate;
3497 std::string m_description;
3500 PredicateMatcher(std::function<
bool(T
const&)>
const& elem, std::string
const& descr)
3501 :m_predicate(std::move(elem)),
3502 m_description(Detail::finalizeDescription(descr))
3505 bool match( T
const& item )
const override {
3506 return m_predicate(item);
3509 std::string describe()
const override {
3510 return m_description;
3520 template<
typename T>
3534 namespace Matchers {
3536 namespace StdString {
3540 CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity );
3541 std::string adjustString( std::string
const& str )
const;
3542 std::string caseSensitivitySuffix()
const;
3544 CaseSensitive::Choice m_caseSensitivity;
3550 std::string describe()
const override;
3553 std::string m_operation;
3558 bool match( std::string
const& source )
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 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3575 bool match( std::string
const& matchee )
const override;
3576 std::string describe()
const override;
3579 std::string m_regex;
3580 CaseSensitive::Choice m_caseSensitivity;
3588 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3592 StdString::RegexMatcher Matches( std::string
const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3600 #include <algorithm> 3603 namespace Matchers {
3606 template<
typename T,
typename Alloc>
3611 bool match(std::vector<T, Alloc>
const &v)
const override {
3612 for (
auto const& el : v) {
3613 if (el == m_comparator) {
3620 std::string describe()
const override {
3621 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3624 T
const& m_comparator;
3627 template<
typename T,
typename AllocComp,
typename AllocMatch>
3630 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3632 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3634 if (m_comparator.size() > v.size())
3636 for (
auto const& comparator : m_comparator) {
3637 auto present =
false;
3638 for (
const auto& el : v) {
3639 if (el == comparator) {
3650 std::string describe()
const override {
3651 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3654 std::vector<T, AllocComp>
const& m_comparator;
3657 template<
typename T,
typename AllocComp,
typename AllocMatch>
3660 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3662 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3667 if (m_comparator.size() != v.size())
3669 for (std::size_t i = 0; i < v.size(); ++i)
3670 if (m_comparator[i] != v[i])
3674 std::string describe()
const override {
3675 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3677 std::vector<T, AllocComp>
const& m_comparator;
3680 template<
typename T,
typename AllocComp,
typename AllocMatch>
3683 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3685 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3686 if (m_comparator.size() != v.size())
3688 for (std::size_t i = 0; i < v.size(); ++i)
3689 if (m_comparator[i] != approx(v[i]))
3693 std::string describe()
const override {
3694 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3696 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3698 approx.epsilon(newEpsilon);
3701 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3703 approx.margin(newMargin);
3706 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3708 approx.scale(newScale);
3712 std::vector<T, AllocComp>
const& m_comparator;
3716 template<
typename T,
typename AllocComp,
typename AllocMatch>
3719 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3720 if (m_target.size() != vec.size()) {
3723 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3726 std::string describe()
const override {
3727 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3730 std::vector<T, AllocComp>
const& m_target;
3738 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3743 template<
typename T,
typename Alloc = std::allocator<T>>
3748 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3753 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3758 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3769 template<
typename ArgT,
typename MatcherT>
3775 MatchExpr( ArgT
const& arg, MatcherT
const& matcher,
StringRef const& matcherString )
3778 m_matcher( matcher ),
3779 m_matcherString( matcherString )
3782 void streamReconstructedExpression( std::ostream &os )
const override {
3783 auto matcherAsString = m_matcher.toString();
3784 os << Catch::Detail::stringify( m_arg ) <<
' ';
3785 if( matcherAsString == Detail::unprintableString )
3786 os << m_matcherString;
3788 os << matcherAsString;
3796 template<
typename ArgT,
typename MatcherT>
3804 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ 3806 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3807 INTERNAL_CATCH_TRY { \ 3808 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ 3809 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ 3810 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3814 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ 3816 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ 3817 if( catchAssertionHandler.allowThrows() ) \ 3819 static_cast<void>(__VA_ARGS__ ); \ 3820 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ 3822 catch( exceptionType const& ex ) { \ 3823 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ 3826 catchAssertionHandler.handleUnexpectedInflightException(); \ 3829 catchAssertionHandler.handleThrowingCallSkipped(); \ 3830 INTERNAL_CATCH_REACT( catchAssertionHandler ) \ 3844 namespace Generators {
3853 virtual bool next() = 0;
3855 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3861 virtual auto hasGenerator()
const ->
bool = 0;
3862 virtual auto getGenerator()
const -> Generators::GeneratorBasePtr
const& = 0;
3863 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3871 #include <exception> 3874 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 3875 template <
typename Ex>
3877 void throw_exception(Ex
const& e) {
3880 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 3882 void throw_exception(std::exception
const& e);
3886 void throw_logic_error(std::string
const& msg);
3888 void throw_domain_error(std::string
const& msg);
3890 void throw_runtime_error(std::string
const& msg);
3894 #define CATCH_MAKE_MSG(...) \ 3895 (Catch::ReusableStringStream() << __VA_ARGS__).str() 3897 #define CATCH_INTERNAL_ERROR(...) \ 3898 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__)) 3900 #define CATCH_ERROR(...) \ 3901 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3903 #define CATCH_RUNTIME_ERROR(...) \ 3904 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ )) 3906 #define CATCH_ENFORCE( condition, ... ) \ 3907 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false) 3915 #include <exception> 3920 const char*
const m_msg =
"";
3927 const char* what()
const noexcept
override final;
3930 namespace Generators {
3934 template<
typename T,
typename... Args>
3935 std::unique_ptr<T> make_unique( Args&&... args ) {
3936 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
3940 template<
typename T>
3948 virtual T
const&
get()
const = 0;
3952 template<
typename T>
3958 T
const&
get()
const override {
3961 bool next()
override {
3966 template<
typename T>
3968 static_assert(!std::is_same<T, bool>::value,
3969 "FixedValuesGenerator does not support bools because of std::vector<bool>" 3970 "specialization, use SingleValue Generator instead.");
3971 std::vector<T> m_values;
3976 T
const&
get()
const override {
3977 return m_values[m_idx];
3979 bool next()
override {
3981 return m_idx < m_values.size();
3985 template <
typename T>
3987 std::unique_ptr<IGenerator<T>> m_generator;
3990 m_generator(std::move(generator))
3992 T
const&
get()
const {
3993 return m_generator->get();
3996 return m_generator->next();
4000 template <
typename T>
4002 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4004 template <
typename T>
4009 template<
typename T>
4011 std::vector<GeneratorWrapper<T>> m_generators;
4012 size_t m_current = 0;
4015 m_generators.emplace_back(std::move(generator));
4017 void populate(T&& val) {
4018 m_generators.emplace_back(value(std::forward<T>(val)));
4020 template<
typename U>
4021 void populate(U&& val) {
4022 populate(T(std::forward<U>(val)));
4024 template<
typename U,
typename... Gs>
4025 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4026 populate(std::forward<U>(valueOrGenerator));
4027 populate(std::forward<Gs>(moreGenerators)...);
4031 template <
typename... Gs>
4033 m_generators.reserve(
sizeof...(Gs));
4034 populate(std::forward<Gs>(moreGenerators)...);
4037 T
const&
get()
const override {
4038 return m_generators[m_current].get();
4041 bool next()
override {
4042 if (m_current >= m_generators.size()) {
4045 const bool current_status = m_generators[m_current].next();
4046 if (!current_status) {
4049 return m_current < m_generators.size();
4053 template<
typename... Ts>
4054 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples ) {
4055 return values<std::tuple<Ts...>>( tuples );
4059 template <
typename T>
4062 template<
typename T,
typename... Gs>
4064 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4066 template<
typename T>
4070 template<
typename T,
typename... Gs>
4071 auto makeGenerators( T&& val, Gs &&... moreGenerators ) ->
Generators<T> {
4072 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4074 template<
typename T,
typename U,
typename... Gs>
4076 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4081 template<
typename L>
4085 auto generate(
StringRef generatorName,
SourceLineInfo const& lineInfo, L
const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().
get()) {
4086 using UnderlyingType =
typename decltype(generatorExpression())::type;
4088 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4089 if (!tracker.hasGenerator()) {
4094 return generator.get();
4100 #define GENERATE( ... ) \ 4101 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \ 4102 CATCH_INTERNAL_LINEINFO, \ 4103 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace) 4104 #define GENERATE_COPY( ... ) \ 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_REF( ... ) \ 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) 4119 template <
typename T>
4122 size_t m_returned = 0;
4126 m_generator(std::move(generator)),
4129 assert(target != 0 &&
"Empty generators are not allowed");
4131 T
const&
get()
const override {
4132 return m_generator.get();
4134 bool next()
override {
4136 if (m_returned >= m_target) {
4140 const auto success = m_generator.next();
4144 m_returned = m_target;
4150 template <
typename T>
4152 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4155 template <
typename T,
typename Predicate>
4158 Predicate m_predicate;
4160 template <
typename P = Predicate>
4162 m_generator(std::move(generator)),
4163 m_predicate(std::forward<P>(pred))
4165 if (!m_predicate(m_generator.get())) {
4168 auto has_initial_value = nextImpl();
4169 if (!has_initial_value) {
4170 Catch::throw_exception(
GeneratorException(
"No valid value found in filtered generator"));
4175 T
const&
get()
const override {
4176 return m_generator.get();
4179 bool next()
override {
4185 bool success = m_generator.next();
4189 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) ==
true);
4194 template <
typename T,
typename Predicate>
4196 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4199 template <
typename T>
4201 static_assert(!std::is_same<T, bool>::value,
4202 "RepeatGenerator currently does not support bools" 4203 "because of std::vector<bool> specialization");
4205 mutable std::vector<T> m_returned;
4206 size_t m_target_repeats;
4207 size_t m_current_repeat = 0;
4208 size_t m_repeat_index = 0;
4211 m_generator(std::move(generator)),
4212 m_target_repeats(repeats)
4214 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4217 T
const&
get()
const override {
4218 if (m_current_repeat == 0) {
4219 m_returned.push_back(m_generator.get());
4220 return m_returned.back();
4222 return m_returned[m_repeat_index];
4225 bool next()
override {
4232 if (m_current_repeat == 0) {
4233 const auto success = m_generator.next();
4237 return m_current_repeat < m_target_repeats;
4242 if (m_repeat_index == m_returned.size()) {
4246 return m_current_repeat < m_target_repeats;
4250 template <
typename T>
4252 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4255 template <
typename T,
typename U,
typename Func>
4263 template <
typename F2 = Func>
4265 m_generator(std::move(generator)),
4266 m_function(std::forward<F2>(
function)),
4267 m_cache(m_function(m_generator.get()))
4270 T
const&
get()
const override {
4273 bool next()
override {
4274 const auto success = m_generator.next();
4276 m_cache = m_function(m_generator.get());
4282 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4285 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4289 template <
typename T,
typename U,
typename Func>
4292 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4296 template <
typename T>
4298 std::vector<T> m_chunk;
4299 size_t m_chunk_size;
4301 bool m_used_up =
false;
4304 m_chunk_size(size), m_generator(std::move(generator))
4306 m_chunk.reserve(m_chunk_size);
4307 if (m_chunk_size != 0) {
4308 m_chunk.push_back(m_generator.get());
4309 for (
size_t i = 1; i < m_chunk_size; ++i) {
4310 if (!m_generator.next()) {
4311 Catch::throw_exception(
GeneratorException(
"Not enough values to initialize the first chunk"));
4313 m_chunk.push_back(m_generator.get());
4317 std::vector<T>
const&
get()
const override {
4320 bool next()
override {
4322 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4323 if (!m_generator.next()) {
4326 m_chunk.push_back(m_generator.get());
4332 template <
typename T>
4335 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4356 using IConfigPtr = std::shared_ptr<IConfig const>;
4363 virtual IRunner* getRunner() = 0;
4364 virtual IConfigPtr
const& getConfig()
const = 0;
4370 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4371 virtual void setRunner(
IRunner* runner ) = 0;
4372 virtual void setConfig( IConfigPtr
const& config ) = 0;
4377 friend void cleanUpContext();
4378 static void createContext();
4383 if( !IMutableContext::currentContext )
4384 IMutableContext::createContext();
4386 return *IMutableContext::currentContext;
4389 inline IContext& getCurrentContext()
4391 return getCurrentMutableContext();
4394 void cleanUpContext();
4408 template<
typename T>
4411 Option() : nullableValue(
nullptr ) {}
4412 Option( T
const& _value )
4413 : nullableValue(
new( storage ) T( _value ) )
4416 : nullableValue( _other ?
new( storage ) T( *_other ) :
nullptr )
4424 if( &_other !=
this ) {
4427 nullableValue =
new( storage ) T( *_other );
4431 Option& operator = ( T
const& _value ) {
4433 nullableValue =
new( storage ) T( _value );
4439 nullableValue->~T();
4440 nullableValue =
nullptr;
4443 T& operator*() {
return *nullableValue; }
4444 T
const& operator*()
const {
return *nullableValue; }
4445 T* operator->() {
return nullableValue; }
4446 const T* operator->()
const {
return nullableValue; }
4448 T valueOr( T
const& defaultValue )
const {
4449 return nullableValue ? *nullableValue : defaultValue;
4452 bool some()
const {
return nullableValue !=
nullptr; }
4453 bool none()
const {
return nullableValue ==
nullptr; }
4455 bool operator !()
const {
return nullableValue ==
nullptr; }
4456 explicit operator bool()
const {
4462 alignas(
alignof(T))
char storage[
sizeof(T)];
4476 enum class Verbosity {
4484 NoAssertions = 0x01,
4495 InLexicographicalOrder,
4507 BeforeStartAndExit = BeforeStart | BeforeExit
4516 virtual bool allowThrows()
const = 0;
4517 virtual std::ostream& stream()
const = 0;
4518 virtual std::string name()
const = 0;
4519 virtual bool includeSuccessfulResults()
const = 0;
4520 virtual bool shouldDebugBreak()
const = 0;
4521 virtual bool warnAboutMissingAssertions()
const = 0;
4522 virtual bool warnAboutNoTests()
const = 0;
4523 virtual int abortAfter()
const = 0;
4524 virtual bool showInvisibles()
const = 0;
4525 virtual ShowDurations::OrNot showDurations()
const = 0;
4526 virtual double minDuration()
const = 0;
4527 virtual TestSpec
const& testSpec()
const = 0;
4528 virtual bool hasTestFilters()
const = 0;
4529 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4530 virtual RunTests::InWhatOrder runOrder()
const = 0;
4531 virtual unsigned int rngSeed()
const = 0;
4532 virtual UseColour::YesOrNo useColour()
const = 0;
4533 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4534 virtual Verbosity verbosity()
const = 0;
4536 virtual bool benchmarkNoAnalysis()
const = 0;
4537 virtual int benchmarkSamples()
const = 0;
4538 virtual double benchmarkConfidenceInterval()
const = 0;
4539 virtual unsigned int benchmarkResamples()
const = 0;
4540 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4543 using IConfigPtr = std::shared_ptr<IConfig const>;
4559 using state_type = std::uint64_t;
4561 using result_type = std::uint32_t;
4562 static constexpr result_type (min)() {
4565 static constexpr result_type (max)() {
4566 return static_cast<result_type
>(-1);
4574 void seed(result_type seed_);
4575 void discard(uint64_t skip);
4577 result_type operator()();
4586 std::uint64_t m_state;
4591 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4600 namespace Generators {
4602 template <
typename Float>
4605 std::uniform_real_distribution<Float> m_dist;
4606 Float m_current_number;
4612 static_cast<void>(next());
4615 Float
const&
get()
const override {
4616 return m_current_number;
4618 bool next()
override {
4619 m_current_number = m_dist(m_rng);
4624 template <
typename Integer>
4627 std::uniform_int_distribution<Integer> m_dist;
4628 Integer m_current_number;
4634 static_cast<void>(next());
4637 Integer
const&
get()
const override {
4638 return m_current_number;
4640 bool next()
override {
4641 m_current_number = m_dist(m_rng);
4648 template <
typename T>
4649 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4653 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4657 template <
typename T>
4658 typename std::enable_if<std::is_floating_point<T>::value,
4662 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4666 template <
typename T>
4678 m_positive(m_step > T(0))
4680 assert(m_current != m_end &&
"Range start and end cannot be equal");
4681 assert(m_step != T(0) &&
"Step size cannot be zero");
4682 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4689 T
const&
get()
const override {
4693 bool next()
override {
4694 m_current += m_step;
4695 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4699 template <
typename T>
4701 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
"Type must be numeric");
4705 template <
typename T>
4707 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
"Type must be an integer");
4711 template <
typename T>
4713 static_assert(!std::is_same<T, bool>::value,
4714 "IteratorGenerator currently does not support bools" 4715 "because of std::vector<bool> specialization");
4717 std::vector<T> m_elems;
4718 size_t m_current = 0;
4720 template <
typename InputIterator,
typename InputSentinel>
4721 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4722 if (m_elems.empty()) {
4723 Catch::throw_exception(
GeneratorException(
"IteratorGenerator received no valid values"));
4727 T
const&
get()
const override {
4728 return m_elems[m_current];
4731 bool next()
override {
4733 return m_current != m_elems.size();
4737 template <
typename InputIterator,
4738 typename InputSentinel,
4739 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4744 template <
typename Container,
4745 typename ResultType =
typename Container::value_type>
4764 #pragma clang diagnostic push 4765 #pragma clang diagnostic ignored "-Wpadded" 4773 enum SpecialProperties{
4776 ShouldFail = 1 << 2,
4779 NonPortable = 1 << 5,
4784 std::string
const& _className,
4785 std::string
const& _description,
4786 std::vector<std::string>
const& _tags,
4789 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4791 bool isHidden()
const;
4792 bool throws()
const;
4793 bool okToFail()
const;
4794 bool expectedToFail()
const;
4796 std::string tagsAsString()
const;
4799 std::string className;
4800 std::string description;
4801 std::vector<std::string> tags;
4802 std::vector<std::string> lcaseTags;
4804 SpecialProperties properties;
4812 TestCase withName( std::string
const& _newName )
const;
4814 void invoke()
const;
4818 bool operator == (
TestCase const& other )
const;
4819 bool operator < (
TestCase const& other )
const;
4822 std::shared_ptr<ITestInvoker>
test;
4826 std::string
const& className,
4832 #pragma clang diagnostic pop 4842 virtual bool aborting()
const = 0;
4851 #import <objc/runtime.h> 4876 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4878 virtual void invoke()
const {
4879 id obj = [[m_cls alloc] init];
4881 performOptionalSelector( obj,
@selector(setUp) );
4882 performOptionalSelector( obj, m_sel );
4883 performOptionalSelector( obj,
@selector(tearDown) );
4885 arcSafeRelease( obj );
4888 virtual ~OcMethod() {}
4896 inline std::string getAnnotation( Class cls,
4897 std::string
const& annotationName,
4898 std::string
const& testCaseName ) {
4899 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4900 SEL sel = NSSelectorFromString( selStr );
4901 arcSafeRelease( selStr );
4902 id value = performOptionalSelector( cls, sel );
4904 return [(NSString*)value UTF8String];
4909 inline std::size_t registerTestMethods() {
4910 std::size_t noTestMethods = 0;
4911 int noClasses = objc_getClassList(
nullptr, 0 );
4913 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4914 objc_getClassList( classes, noClasses );
4916 for(
int c = 0; c < noClasses; c++ ) {
4917 Class cls = classes[c];
4920 Method* methods = class_copyMethodList( cls, &count );
4921 for( u_int m = 0; m < count ; m++ ) {
4922 SEL selector = method_getName(methods[m]);
4923 std::string methodName = sel_getName(selector);
4924 if( startsWith( methodName,
"Catch_TestCase_" ) ) {
4925 std::string testCaseName = methodName.substr( 15 );
4926 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4927 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4928 const char* className = class_getName( cls );
4930 getMutableRegistryHub().registerTest( makeTestCase(
new OcMethod( cls, selector ), className,
NameAndTags( name.c_str(), desc.c_str() ),
SourceLineInfo(
"",0) ) );
4937 return noTestMethods;
4940 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 4942 namespace Matchers {
4944 namespace NSStringMatchers {
4947 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4948 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4950 arcSafeRelease( m_substr );
4953 bool match( NSString* str )
const override {
4957 NSString* CATCH_ARC_STRONG m_substr;
4960 struct Equals : StringHolder {
4961 Equals( NSString* substr ) : StringHolder( substr ){}
4963 bool match( NSString* str )
const override {
4964 return (str != nil || m_substr == nil ) &&
4965 [str isEqualToString:m_substr];
4968 std::string describe()
const override {
4969 return "equals string: " + Catch::Detail::stringify( m_substr );
4973 struct Contains : StringHolder {
4974 Contains( NSString* substr ) : StringHolder( substr ){}
4976 bool match( NSString* str )
const override {
4977 return (str != nil || m_substr == nil ) &&
4978 [str rangeOfString:m_substr].location != NSNotFound;
4981 std::string describe()
const override {
4982 return "contains string: " + Catch::Detail::stringify( m_substr );
4986 struct StartsWith : StringHolder {
4987 StartsWith( NSString* substr ) : StringHolder( substr ){}
4989 bool match( NSString* str )
const override {
4990 return (str != nil || m_substr == nil ) &&
4991 [str rangeOfString:m_substr].location == 0;
4994 std::string describe()
const override {
4995 return "starts with: " + Catch::Detail::stringify( m_substr );
4998 struct EndsWith : StringHolder {
4999 EndsWith( NSString* substr ) : StringHolder( substr ){}
5001 bool match( NSString* str )
const override {
5002 return (str != nil || m_substr == nil ) &&
5003 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5006 std::string describe()
const override {
5007 return "ends with: " + Catch::Detail::stringify( m_substr );
5014 inline Impl::NSStringMatchers::Equals
5015 Equals( NSString* substr ){
return Impl::NSStringMatchers::Equals( substr ); }
5017 inline Impl::NSStringMatchers::Contains
5018 Contains( NSString* substr ){
return Impl::NSStringMatchers::Contains( substr ); }
5020 inline Impl::NSStringMatchers::StartsWith
5021 StartsWith( NSString* substr ){
return Impl::NSStringMatchers::StartsWith( substr ); }
5023 inline Impl::NSStringMatchers::EndsWith
5024 EndsWith( NSString* substr ){
return Impl::NSStringMatchers::EndsWith( substr ); }
5028 using namespace Matchers;
5030 #endif // CATCH_CONFIG_DISABLE_MATCHERS 5035 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix 5036 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ 5037 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ 5041 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ 5045 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) 5047 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) 5053 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5065 #pragma clang diagnostic push 5066 #pragma clang diagnostic ignored "-Wpadded" 5072 #pragma clang diagnostic push 5073 #pragma clang diagnostic ignored "-Wpadded" 5080 class WildcardPattern {
5081 enum WildcardPosition {
5083 WildcardAtStart = 1,
5085 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5090 WildcardPattern( std::string
const& pattern, CaseSensitive::Choice caseSensitivity );
5091 virtual ~WildcardPattern() =
default;
5092 virtual bool matches( std::string
const& str )
const;
5095 std::string normaliseString( std::string
const& str )
const;
5096 CaseSensitive::Choice m_caseSensitivity;
5097 WildcardPosition m_wildcard = NoWildcard;
5098 std::string m_pattern;
5114 explicit Pattern( std::string
const& name );
5116 virtual bool matches(
TestCaseInfo const& testCase )
const = 0;
5117 std::string
const& name()
const;
5119 std::string
const m_name;
5121 using PatternPtr = std::shared_ptr<Pattern>;
5123 class NamePattern :
public Pattern {
5125 explicit NamePattern( std::string
const& name, std::string
const& filterString );
5126 bool matches(
TestCaseInfo const& testCase )
const override;
5128 WildcardPattern m_wildcardPattern;
5131 class TagPattern :
public Pattern {
5133 explicit TagPattern( std::string
const& tag, std::string
const& filterString );
5134 bool matches(
TestCaseInfo const& testCase )
const override;
5139 class ExcludedPattern :
public Pattern {
5141 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5142 bool matches(
TestCaseInfo const& testCase )
const override;
5144 PatternPtr m_underlyingPattern;
5148 std::vector<PatternPtr> m_patterns;
5151 std::string name()
const;
5155 struct FilterMatch {
5157 std::vector<TestCase const*> tests;
5159 using Matches = std::vector<FilterMatch>;
5160 using vectorStrings = std::vector<std::string>;
5162 bool hasFilters()
const;
5164 Matches matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const;
5165 const vectorStrings & getInvalidArgs()
const;
5168 std::vector<Filter> m_filters;
5169 std::vector<std::string> m_invalidArgs;
5170 friend class TestSpecParser;
5175 #pragma clang diagnostic pop 5187 struct ITagAliasRegistry {
5188 virtual ~ITagAliasRegistry();
5190 virtual TagAlias
const* find( std::string
const& alias )
const = 0;
5191 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
5193 static ITagAliasRegistry
const&
get();
5201 class TestSpecParser {
5202 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5204 Mode lastMode = None;
5205 bool m_exclusion =
false;
5206 std::size_t m_pos = 0;
5207 std::size_t m_realPatternPos = 0;
5209 std::string m_substring;
5210 std::string m_patternName;
5211 std::vector<std::size_t> m_escapeChars;
5212 TestSpec::Filter m_currentFilter;
5213 TestSpec m_testSpec;
5214 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5217 TestSpecParser( ITagAliasRegistry
const& tagAliases );
5219 TestSpecParser& parse( std::string
const& arg );
5220 TestSpec testSpec();
5223 bool visitChar(
char c );
5224 void startNewMode( Mode mode );
5225 bool processNoneChar(
char c );
5226 void processNameChar(
char c );
5227 bool processOtherChar(
char c );
5230 bool isControlChar(
char c )
const;
5231 void saveLastMode();
5232 void revertBackToLastMode();
5237 std::string preprocessPattern();
5239 void addNamePattern();
5241 void addTagPattern();
5243 inline void addCharToPattern(
char c) {
5250 TestSpec parseTestSpec( std::string
const& arg );
5255 #pragma clang diagnostic pop 5265 #ifndef CATCH_CONFIG_CONSOLE_WIDTH 5266 #define CATCH_CONFIG_CONSOLE_WIDTH 80 5274 bool listTests =
false;
5275 bool listTags =
false;
5276 bool listReporters =
false;
5277 bool listTestNamesOnly =
false;
5279 bool showSuccessfulTests =
false;
5280 bool shouldDebugBreak =
false;
5281 bool noThrow =
false;
5282 bool showHelp =
false;
5283 bool showInvisibles =
false;
5284 bool filenamesAsTags =
false;
5285 bool libIdentify =
false;
5287 int abortAfter = -1;
5288 unsigned int rngSeed = 0;
5290 bool benchmarkNoAnalysis =
false;
5291 unsigned int benchmarkSamples = 100;
5292 double benchmarkConfidenceInterval = 0.95;
5293 unsigned int benchmarkResamples = 100000;
5294 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5296 Verbosity verbosity = Verbosity::Normal;
5297 WarnAbout::What warnings = WarnAbout::Nothing;
5298 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5299 double minDuration = -1;
5300 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5301 UseColour::YesOrNo useColour = UseColour::Auto;
5302 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5304 std::string outputFilename;
5306 std::string processName;
5307 #ifndef CATCH_CONFIG_DEFAULT_REPORTER 5308 #define CATCH_CONFIG_DEFAULT_REPORTER "console" 5310 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5311 #undef CATCH_CONFIG_DEFAULT_REPORTER 5313 std::vector<std::string> testsOrTags;
5314 std::vector<std::string> sectionsToRun;
5317 class Config :
public IConfig {
5321 Config( ConfigData
const& data );
5322 virtual ~Config() =
default;
5324 std::string
const& getFilename()
const;
5326 bool listTests()
const;
5327 bool listTestNamesOnly()
const;
5328 bool listTags()
const;
5329 bool listReporters()
const;
5331 std::string getProcessName()
const;
5332 std::string
const& getReporterName()
const;
5334 std::vector<std::string>
const& getTestsOrTags()
const override;
5335 std::vector<std::string>
const& getSectionsToRun()
const override;
5337 TestSpec
const& testSpec()
const override;
5338 bool hasTestFilters()
const override;
5340 bool showHelp()
const;
5343 bool allowThrows()
const override;
5344 std::ostream& stream()
const override;
5345 std::string name()
const override;
5346 bool includeSuccessfulResults()
const override;
5347 bool warnAboutMissingAssertions()
const override;
5348 bool warnAboutNoTests()
const override;
5349 ShowDurations::OrNot showDurations()
const override;
5350 double minDuration()
const override;
5351 RunTests::InWhatOrder runOrder()
const override;
5352 unsigned int rngSeed()
const override;
5353 UseColour::YesOrNo useColour()
const override;
5354 bool shouldDebugBreak()
const override;
5355 int abortAfter()
const override;
5356 bool showInvisibles()
const override;
5357 Verbosity verbosity()
const override;
5358 bool benchmarkNoAnalysis()
const override;
5359 int benchmarkSamples()
const override;
5360 double benchmarkConfidenceInterval()
const override;
5361 unsigned int benchmarkResamples()
const override;
5362 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5369 std::unique_ptr<IStream const> m_stream;
5370 TestSpec m_testSpec;
5371 bool m_hasTestFilters =
false;
5383 struct AssertionResultData
5385 AssertionResultData() =
delete;
5387 AssertionResultData( ResultWas::OfType _resultType,
LazyExpression const& _lazyExpression );
5389 std::string message;
5390 mutable std::string reconstructedExpression;
5392 ResultWas::OfType resultType;
5394 std::string reconstructExpression()
const;
5397 class AssertionResult {
5399 AssertionResult() =
delete;
5400 AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data );
5403 bool succeeded()
const;
5404 ResultWas::OfType getResultType()
const;
5405 bool hasExpression()
const;
5406 bool hasMessage()
const;
5407 std::string getExpression()
const;
5408 std::string getExpressionInMacro()
const;
5409 bool hasExpandedExpression()
const;
5410 std::string getExpandedExpression()
const;
5411 std::string getMessage()
const;
5417 AssertionResultData m_resultData;
5423 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5430 namespace Benchmark {
5431 template <
typename Duration>
5434 Duration lower_bound;
5435 Duration upper_bound;
5436 double confidence_interval;
5438 template <
typename Duration2>
5439 operator Estimate<Duration2>()
const {
5440 return { point, lower_bound, upper_bound, confidence_interval };
5452 namespace Benchmark {
5453 struct OutlierClassification {
5454 int samples_seen = 0;
5458 int high_severe = 0;
5461 return low_severe + low_mild + high_mild + high_severe;
5470 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5477 #include <algorithm> 5481 struct ReporterConfig {
5482 explicit ReporterConfig( IConfigPtr
const& _fullConfig );
5484 ReporterConfig( IConfigPtr
const& _fullConfig, std::ostream& _stream );
5486 std::ostream& stream()
const;
5487 IConfigPtr fullConfig()
const;
5490 std::ostream* m_stream;
5491 IConfigPtr m_fullConfig;
5494 struct ReporterPreferences {
5495 bool shouldRedirectStdOut =
false;
5496 bool shouldReportAllAssertions =
false;
5499 template<
typename T>
5500 struct LazyStat :
Option<T> {
5501 LazyStat& operator=( T
const& _value ) {
5513 struct TestRunInfo {
5514 TestRunInfo( std::string
const& _name );
5518 GroupInfo( std::string
const& _name,
5519 std::size_t _groupIndex,
5520 std::size_t _groupsCount );
5523 std::size_t groupIndex;
5524 std::size_t groupsCounts;
5527 struct AssertionStats {
5528 AssertionStats( AssertionResult
const& _assertionResult,
5529 std::vector<MessageInfo>
const& _infoMessages,
5532 AssertionStats( AssertionStats
const& ) =
default;
5533 AssertionStats( AssertionStats && ) =
default;
5534 AssertionStats& operator = ( AssertionStats
const& ) =
delete;
5535 AssertionStats& operator = ( AssertionStats && ) =
delete;
5536 virtual ~AssertionStats();
5538 AssertionResult assertionResult;
5539 std::vector<MessageInfo> infoMessages;
5543 struct SectionStats {
5545 Counts const& _assertions,
5546 double _durationInSeconds,
5547 bool _missingAssertions );
5548 SectionStats( SectionStats
const& ) =
default;
5549 SectionStats( SectionStats && ) =
default;
5550 SectionStats& operator = ( SectionStats
const& ) =
default;
5551 SectionStats& operator = ( SectionStats && ) =
default;
5552 virtual ~SectionStats();
5556 double durationInSeconds;
5557 bool missingAssertions;
5560 struct TestCaseStats {
5563 std::string
const& _stdOut,
5564 std::string
const& _stdErr,
5567 TestCaseStats( TestCaseStats
const& ) =
default;
5568 TestCaseStats( TestCaseStats && ) =
default;
5569 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5570 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5571 virtual ~TestCaseStats();
5580 struct TestGroupStats {
5581 TestGroupStats( GroupInfo
const& _groupInfo,
5584 TestGroupStats( GroupInfo
const& _groupInfo );
5586 TestGroupStats( TestGroupStats
const& ) =
default;
5587 TestGroupStats( TestGroupStats && ) =
default;
5588 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5589 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5590 virtual ~TestGroupStats();
5592 GroupInfo groupInfo;
5597 struct TestRunStats {
5598 TestRunStats( TestRunInfo
const& _runInfo,
5602 TestRunStats( TestRunStats
const& ) =
default;
5603 TestRunStats( TestRunStats && ) =
default;
5604 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5605 TestRunStats& operator = ( TestRunStats && ) =
default;
5606 virtual ~TestRunStats();
5608 TestRunInfo runInfo;
5613 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5614 struct BenchmarkInfo {
5616 double estimatedDuration;
5619 unsigned int resamples;
5620 double clockResolution;
5624 template <
class Duration>
5625 struct BenchmarkStats {
5628 std::vector<Duration> samples;
5629 Benchmark::Estimate<Duration> mean;
5630 Benchmark::Estimate<Duration> standardDeviation;
5631 Benchmark::OutlierClassification outliers;
5632 double outlierVariance;
5634 template <
typename Duration2>
5635 operator BenchmarkStats<Duration2>()
const {
5636 std::vector<Duration2> samples2;
5637 samples2.reserve(samples.size());
5638 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) {
return Duration2(d); });
5641 std::move(samples2),
5649 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5651 struct IStreamingReporter {
5652 virtual ~IStreamingReporter() =
default;
5658 virtual ReporterPreferences getPreferences()
const = 0;
5660 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5662 virtual void reportInvalidArguments(std::string
const&) {}
5664 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5665 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5667 virtual void testCaseStarting(
TestCaseInfo const& testInfo ) = 0;
5668 virtual void sectionStarting(
SectionInfo const& sectionInfo ) = 0;
5670 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 5671 virtual void benchmarkPreparing( std::string
const& ) {}
5672 virtual void benchmarkStarting( BenchmarkInfo
const& ) {}
5673 virtual void benchmarkEnded( BenchmarkStats<>
const& ) {}
5674 virtual void benchmarkFailed( std::string
const& ) {}
5675 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 5677 virtual void assertionStarting(
AssertionInfo const& assertionInfo ) = 0;
5680 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5682 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5683 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5684 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5685 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5687 virtual void skipTest(
TestCaseInfo const& testInfo ) = 0;
5690 virtual void fatalErrorEncountered(
StringRef name );
5692 virtual bool isMulti()
const;
5694 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5696 struct IReporterFactory {
5697 virtual ~IReporterFactory();
5698 virtual IStreamingReporterPtr create( ReporterConfig
const& config )
const = 0;
5699 virtual std::string getDescription()
const = 0;
5701 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5703 struct IReporterRegistry {
5704 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5705 using Listeners = std::vector<IReporterFactoryPtr>;
5707 virtual ~IReporterRegistry();
5708 virtual IStreamingReporterPtr create( std::string
const& name, IConfigPtr
const& config )
const = 0;
5709 virtual FactoryMap
const& getFactories()
const = 0;
5710 virtual Listeners
const& getListeners()
const = 0;
5716 #include <algorithm> 5725 void prepareExpandedExpression(AssertionResult& result);
5728 std::string getFormattedDuration(
double duration );
5731 bool shouldShowDuration(
IConfig const& config,
double duration );
5733 std::string serializeFilters( std::vector<std::string>
const& container );
5735 template<
typename DerivedT>
5736 struct StreamingReporterBase : IStreamingReporter {
5738 StreamingReporterBase( ReporterConfig
const& _config )
5739 : m_config( _config.fullConfig() ),
5740 stream( _config.stream() )
5742 m_reporterPrefs.shouldRedirectStdOut =
false;
5743 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5744 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5747 ReporterPreferences getPreferences()
const override {
5748 return m_reporterPrefs;
5751 static std::set<Verbosity> getSupportedVerbosities() {
5752 return { Verbosity::Normal };
5755 ~StreamingReporterBase()
override =
default;
5757 void noMatchingTestCases(std::string
const&)
override {}
5759 void reportInvalidArguments(std::string
const&)
override {}
5761 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5762 currentTestRunInfo = _testRunInfo;
5765 void testGroupStarting(GroupInfo
const& _groupInfo)
override {
5766 currentGroupInfo = _groupInfo;
5769 void testCaseStarting(
TestCaseInfo const& _testInfo)
override {
5770 currentTestCaseInfo = _testInfo;
5772 void sectionStarting(
SectionInfo const& _sectionInfo)
override {
5773 m_sectionStack.push_back(_sectionInfo);
5776 void sectionEnded(SectionStats
const& )
override {
5777 m_sectionStack.pop_back();
5779 void testCaseEnded(TestCaseStats
const& )
override {
5780 currentTestCaseInfo.reset();
5782 void testGroupEnded(TestGroupStats
const& )
override {
5783 currentGroupInfo.reset();
5785 void testRunEnded(TestRunStats
const& )
override {
5786 currentTestCaseInfo.reset();
5787 currentGroupInfo.reset();
5788 currentTestRunInfo.reset();
5796 IConfigPtr m_config;
5797 std::ostream& stream;
5799 LazyStat<TestRunInfo> currentTestRunInfo;
5800 LazyStat<GroupInfo> currentGroupInfo;
5801 LazyStat<TestCaseInfo> currentTestCaseInfo;
5803 std::vector<SectionInfo> m_sectionStack;
5804 ReporterPreferences m_reporterPrefs;
5807 template<
typename DerivedT>
5808 struct CumulativeReporterBase : IStreamingReporter {
5809 template<
typename T,
typename ChildNodeT>
5811 explicit Node( T
const& _value ) : value( _value ) {}
5814 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5816 ChildNodes children;
5818 struct SectionNode {
5819 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5820 virtual ~SectionNode() =
default;
5822 bool operator == (SectionNode
const& other)
const {
5823 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5825 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5826 return operator==(*other);
5830 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5831 using Assertions = std::vector<AssertionStats>;
5832 ChildSections childSections;
5833 Assertions assertions;
5838 struct BySectionInfo {
5839 BySectionInfo(
SectionInfo const& other ) : m_other( other ) {}
5840 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
5841 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5842 return ((node->stats.sectionInfo.name == m_other.name) &&
5843 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5845 void operator=(BySectionInfo
const&) =
delete;
5851 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5852 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5853 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5855 CumulativeReporterBase( ReporterConfig
const& _config )
5856 : m_config( _config.fullConfig() ),
5857 stream( _config.stream() )
5859 m_reporterPrefs.shouldRedirectStdOut =
false;
5860 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5861 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5863 ~CumulativeReporterBase()
override =
default;
5865 ReporterPreferences getPreferences()
const override {
5866 return m_reporterPrefs;
5869 static std::set<Verbosity> getSupportedVerbosities() {
5870 return { Verbosity::Normal };
5873 void testRunStarting( TestRunInfo
const& )
override {}
5874 void testGroupStarting( GroupInfo
const& )
override {}
5876 void testCaseStarting(
TestCaseInfo const& )
override {}
5878 void sectionStarting(
SectionInfo const& sectionInfo )
override {
5879 SectionStats incompleteStats( sectionInfo,
Counts(), 0,
false );
5880 std::shared_ptr<SectionNode> node;
5881 if( m_sectionStack.empty() ) {
5882 if( !m_rootSection )
5883 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5884 node = m_rootSection;
5887 SectionNode& parentNode = *m_sectionStack.back();
5889 std::find_if( parentNode.childSections.begin(),
5890 parentNode.childSections.end(),
5891 BySectionInfo( sectionInfo ) );
5892 if( it == parentNode.childSections.end() ) {
5893 node = std::make_shared<SectionNode>( incompleteStats );
5894 parentNode.childSections.push_back( node );
5899 m_sectionStack.push_back( node );
5900 m_deepestSection = std::move(node);
5905 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5906 assert(!m_sectionStack.empty());
5912 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5913 SectionNode& sectionNode = *m_sectionStack.back();
5914 sectionNode.assertions.push_back(assertionStats);
5917 void sectionEnded(SectionStats
const& sectionStats)
override {
5918 assert(!m_sectionStack.empty());
5919 SectionNode& node = *m_sectionStack.back();
5920 node.stats = sectionStats;
5921 m_sectionStack.pop_back();
5923 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5924 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5925 assert(m_sectionStack.size() == 0);
5926 node->children.push_back(m_rootSection);
5927 m_testCases.push_back(node);
5928 m_rootSection.reset();
5930 assert(m_deepestSection);
5931 m_deepestSection->stdOut = testCaseStats.stdOut;
5932 m_deepestSection->stdErr = testCaseStats.stdErr;
5934 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5935 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5936 node->children.swap(m_testCases);
5937 m_testGroups.push_back(node);
5939 void testRunEnded(TestRunStats
const& testRunStats)
override {
5940 auto node = std::make_shared<TestRunNode>(testRunStats);
5941 node->children.swap(m_testGroups);
5942 m_testRuns.push_back(node);
5943 testRunEndedCumulative();
5945 virtual void testRunEndedCumulative() = 0;
5949 IConfigPtr m_config;
5950 std::ostream& stream;
5951 std::vector<AssertionStats> m_assertions;
5952 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5953 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5954 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5956 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5958 std::shared_ptr<SectionNode> m_rootSection;
5959 std::shared_ptr<SectionNode> m_deepestSection;
5960 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5961 ReporterPreferences m_reporterPrefs;
5965 char const* getLineOfChars() {
5966 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5968 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5969 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5974 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5975 TestEventListenerBase( ReporterConfig
const& _config );
5977 static std::set<Verbosity> getSupportedVerbosities();
5980 bool assertionEnded(AssertionStats
const&)
override;
6004 BrightRed = Bright | Red,
6005 BrightGreen = Bright | Green,
6006 LightGrey = Bright | Grey,
6007 BrightWhite = Bright | White,
6008 BrightYellow = Bright | Yellow,
6011 FileName = LightGrey,
6012 Warning = BrightYellow,
6013 ResultError = BrightRed,
6014 ResultSuccess = BrightGreen,
6015 ResultExpectedFailure = Warning,
6020 OriginalExpression = Cyan,
6021 ReconstructedExpression = BrightYellow,
6023 SecondaryText = LightGrey,
6028 Colour( Code _colourCode );
6029 Colour( Colour&& other ) noexcept;
6030 Colour& operator=( Colour&& other ) noexcept;
6034 static void use( Code _colourCode );
6037 bool m_moved =
false;
6040 std::ostream& operator << ( std::ostream& os, Colour
const& );
6050 template<
typename T>
6051 class ReporterRegistrar {
6053 class ReporterFactory :
public IReporterFactory {
6055 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6056 return std::unique_ptr<T>(
new T( config ) );
6059 std::string getDescription()
const override {
6060 return T::getDescription();
6066 explicit ReporterRegistrar( std::string
const& name ) {
6067 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6071 template<
typename T>
6072 class ListenerRegistrar {
6074 class ListenerFactory :
public IReporterFactory {
6076 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6077 return std::unique_ptr<T>(
new T( config ) );
6079 std::string getDescription()
const override {
6080 return std::string();
6086 ListenerRegistrar() {
6087 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6092 #if !defined(CATCH_CONFIG_DISABLE) 6094 #define CATCH_REGISTER_REPORTER( name, reporterType ) \ 6095 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6096 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6097 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \ 6098 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6100 #define CATCH_REGISTER_LISTENER( listenerType ) \ 6101 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ 6102 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ 6103 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \ 6104 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION 6105 #else // CATCH_CONFIG_DISABLE 6107 #define CATCH_REGISTER_REPORTER(name, reporterType) 6108 #define CATCH_REGISTER_LISTENER(listenerType) 6110 #endif // CATCH_CONFIG_DISABLE 6118 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6120 using StreamingReporterBase::StreamingReporterBase;
6122 ~CompactReporter()
override;
6124 static std::string getDescription();
6126 void noMatchingTestCases(std::string
const& spec)
override;
6130 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6132 void sectionEnded(SectionStats
const& _sectionStats)
override;
6134 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6143 #if defined(_MSC_VER) 6144 #pragma warning(push) 6145 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 6152 struct SummaryColumn;
6155 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6156 std::unique_ptr<TablePrinter> m_tablePrinter;
6158 ConsoleReporter(ReporterConfig
const& config);
6159 ~ConsoleReporter()
override;
6160 static std::string getDescription();
6162 void noMatchingTestCases(std::string
const& spec)
override;
6164 void reportInvalidArguments(std::string
const&arg)
override;
6168 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6170 void sectionStarting(
SectionInfo const& _sectionInfo)
override;
6171 void sectionEnded(SectionStats
const& _sectionStats)
override;
6173 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6174 void benchmarkPreparing(std::string
const& name)
override;
6175 void benchmarkStarting(BenchmarkInfo
const& info)
override;
6176 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6177 void benchmarkFailed(std::string
const& error)
override;
6178 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6180 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6181 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6182 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6183 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6188 void lazyPrintWithoutClosingBenchmarkTable();
6189 void lazyPrintRunInfo();
6190 void lazyPrintGroupInfo();
6191 void printTestCaseAndSectionHeader();
6193 void printClosedHeader(std::string
const& _name);
6194 void printOpenHeader(std::string
const& _name);
6198 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6200 void printTotals(
Totals const& totals);
6201 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row);
6203 void printTotalsDivider(
Totals const& totals);
6204 void printSummaryDivider();
6205 void printTestFilters();
6208 bool m_headerPrinted =
false;
6213 #if defined(_MSC_VER) 6214 #pragma warning(pop) 6225 enum class XmlFormatting {
6231 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6232 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6236 enum ForWhat { ForTextNodes, ForAttributes };
6238 XmlEncode( std::string
const& str, ForWhat forWhat = ForTextNodes );
6240 void encodeTo( std::ostream& os )
const;
6242 friend std::ostream& operator << ( std::ostream& os, XmlEncode
const& xmlEncode );
6252 class ScopedElement {
6254 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6256 ScopedElement( ScopedElement&& other ) noexcept;
6257 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6261 ScopedElement& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6263 template<
typename T>
6264 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
6265 m_writer->writeAttribute( name, attribute );
6270 mutable XmlWriter* m_writer =
nullptr;
6271 XmlFormatting m_fmt;
6274 XmlWriter( std::ostream& os = Catch::cout() );
6277 XmlWriter( XmlWriter
const& ) =
delete;
6278 XmlWriter& operator=( XmlWriter
const& ) =
delete;
6280 XmlWriter& startElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6282 ScopedElement scopedElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6284 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6286 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute );
6288 XmlWriter& writeAttribute( std::string
const& name,
bool attribute );
6290 template<
typename T>
6291 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
6294 return writeAttribute( name, rss.str() );
6297 XmlWriter& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6299 XmlWriter& writeComment(std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6301 void writeStylesheetRef( std::string
const& url );
6303 XmlWriter& writeBlankLine();
6305 void ensureTagClosed();
6309 void applyFormatting(XmlFormatting fmt);
6311 void writeDeclaration();
6313 void newlineIfNecessary();
6315 bool m_tagIsOpen =
false;
6316 bool m_needsNewline =
false;
6317 std::vector<std::string> m_tags;
6318 std::string m_indent;
6327 class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6329 JunitReporter(ReporterConfig
const& _config);
6331 ~JunitReporter()
override;
6333 static std::string getDescription();
6335 void noMatchingTestCases(std::string
const& )
override;
6337 void testRunStarting(TestRunInfo
const& runInfo)
override;
6339 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6341 void testCaseStarting(
TestCaseInfo const& testCaseInfo)
override;
6342 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6344 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6346 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6348 void testRunEndedCumulative()
override;
6350 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6352 void writeTestCase(TestCaseNode
const& testCaseNode);
6354 void writeSection( std::string
const& className,
6355 std::string
const& rootName,
6356 SectionNode
const& sectionNode,
6357 bool testOkToFail );
6359 void writeAssertions(SectionNode
const& sectionNode);
6360 void writeAssertion(AssertionStats
const& stats);
6364 std::string stdOutForSuite;
6365 std::string stdErrForSuite;
6366 unsigned int unexpectedExceptions = 0;
6367 bool m_okToFail =
false;
6376 class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6378 XmlReporter(ReporterConfig
const& _config);
6380 ~XmlReporter()
override;
6382 static std::string getDescription();
6384 virtual std::string getStylesheetRef()
const;
6390 void noMatchingTestCases(std::string
const& s)
override;
6392 void testRunStarting(TestRunInfo
const& testInfo)
override;
6394 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6396 void testCaseStarting(
TestCaseInfo const& testInfo)
override;
6398 void sectionStarting(
SectionInfo const& sectionInfo)
override;
6402 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6404 void sectionEnded(SectionStats
const& sectionStats)
override;
6406 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6408 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6410 void testRunEnded(TestRunStats
const& testRunStats)
override;
6412 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6413 void benchmarkPreparing(std::string
const& name)
override;
6414 void benchmarkStarting(BenchmarkInfo
const&)
override;
6415 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6416 void benchmarkFailed(std::string
const&)
override;
6417 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 6420 Timer m_testCaseTimer;
6422 int m_sectionDepth = 0;
6432 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 6457 namespace Benchmark {
6458 template <
typename Clock>
6459 using ClockDuration =
typename Clock::duration;
6460 template <
typename Clock>
6461 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6463 template <
typename Clock>
6464 using TimePoint =
typename Clock::time_point;
6466 using default_clock = std::chrono::steady_clock;
6468 template <
typename Clock>
6470 TimePoint<Clock> operator()()
const {
6471 return Clock::now();
6475 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6485 #if defined(_MSC_VER) 6490 namespace Benchmark {
6491 #if defined(__GNUC__) || defined(__clang__) 6492 template <
typename T>
6493 inline void keep_memory(T* p) {
6494 asm volatile(
"" : :
"g"(p) :
"memory");
6496 inline void keep_memory() {
6497 asm volatile(
"" : : :
"memory");
6501 inline void optimizer_barrier() { keep_memory(); }
6503 #elif defined(_MSC_VER) 6505 #pragma optimize("", off) 6506 template <
typename T>
6507 inline void keep_memory(T* p) {
6509 *
reinterpret_cast<char volatile*
>(p) = *reinterpret_cast<char const volatile*>(p);
6512 #pragma optimize("", on) 6515 inline void optimizer_barrier() {
6516 std::atomic_thread_fence(std::memory_order_seq_cst);
6522 template <
typename T>
6523 inline void deoptimize_value(T&& x) {
6527 template <
typename Fn,
typename... Args>
6528 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6529 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6532 template <
typename Fn,
typename... Args>
6533 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6534 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6545 #include <type_traits> 6549 namespace Benchmark {
6551 template <
typename T>
6552 struct CompleteType {
using type = T; };
6554 struct CompleteType<void> {
struct type {}; };
6556 template <
typename T>
6557 using CompleteType_t =
typename CompleteType<T>::type;
6559 template <
typename Result>
6560 struct CompleteInvoker {
6561 template <
typename Fun,
typename... Args>
6562 static Result invoke(Fun&& fun, Args&&... args) {
6563 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6567 struct CompleteInvoker<void> {
6568 template <
typename Fun,
typename... Args>
6569 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6570 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6576 template <
typename Fun,
typename... Args>
6577 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6578 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6581 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6584 template <
typename Fun>
6585 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6587 return Detail::complete_invoke(std::forward<Fun>(fun));
6589 getResultCapture().benchmarkFailed(translateActiveException());
6590 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6598 namespace Benchmark {
6600 struct ChronometerConcept {
6601 virtual void start() = 0;
6602 virtual void finish() = 0;
6603 virtual ~ChronometerConcept() =
default;
6605 template <
typename Clock>
6606 struct ChronometerModel final :
public ChronometerConcept {
6607 void start()
override { started = Clock::now(); }
6608 void finish()
override { finished = Clock::now(); }
6610 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6612 TimePoint<Clock> started;
6613 TimePoint<Clock> finished;
6617 struct Chronometer {
6619 template <
typename Fun>
6620 void measure(Fun&& fun) { measure(std::forward<Fun>(fun),
is_callable<Fun(
int)>()); }
6622 int runs()
const {
return k; }
6624 Chronometer(Detail::ChronometerConcept& meter,
int k)
6629 template <
typename Fun>
6630 void measure(Fun&& fun, std::false_type) {
6631 measure([&fun](
int) {
return fun(); }, std::true_type());
6634 template <
typename Fun>
6635 void measure(Fun&& fun, std::true_type) {
6636 Detail::optimizer_barrier();
6638 for (
int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6640 Detail::optimizer_barrier();
6643 Detail::ChronometerConcept* impl;
6656 namespace Benchmark {
6657 template <
typename Duration>
6658 struct EnvironmentEstimate {
6660 OutlierClassification outliers;
6662 template <
typename Duration2>
6663 operator EnvironmentEstimate<Duration2>()
const {
6664 return { mean, outliers };
6667 template <
typename Clock>
6668 struct Environment {
6669 using clock_type = Clock;
6670 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6671 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6688 #include <type_traits> 6693 namespace Benchmark {
6695 template <
typename T>
6696 using Decay =
typename std::decay<T>::type;
6697 template <
typename T,
typename U>
6699 : std::is_same<Decay<T>, Decay<U>> {};
6708 struct BenchmarkFunction {
6711 virtual void call(Chronometer meter)
const = 0;
6712 virtual callable* clone()
const = 0;
6713 virtual ~callable() =
default;
6715 template <
typename Fun>
6716 struct model :
public callable {
6717 model(Fun&& fun) : fun(std::move(fun)) {}
6718 model(Fun
const& fun) : fun(fun) {}
6720 model<Fun>* clone()
const override {
return new model<Fun>(*this); }
6722 void call(Chronometer meter)
const override {
6725 void call(Chronometer meter, std::true_type)
const {
6728 void call(Chronometer meter, std::false_type)
const {
6735 struct do_nothing {
void operator()()
const {} };
6737 template <
typename T>
6738 BenchmarkFunction(model<T>* c) : f(c) {}
6742 : f(
new model<do_nothing>{ {} }) {}
6744 template <
typename Fun,
6745 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
int>::type = 0>
6746 BenchmarkFunction(Fun&& fun)
6747 : f(
new model<
typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6749 BenchmarkFunction(BenchmarkFunction&& that)
6750 : f(std::move(that.f)) {}
6752 BenchmarkFunction(BenchmarkFunction
const& that)
6753 : f(that.f->clone()) {}
6755 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6756 f = std::move(that.f);
6760 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6761 f.reset(that.f->clone());
6765 void operator()(Chronometer meter)
const { f->call(meter); }
6768 std::unique_ptr<callable> f;
6780 #include <type_traits> 6784 namespace Benchmark {
6786 template <
typename Fun>
6788 void operator()(
int k)
const {
6789 for (
int i = 0; i < k; ++i) {
6795 template <
typename Fun>
6796 repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6797 return { std::forward<Fun>(fun) };
6820 #include <type_traits> 6823 namespace Benchmark {
6824 template <
typename Duration,
typename Result>
6830 template <
typename Clock,
typename Func,
typename... Args>
6831 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6839 namespace Benchmark {
6841 template <
typename Clock,
typename Fun,
typename... Args>
6842 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6843 auto start = Clock::now();
6844 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6845 auto end = Clock::now();
6846 auto delta = end - start;
6847 return { delta, std::forward<decltype(r)>(r), 1 };
6855 #include <type_traits> 6858 namespace Benchmark {
6860 template <
typename Clock,
typename Fun>
6861 TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6862 return Detail::measure<Clock>(fun, iters);
6864 template <
typename Clock,
typename Fun>
6865 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6866 Detail::ChronometerModel<Clock> meter;
6867 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6869 return { meter.elapsed(), std::move(result), iters };
6872 template <
typename Clock,
typename Fun>
6873 using run_for_at_least_argument_t =
typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer,
int>::type;
6875 struct optimized_away_error : std::exception {
6876 const char* what()
const noexcept
override {
6877 return "could not measure benchmark, maybe it was optimized away";
6881 template <
typename Clock,
typename Fun>
6882 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6884 while (iters < (1 << 30)) {
6887 if (Timing.elapsed >= how_long) {
6888 return { Timing.elapsed, std::move(Timing.result), iters };
6892 Catch::throw_exception(optimized_away_error{});
6899 #include <algorithm> 6903 namespace Benchmark {
6904 template <
typename Duration>
6905 struct ExecutionPlan {
6906 int iterations_per_sample;
6907 Duration estimated_duration;
6908 Detail::BenchmarkFunction benchmark;
6909 Duration warmup_time;
6910 int warmup_iterations;
6912 template <
typename Duration2>
6913 operator ExecutionPlan<Duration2>()
const {
6914 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6917 template <
typename Clock>
6918 std::vector<FloatDuration<Clock>> run(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
6920 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6922 std::vector<FloatDuration<Clock>> times;
6923 times.reserve(cfg.benchmarkSamples());
6924 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6925 Detail::ChronometerModel<Clock> model;
6926 this->benchmark(Chronometer(model, iterations_per_sample));
6927 auto sample_time = model.elapsed() - env.clock_cost.mean;
6928 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6929 return sample_time / iterations_per_sample;
6948 #include <algorithm> 6949 #include <functional> 6960 namespace Benchmark {
6962 using sample = std::vector<double>;
6964 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6966 template <
typename Iterator>
6967 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6968 std::vector<double> copy(first, last);
6970 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6971 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6973 auto los = q1 - (iqr * 3.);
6974 auto lom = q1 - (iqr * 1.5);
6975 auto him = q3 + (iqr * 1.5);
6976 auto his = q3 + (iqr * 3.);
6978 OutlierClassification o;
6979 for (; first != last; ++first) {
6981 if (t < los) ++o.low_severe;
6982 else if (t < lom) ++o.low_mild;
6983 else if (t > his) ++o.high_severe;
6984 else if (t > him) ++o.high_mild;
6990 template <
typename Iterator>
6991 double mean(Iterator first, Iterator last) {
6992 auto count = last - first;
6993 double sum = std::accumulate(first, last, 0.);
6997 template <
typename URng,
typename Iterator,
typename Estimator>
6998 sample resample(URng& rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
6999 auto n = last - first;
7000 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7003 out.reserve(resamples);
7004 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7005 std::vector<double> resampled;
7006 resampled.reserve(n);
7007 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
return first[dist(rng)]; });
7008 return estimator(resampled.begin(), resampled.end());
7010 std::sort(out.begin(), out.end());
7014 template <
typename Estimator,
typename Iterator>
7015 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7016 auto n = last - first;
7017 auto second = std::next(first);
7021 for (
auto it = first; it != last; ++it) {
7022 std::iter_swap(it, first);
7023 results.push_back(estimator(second, last));
7029 inline double normal_cdf(
double x) {
7030 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7033 double erfc_inv(
double x);
7035 double normal_quantile(
double p);
7037 template <
typename Iterator,
typename Estimator>
7038 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last, sample
const& resample, Estimator&& estimator) {
7039 auto n_samples = last - first;
7041 double point = estimator(first, last);
7043 if (n_samples == 1)
return { point, point, point, confidence_level };
7045 sample jack = jackknife(estimator, first, last);
7046 double jack_mean = mean(jack.begin(), jack.end());
7047 double sum_squares, sum_cubes;
7048 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> {
7049 auto d = jack_mean - x;
7052 return { sqcb.first + d2, sqcb.second + d3 };
7055 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7056 int n =
static_cast<int>(resample.size());
7057 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) {
return x < point; }) / (
double)n;
7059 if (prob_n == 0)
return { point, point, point, confidence_level };
7061 double bias = normal_quantile(prob_n);
7062 double z1 = normal_quantile((1. - confidence_level) / 2.);
7064 auto cumn = [n](
double x) ->
int {
7065 return std::lround(normal_cdf(x) * n); };
7066 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7067 double b1 = bias + z1;
7068 double b2 = bias - z1;
7071 auto lo = (std::max)(cumn(a1), 0);
7072 auto hi = (std::min)(cumn(a2), n - 1);
7074 return { point, resample[lo], resample[hi], confidence_level };
7077 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7079 struct bootstrap_analysis {
7080 Estimate<double> mean;
7081 Estimate<double> standard_deviation;
7082 double outlier_variance;
7085 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7091 #include <algorithm> 7098 namespace Benchmark {
7100 template <
typename Clock>
7101 std::vector<double> resolution(
int k) {
7102 std::vector<TimePoint<Clock>> times;
7103 times.reserve(k + 1);
7104 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7106 std::vector<double> deltas;
7108 std::transform(std::next(times.begin()), times.end(), times.begin(),
7109 std::back_inserter(deltas),
7110 [](TimePoint<Clock> a, TimePoint<Clock> b) {
return static_cast<double>((a - b).count()); });
7115 const auto warmup_iterations = 10000;
7116 const auto warmup_time = std::chrono::milliseconds(100);
7117 const auto minimum_ticks = 1000;
7118 const auto warmup_seed = 10000;
7119 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7120 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7121 const auto clock_cost_estimation_tick_limit = 100000;
7122 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7123 const auto clock_cost_estimation_iterations = 10000;
7125 template <
typename Clock>
7127 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7130 template <
typename Clock>
7131 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7132 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7135 FloatDuration<Clock>(mean(r.begin(), r.end())),
7136 classify_outliers(r.begin(), r.end()),
7139 template <
typename Clock>
7140 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7141 auto time_limit = (std::min)(
7142 resolution * clock_cost_estimation_tick_limit,
7143 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7144 auto time_clock = [](
int k) {
7145 return Detail::measure<Clock>([k] {
7146 for (
int i = 0; i < k; ++i) {
7147 volatile auto ignored = Clock::now();
7153 int iters = clock_cost_estimation_iterations;
7154 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7155 std::vector<double> times;
7156 int nsamples =
static_cast<int>(std::ceil(time_limit / r.elapsed));
7157 times.reserve(nsamples);
7158 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7159 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7162 FloatDuration<Clock>(mean(times.begin(), times.end())),
7163 classify_outliers(times.begin(), times.end()),
7167 template <
typename Clock>
7168 Environment<FloatDuration<Clock>> measure_environment() {
7169 static Environment<FloatDuration<Clock>>* env =
nullptr;
7174 auto iters = Detail::warmup<Clock>();
7175 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7176 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7178 env =
new Environment<FloatDuration<Clock>>{ resolution, cost };
7196 #include <algorithm> 7202 namespace Benchmark {
7203 template <
typename Duration>
7204 struct SampleAnalysis {
7205 std::vector<Duration> samples;
7206 Estimate<Duration> mean;
7207 Estimate<Duration> standard_deviation;
7208 OutlierClassification outliers;
7209 double outlier_variance;
7211 template <
typename Duration2>
7212 operator SampleAnalysis<Duration2>()
const {
7213 std::vector<Duration2> samples2;
7214 samples2.reserve(samples.size());
7215 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) {
return Duration2(d); });
7217 std::move(samples2),
7229 #include <algorithm> 7234 namespace Benchmark {
7236 template <
typename Duration,
typename Iterator>
7237 SampleAnalysis<Duration> analyse(
const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7238 if (!cfg.benchmarkNoAnalysis()) {
7239 std::vector<double> samples;
7240 samples.reserve(last - first);
7241 std::transform(first, last, std::back_inserter(samples), [](Duration d) {
return d.count(); });
7243 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7244 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7246 auto wrap_estimate = [](Estimate<double> e) {
7247 return Estimate<Duration> {
7249 Duration(e.lower_bound),
7250 Duration(e.upper_bound),
7251 e.confidence_interval,
7254 std::vector<Duration> samples2;
7255 samples2.reserve(samples.size());
7256 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
double d) {
return Duration(d); });
7258 std::move(samples2),
7259 wrap_estimate(analysis.mean),
7260 wrap_estimate(analysis.standard_deviation),
7262 analysis.outlier_variance,
7265 std::vector<Duration> samples;
7266 samples.reserve(last - first);
7268 Duration mean = Duration(0);
7270 for (
auto it = first; it < last; ++it, ++i) {
7271 samples.push_back(Duration(*it));
7272 mean += Duration(*it);
7278 Estimate<Duration>{mean, mean, mean, 0.0},
7279 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7280 OutlierClassification{},
7290 #include <algorithm> 7291 #include <functional> 7297 namespace Benchmark {
7299 Benchmark(std::string &&name)
7300 : name(std::move(name)) {}
7302 template <
class FUN>
7303 Benchmark(std::string &&name, FUN &&func)
7304 : fun(std::move(func)), name(std::move(name)) {}
7306 template <
typename Clock>
7307 ExecutionPlan<FloatDuration<Clock>> prepare(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
7308 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7309 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7310 auto&&
test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7311 int new_iters =
static_cast<int>(std::ceil(min_time *
test.iterations /
test.elapsed));
7312 return { new_iters,
test.elapsed /
test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7315 template <
typename Clock = default_clock>
7317 IConfigPtr cfg = getCurrentContext().getConfig();
7319 auto env = Detail::measure_environment<Clock>();
7321 getResultCapture().benchmarkPreparing(name);
7323 auto plan = user_code([&] {
7324 return prepare<Clock>(*cfg, env);
7327 BenchmarkInfo info {
7329 plan.estimated_duration.count(),
7330 plan.iterations_per_sample,
7331 cfg->benchmarkSamples(),
7332 cfg->benchmarkResamples(),
7333 env.clock_resolution.mean.count(),
7334 env.clock_cost.mean.count()
7337 getResultCapture().benchmarkStarting(info);
7339 auto samples = user_code([&] {
7340 return plan.template run<Clock>(*cfg, env);
7343 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7344 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7345 getResultCapture().benchmarkEnded(stats);
7348 if (translateActiveException() != Detail::benchmarkErrorMsg)
7349 std::rethrow_exception(std::current_exception());
7354 template <
typename Fun,
7355 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value,
int>::type = 0>
7356 Benchmark & operator=(Fun func) {
7357 fun = Detail::BenchmarkFunction(func);
7362 explicit operator bool() {
7367 Detail::BenchmarkFunction fun;
7373 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1 7374 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2 7376 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\ 7377 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ 7378 BenchmarkName = [&](int benchmarkIndex) 7380 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\ 7381 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \ 7390 #include <type_traits> 7393 namespace Benchmark {
7395 template <
typename T,
bool Destruct>
7396 struct ObjectStorage
7398 using TStorage =
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7400 ObjectStorage() : data() {}
7402 ObjectStorage(
const ObjectStorage& other)
7404 new(&data) T(other.stored_object());
7407 ObjectStorage(ObjectStorage&& other)
7409 new(&data) T(std::move(other.stored_object()));
7412 ~ObjectStorage() { destruct_on_exit<T>(); }
7414 template <
typename... Args>
7415 void construct(Args&&... args)
7417 new (&data) T(std::forward<Args>(args)...);
7420 template <
bool AllowManualDestruction = !Destruct>
7421 typename std::enable_if<AllowManualDestruction>::type destruct()
7423 stored_object().~T();
7428 template <
typename U>
7429 void destruct_on_exit(
typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7431 template <
typename U>
7432 void destruct_on_exit(
typename std::enable_if<!Destruct, U>::type* = 0) { }
7434 T& stored_object() {
7435 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7438 T
const& stored_object()
const {
7439 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7446 template <
typename T>
7447 using storage_for = Detail::ObjectStorage<T, true>;
7449 template <
typename T>
7450 using destructable_object = Detail::ObjectStorage<T, false>;
7458 #endif // ! CATCH_CONFIG_IMPL_ONLY 7464 #pragma clang diagnostic push 7465 #pragma clang diagnostic ignored "-Wweak-vtables" 7476 namespace TestCaseTracking {
7478 struct NameAndLocation {
7482 NameAndLocation( std::string
const& _name,
SourceLineInfo const& _location );
7483 friend bool operator==(NameAndLocation
const& lhs, NameAndLocation
const& rhs) {
7484 return lhs.name == rhs.name
7485 && lhs.location == rhs.location;
7491 using ITrackerPtr = std::shared_ptr<ITracker>;
7494 NameAndLocation m_nameAndLocation;
7497 ITracker(NameAndLocation
const& nameAndLoc) :
7498 m_nameAndLocation(nameAndLoc)
7502 NameAndLocation
const& nameAndLocation()
const {
7503 return m_nameAndLocation;
7506 virtual ~ITracker();
7509 virtual bool isComplete()
const = 0;
7510 virtual bool isSuccessfullyCompleted()
const = 0;
7511 virtual bool isOpen()
const = 0;
7512 virtual bool hasChildren()
const = 0;
7513 virtual bool hasStarted()
const = 0;
7515 virtual ITracker& parent() = 0;
7518 virtual void close() = 0;
7519 virtual void fail() = 0;
7520 virtual void markAsNeedingAnotherRun() = 0;
7522 virtual void addChild( ITrackerPtr
const& child ) = 0;
7523 virtual ITrackerPtr findChild( NameAndLocation
const& nameAndLocation ) = 0;
7524 virtual void openChild() = 0;
7527 virtual bool isSectionTracker()
const = 0;
7528 virtual bool isGeneratorTracker()
const = 0;
7531 class TrackerContext {
7539 ITrackerPtr m_rootTracker;
7540 ITracker* m_currentTracker =
nullptr;
7541 RunState m_runState = NotStarted;
7545 ITracker& startRun();
7549 void completeCycle();
7551 bool completedCycle()
const;
7552 ITracker& currentTracker();
7553 void setCurrentTracker( ITracker* tracker );
7556 class TrackerBase :
public ITracker {
7563 CompletedSuccessfully,
7567 using Children = std::vector<ITrackerPtr>;
7568 TrackerContext& m_ctx;
7570 Children m_children;
7571 CycleState m_runState = NotStarted;
7574 TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7576 bool isComplete()
const override;
7577 bool isSuccessfullyCompleted()
const override;
7578 bool isOpen()
const override;
7579 bool hasChildren()
const override;
7580 bool hasStarted()
const override {
7581 return m_runState != NotStarted;
7584 void addChild( ITrackerPtr
const& child )
override;
7586 ITrackerPtr findChild( NameAndLocation
const& nameAndLocation )
override;
7587 ITracker& parent()
override;
7589 void openChild()
override;
7591 bool isSectionTracker()
const override;
7592 bool isGeneratorTracker()
const override;
7596 void close()
override;
7597 void fail()
override;
7598 void markAsNeedingAnotherRun()
override;
7601 void moveToParent();
7605 class SectionTracker :
public TrackerBase {
7606 std::vector<std::string> m_filters;
7607 std::string m_trimmed_name;
7609 SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7611 bool isSectionTracker()
const override;
7613 bool isComplete()
const override;
7615 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation );
7619 void addInitialFilters( std::vector<std::string>
const& filters );
7620 void addNextFilters( std::vector<std::string>
const& filters );
7622 std::vector<std::string>
const& getFilters()
const;
7624 std::string
const& trimmedName()
const;
7629 using TestCaseTracking::ITracker;
7630 using TestCaseTracking::TrackerContext;
7631 using TestCaseTracking::SectionTracker;
7641 struct LeakDetector {
7653 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 7658 #if defined(CATCH_CONFIG_USE_ASYNC) 7663 double erf_inv(
double x) {
7667 w = -log((1.0 - x) * (1.0 + x));
7671 p = -3.6444120640178196996e-21;
7672 p = -1.685059138182016589e-19 + p * w;
7673 p = 1.2858480715256400167e-18 + p * w;
7674 p = 1.115787767802518096e-17 + p * w;
7675 p = -1.333171662854620906e-16 + p * w;
7676 p = 2.0972767875968561637e-17 + p * w;
7677 p = 6.6376381343583238325e-15 + p * w;
7678 p = -4.0545662729752068639e-14 + p * w;
7679 p = -8.1519341976054721522e-14 + p * w;
7680 p = 2.6335093153082322977e-12 + p * w;
7681 p = -1.2975133253453532498e-11 + p * w;
7682 p = -5.4154120542946279317e-11 + p * w;
7683 p = 1.051212273321532285e-09 + p * w;
7684 p = -4.1126339803469836976e-09 + p * w;
7685 p = -2.9070369957882005086e-08 + p * w;
7686 p = 4.2347877827932403518e-07 + p * w;
7687 p = -1.3654692000834678645e-06 + p * w;
7688 p = -1.3882523362786468719e-05 + p * w;
7689 p = 0.0001867342080340571352 + p * w;
7690 p = -0.00074070253416626697512 + p * w;
7691 p = -0.0060336708714301490533 + p * w;
7692 p = 0.24015818242558961693 + p * w;
7693 p = 1.6536545626831027356 + p * w;
7694 }
else if (w < 16.000000) {
7695 w = sqrt(w) - 3.250000;
7696 p = 2.2137376921775787049e-09;
7697 p = 9.0756561938885390979e-08 + p * w;
7698 p = -2.7517406297064545428e-07 + p * w;
7699 p = 1.8239629214389227755e-08 + p * w;
7700 p = 1.5027403968909827627e-06 + p * w;
7701 p = -4.013867526981545969e-06 + p * w;
7702 p = 2.9234449089955446044e-06 + p * w;
7703 p = 1.2475304481671778723e-05 + p * w;
7704 p = -4.7318229009055733981e-05 + p * w;
7705 p = 6.8284851459573175448e-05 + p * w;
7706 p = 2.4031110387097893999e-05 + p * w;
7707 p = -0.0003550375203628474796 + p * w;
7708 p = 0.00095328937973738049703 + p * w;
7709 p = -0.0016882755560235047313 + p * w;
7710 p = 0.0024914420961078508066 + p * w;
7711 p = -0.0037512085075692412107 + p * w;
7712 p = 0.005370914553590063617 + p * w;
7713 p = 1.0052589676941592334 + p * w;
7714 p = 3.0838856104922207635 + p * w;
7716 w = sqrt(w) - 5.000000;
7717 p = -2.7109920616438573243e-11;
7718 p = -2.5556418169965252055e-10 + p * w;
7719 p = 1.5076572693500548083e-09 + p * w;
7720 p = -3.7894654401267369937e-09 + p * w;
7721 p = 7.6157012080783393804e-09 + p * w;
7722 p = -1.4960026627149240478e-08 + p * w;
7723 p = 2.9147953450901080826e-08 + p * w;
7724 p = -6.7711997758452339498e-08 + p * w;
7725 p = 2.2900482228026654717e-07 + p * w;
7726 p = -9.9298272942317002539e-07 + p * w;
7727 p = 4.5260625972231537039e-06 + p * w;
7728 p = -1.9681778105531670567e-05 + p * w;
7729 p = 7.5995277030017761139e-05 + p * w;
7730 p = -0.00021503011930044477347 + p * w;
7731 p = -0.00013871931833623122026 + p * w;
7732 p = 1.0103004648645343977 + p * w;
7733 p = 4.8499064014085844221 + p * w;
7738 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7739 auto m = Catch::Benchmark::Detail::mean(first, last);
7740 double variance = std::accumulate(first, last, 0., [m](
double a,
double b) {
7741 double diff = b - m;
7742 return a + diff * diff;
7743 }) / (last - first);
7744 return std::sqrt(variance);
7750 namespace Benchmark {
7753 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7754 auto count = last - first;
7755 double idx = (count - 1) * k / static_cast<double>(q);
7756 int j =
static_cast<int>(idx);
7758 std::nth_element(first, first + j, last);
7760 if (g == 0)
return xj;
7762 auto xj1 = *std::min_element(first + (j + 1), last);
7763 return xj + g * (xj1 - xj);
7766 double erfc_inv(
double x) {
7767 return erf_inv(1.0 - x);
7770 double normal_quantile(
double p) {
7771 static const double ROOT_TWO = std::sqrt(2.0);
7773 double result = 0.0;
7774 assert(p >= 0 && p <= 1);
7775 if (p < 0 || p > 1) {
7779 result = -erfc_inv(2.0 * p);
7786 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7787 double sb = stddev.point;
7788 double mn = mean.point / n;
7789 double mg_min = mn / 2.;
7790 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7791 double sg2 = sg * sg;
7792 double sb2 = sb * sb;
7794 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7798 double k0 = -n * nd;
7799 double k1 = sb2 - n * sg2 + nd;
7800 double det = k1 * k1 - 4 * sg2 * k0;
7801 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7804 auto var_out = [n, sb2, sg2](
double c) {
7806 return (nc / n) * (sb2 - nc * sg2);
7809 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7812 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7813 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7814 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7815 static std::random_device entropy;
7816 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7818 auto n =
static_cast<int>(last - first);
7820 auto mean = &Detail::mean<std::vector<double>::iterator>;
7821 auto stddev = &standard_deviation;
7823 #if defined(CATCH_CONFIG_USE_ASYNC) 7824 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7825 auto seed = entropy();
7826 return std::async(std::launch::async, [=] {
7827 std::mt19937 rng(seed);
7828 auto resampled = resample(rng, n_resamples, first, last, f);
7829 return bootstrap(confidence_level, first, last, resampled, f);
7833 auto mean_future = Estimate(mean);
7834 auto stddev_future = Estimate(stddev);
7836 auto mean_estimate = mean_future.get();
7837 auto stddev_estimate = stddev_future.get();
7839 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7840 auto seed = entropy();
7841 std::mt19937 rng(seed);
7842 auto resampled = resample(rng, n_resamples, first, last, f);
7843 return bootstrap(confidence_level, first, last, resampled, f);
7846 auto mean_estimate = Estimate(mean);
7847 auto stddev_estimate = Estimate(stddev);
7848 #endif // CATCH_USE_ASYNC 7850 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7852 return { mean_estimate, stddev_estimate, outlier_variance };
7858 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 7869 bool marginComparison(
double lhs,
double rhs,
double margin) {
7870 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7878 Approx::Approx (
double value )
7879 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7885 Approx Approx::custom() {
7889 Approx Approx::operator-()
const {
7891 temp.m_value = -temp.m_value;
7895 std::string Approx::toString()
const {
7897 rss <<
"Approx( " << ::Catch::Detail::stringify( m_value ) <<
" )";
7901 bool Approx::equalityComparisonImpl(
const double other)
const {
7904 return marginComparison(m_value, other, m_margin)
7905 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7908 void Approx::setMargin(
double newMargin) {
7909 CATCH_ENFORCE(newMargin >= 0,
7910 "Invalid Approx::margin: " << newMargin <<
'.' 7911 <<
" Approx::Margin has to be non-negative.");
7912 m_margin = newMargin;
7915 void Approx::setEpsilon(
double newEpsilon) {
7916 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7917 "Invalid Approx::epsilon: " << newEpsilon <<
'.' 7918 <<
" Approx::epsilon has to be in [0, 1]");
7919 m_epsilon = newEpsilon;
7924 namespace literals {
7934 return value.toString();
7944 bool isDebuggerActive();
7947 #ifdef CATCH_PLATFORM_MAC 7949 #if defined(__i386__) || defined(__x86_64__) 7950 #define CATCH_TRAP() __asm__("int $3\n" : : ) 7951 #elif defined(__aarch64__) 7952 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7955 #elif defined(CATCH_PLATFORM_IPHONE) 7958 #if defined(__i386__) || defined(__x86_64__) 7959 #define CATCH_TRAP() __asm__("int $3") 7960 #elif defined(__aarch64__) 7961 #define CATCH_TRAP() __asm__(".inst 0xd4200000") 7962 #elif defined(__arm__) && !defined(__thumb__) 7963 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0") 7964 #elif defined(__arm__) && defined(__thumb__) 7965 #define CATCH_TRAP() __asm__(".inst 0xde01") 7968 #elif defined(CATCH_PLATFORM_LINUX) 7972 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) 7973 #define CATCH_TRAP() asm volatile ("int $3") 7974 #else // Fall back to the generic way. 7977 #define CATCH_TRAP() raise(SIGTRAP) 7979 #elif defined(_MSC_VER) 7980 #define CATCH_TRAP() __debugbreak() 7981 #elif defined(__MINGW32__) 7982 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7983 #define CATCH_TRAP() DebugBreak() 7986 #ifndef CATCH_BREAK_INTO_DEBUGGER 7988 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() 7990 #define CATCH_BREAK_INTO_DEBUGGER() []{}() 8011 class FatalConditionHandler {
8012 bool m_started =
false;
8017 void engage_platform();
8018 void disengage_platform();
8021 FatalConditionHandler();
8022 ~FatalConditionHandler();
8025 assert(!m_started &&
"Handler cannot be installed twice.");
8031 assert(m_started &&
"Handler cannot be uninstalled without being installed first");
8033 disengage_platform();
8038 class FatalConditionHandlerGuard {
8039 FatalConditionHandler* m_handler;
8041 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8042 m_handler(handler) {
8043 m_handler->engage();
8045 ~FatalConditionHandlerGuard() {
8046 m_handler->disengage();
8064 RunContext( RunContext
const& ) =
delete;
8065 RunContext& operator =( RunContext
const& ) =
delete;
8067 explicit RunContext( IConfigPtr
const& _config, IStreamingReporterPtr&& reporter );
8069 ~RunContext()
override;
8071 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8072 void testGroupEnded( std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8076 IConfigPtr config()
const;
8077 IStreamingReporter& reporter()
const;
8088 ResultWas::OfType resultType,
8091 void handleUnexpectedExceptionNotThrown
8094 void handleUnexpectedInflightException
8096 std::string
const& message,
8098 void handleIncomplete
8102 ResultWas::OfType resultType,
8105 bool sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions )
override;
8108 void sectionEndedEarly(
SectionEndInfo const& endInfo )
override;
8112 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 8113 void benchmarkPreparing( std::string
const& name )
override;
8114 void benchmarkStarting( BenchmarkInfo
const& info )
override;
8115 void benchmarkEnded( BenchmarkStats<>
const& stats )
override;
8116 void benchmarkFailed( std::string
const& error )
override;
8117 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 8119 void pushScopedMessage(
MessageInfo const& message )
override;
8120 void popScopedMessage(
MessageInfo const& message )
override;
8122 void emplaceUnscopedMessage(
MessageBuilder const& builder )
override;
8124 std::string getCurrentTestName()
const override;
8126 const AssertionResult* getLastResult()
const override;
8128 void exceptionEarlyReported()
override;
8130 void handleFatalErrorCondition(
StringRef message )
override;
8132 bool lastAssertionPassed()
override;
8134 void assertionPassed()
override;
8138 bool aborting()
const final;
8142 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8143 void invokeActiveTestCase();
8145 void resetAssertionInfo();
8146 bool testForMissingAssertions(
Counts& assertions );
8148 void assertionEnded( AssertionResult
const& result );
8151 ResultWas::OfType resultType,
8159 void handleUnfinishedSections();
8161 TestRunInfo m_runInfo;
8163 TestCase const* m_activeTestCase =
nullptr;
8164 ITracker* m_testCaseTracker =
nullptr;
8167 IConfigPtr m_config;
8169 IStreamingReporterPtr m_reporter;
8170 std::vector<MessageInfo> m_messages;
8171 std::vector<ScopedMessage> m_messageScopes;
8173 std::vector<SectionEndInfo> m_unfinishedSections;
8174 std::vector<ITracker*> m_activeSections;
8175 TrackerContext m_trackerContext;
8176 FatalConditionHandler m_fatalConditionhandler;
8177 bool m_lastAssertionPassed =
false;
8178 bool m_shouldReportUnexpected =
true;
8179 bool m_includeSuccessfulResults;
8182 void seedRng(
IConfig const& config);
8183 unsigned int rngSeed();
8191 expr.streamReconstructedExpression( os );
8196 LazyExpression::LazyExpression(
bool isNegated )
8197 : m_isNegated( isNegated )
8200 LazyExpression::LazyExpression(
LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
8202 LazyExpression::operator bool()
const {
8203 return m_transientExpression !=
nullptr;
8206 auto operator << ( std::ostream& os,
LazyExpression const& lazyExpr ) -> std::ostream& {
8207 if( lazyExpr.m_isNegated )
8211 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8212 os <<
"(" << *lazyExpr.m_transientExpression <<
")";
8214 os << *lazyExpr.m_transientExpression;
8217 os <<
"{** error - unchecked empty expression requested **}";
8222 AssertionHandler::AssertionHandler
8226 ResultDisposition::Flags resultDisposition )
8227 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8228 m_resultCapture( getResultCapture() )
8232 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8234 void AssertionHandler::handleMessage(ResultWas::OfType resultType,
StringRef const& message) {
8235 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8238 auto AssertionHandler::allowThrows()
const ->
bool {
8239 return getCurrentContext().getConfig()->allowThrows();
8242 void AssertionHandler::complete() {
8244 if( m_reaction.shouldDebugBreak ) {
8250 CATCH_BREAK_INTO_DEBUGGER();
8252 if (m_reaction.shouldThrow) {
8253 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 8256 CATCH_ERROR(
"Test failure requires aborting test!" );
8260 void AssertionHandler::setCompleted() {
8264 void AssertionHandler::handleUnexpectedInflightException() {
8265 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8268 void AssertionHandler::handleExceptionThrownAsExpected() {
8269 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8271 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8272 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8275 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8276 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8279 void AssertionHandler::handleThrowingCallSkipped() {
8280 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8286 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8294 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType,
LazyExpression const & _lazyExpression):
8295 lazyExpression(_lazyExpression),
8296 resultType(_resultType) {}
8298 std::string AssertionResultData::reconstructExpression()
const {
8300 if( reconstructedExpression.empty() ) {
8301 if( lazyExpression ) {
8303 rss << lazyExpression;
8304 reconstructedExpression = rss.str();
8307 return reconstructedExpression;
8310 AssertionResult::AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data )
8312 m_resultData( data )
8316 bool AssertionResult::succeeded()
const {
8317 return Catch::isOk( m_resultData.resultType );
8321 bool AssertionResult::isOk()
const {
8322 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8325 ResultWas::OfType AssertionResult::getResultType()
const {
8326 return m_resultData.resultType;
8329 bool AssertionResult::hasExpression()
const {
8330 return !m_info.capturedExpression.empty();
8333 bool AssertionResult::hasMessage()
const {
8334 return !m_resultData.message.empty();
8337 std::string AssertionResult::getExpression()
const {
8339 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8340 if (isFalseTest(m_info.resultDisposition)) {
8343 expr += m_info.capturedExpression;
8344 if (isFalseTest(m_info.resultDisposition)) {
8350 std::string AssertionResult::getExpressionInMacro()
const {
8352 if( m_info.macroName.empty() )
8353 expr = static_cast<std::string>(m_info.capturedExpression);
8355 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8356 expr += m_info.macroName;
8358 expr += m_info.capturedExpression;
8364 bool AssertionResult::hasExpandedExpression()
const {
8365 return hasExpression() && getExpandedExpression() != getExpression();
8368 std::string AssertionResult::getExpandedExpression()
const {
8369 std::string expr = m_resultData.reconstructExpression();
8375 std::string AssertionResult::getMessage()
const {
8376 return m_resultData.message;
8379 return m_info.lineInfo;
8382 StringRef AssertionResult::getTestMacroName()
const {
8383 return m_info.macroName;
8398 std::string exceptionMessage = Catch::translateActiveException();
8400 handler.handleExpr( expr );
8412 #ifdef CLARA_CONFIG_CONSOLE_WIDTH 8413 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8414 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8416 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 8419 #pragma clang diagnostic push 8420 #pragma clang diagnostic ignored "-Wweak-vtables" 8421 #pragma clang diagnostic ignored "-Wexit-time-destructors" 8422 #pragma clang diagnostic ignored "-Wshadow" 8436 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8437 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 8440 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8441 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH 8444 #ifndef CLARA_CONFIG_OPTIONAL_TYPE 8445 #ifdef __has_include 8446 #if __has_include(<optional>) && __cplusplus >= 201703L 8448 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional 8470 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 8471 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 8476 namespace TextFlow {
8478 inline auto isWhitespace(
char c) ->
bool {
8479 static std::string chars =
" \t\n\r";
8480 return chars.find(c) != std::string::npos;
8482 inline auto isBreakableBefore(
char c) ->
bool {
8483 static std::string chars =
"[({<|";
8484 return chars.find(c) != std::string::npos;
8486 inline auto isBreakableAfter(
char c) ->
bool {
8487 static std::string chars =
"])}>.,:;*+-=&/\\";
8488 return chars.find(c) != std::string::npos;
8494 std::vector<std::string> m_strings;
8495 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8496 size_t m_indent = 0;
8497 size_t m_initialIndent = std::string::npos;
8503 Column
const& m_column;
8504 size_t m_stringIndex = 0;
8509 bool m_suffix =
false;
8511 iterator(Column
const& column,
size_t stringIndex)
8513 m_stringIndex(stringIndex) {}
8515 auto line()
const -> std::string
const& {
return m_column.m_strings[m_stringIndex]; }
8517 auto isBoundary(
size_t at)
const ->
bool {
8519 assert(at <= line().size());
8521 return at == line().size() ||
8522 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8523 isBreakableBefore(line()[at]) ||
8524 isBreakableAfter(line()[at - 1]);
8528 assert(m_stringIndex < m_column.m_strings.size());
8531 auto width = m_column.m_width - indent();
8533 if (line()[m_pos] ==
'\n') {
8536 while (m_end < line().size() && line()[m_end] !=
'\n')
8539 if (m_end < m_pos + width) {
8540 m_len = m_end - m_pos;
8543 while (len > 0 && !isBoundary(m_pos + len))
8545 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8557 auto indent()
const ->
size_t {
8558 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8559 return initial == std::string::npos ? m_column.m_indent : initial;
8562 auto addIndentAndSuffix(std::string
const &plain)
const -> std::string {
8563 return std::string(indent(),
' ') + (m_suffix ? plain +
"-" : plain);
8567 using difference_type = std::ptrdiff_t;
8568 using value_type = std::string;
8569 using pointer = value_type * ;
8570 using reference = value_type & ;
8571 using iterator_category = std::forward_iterator_tag;
8573 explicit iterator(Column
const& column) : m_column(column) {
8574 assert(m_column.m_width > m_column.m_indent);
8575 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8581 auto operator *()
const -> std::string {
8582 assert(m_stringIndex < m_column.m_strings.size());
8583 assert(m_pos <= m_end);
8584 return addIndentAndSuffix(line().substr(m_pos, m_len));
8587 auto operator ++() -> iterator& {
8589 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8592 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8595 if (m_pos == line().size()) {
8599 if (m_stringIndex < m_column.m_strings.size())
8603 auto operator ++(
int) -> iterator {
8604 iterator prev(*
this);
8609 auto operator ==(iterator
const& other)
const ->
bool {
8611 m_pos == other.m_pos &&
8612 m_stringIndex == other.m_stringIndex &&
8613 &m_column == &other.m_column;
8615 auto operator !=(iterator
const& other)
const ->
bool {
8616 return !operator==(other);
8619 using const_iterator = iterator;
8621 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8623 auto width(
size_t newWidth) -> Column& {
8624 assert(newWidth > 0);
8628 auto indent(
size_t newIndent) -> Column& {
8629 m_indent = newIndent;
8632 auto initialIndent(
size_t newIndent) -> Column& {
8633 m_initialIndent = newIndent;
8637 auto width()
const ->
size_t {
return m_width; }
8638 auto begin()
const -> iterator {
return iterator(*
this); }
8639 auto end()
const -> iterator {
return { *
this, m_strings.size() }; }
8641 inline friend std::ostream& operator << (std::ostream& os, Column
const& col) {
8643 for (
auto line : col) {
8653 auto operator + (Column
const& other)->Columns;
8655 auto toString()
const -> std::string {
8656 std::ostringstream oss;
8662 class Spacer :
public Column {
8665 explicit Spacer(
size_t spaceWidth) : Column(
"") {
8671 std::vector<Column> m_columns;
8679 std::vector<Column>
const& m_columns;
8680 std::vector<Column::iterator> m_iterators;
8681 size_t m_activeIterators;
8683 iterator(Columns
const& columns, EndTag)
8684 : m_columns(columns.m_columns),
8685 m_activeIterators(0) {
8686 m_iterators.reserve(m_columns.size());
8688 for (
auto const& col : m_columns)
8689 m_iterators.push_back(col.end());
8693 using difference_type = std::ptrdiff_t;
8694 using value_type = std::string;
8695 using pointer = value_type * ;
8696 using reference = value_type & ;
8697 using iterator_category = std::forward_iterator_tag;
8699 explicit iterator(Columns
const& columns)
8700 : m_columns(columns.m_columns),
8701 m_activeIterators(m_columns.size()) {
8702 m_iterators.reserve(m_columns.size());
8704 for (
auto const& col : m_columns)
8705 m_iterators.push_back(col.begin());
8708 auto operator ==(iterator
const& other)
const ->
bool {
8709 return m_iterators == other.m_iterators;
8711 auto operator !=(iterator
const& other)
const ->
bool {
8712 return m_iterators != other.m_iterators;
8714 auto operator *()
const -> std::string {
8715 std::string row, padding;
8717 for (
size_t i = 0; i < m_columns.size(); ++i) {
8718 auto width = m_columns[i].width();
8719 if (m_iterators[i] != m_columns[i].end()) {
8720 std::string col = *m_iterators[i];
8721 row += padding + col;
8722 if (col.size() < width)
8723 padding = std::string(width - col.size(),
' ');
8727 padding += std::string(width,
' ');
8732 auto operator ++() -> iterator& {
8733 for (
size_t i = 0; i < m_columns.size(); ++i) {
8734 if (m_iterators[i] != m_columns[i].end())
8739 auto operator ++(
int) -> iterator {
8740 iterator prev(*
this);
8745 using const_iterator = iterator;
8747 auto begin()
const -> iterator {
return iterator(*
this); }
8748 auto end()
const -> iterator {
return { *
this, iterator::EndTag() }; }
8750 auto operator += (Column
const& col) -> Columns& {
8751 m_columns.push_back(col);
8754 auto operator + (Column
const& col) -> Columns {
8755 Columns combined = *
this;
8760 inline friend std::ostream& operator << (std::ostream& os, Columns
const& cols) {
8763 for (
auto line : cols) {
8773 auto toString()
const -> std::string {
8774 std::ostringstream oss;
8780 inline auto Column::operator + (Column
const& other) -> Columns {
8798 #include <algorithm> 8800 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) 8801 #define CATCH_PLATFORM_WINDOWS 8804 namespace Catch {
namespace clara {
8808 template<
typename L>
8809 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8811 template<
typename ClassT,
typename ReturnT,
typename... Args>
8812 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8813 static const bool isValid =
false;
8816 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8817 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8818 static const bool isValid =
true;
8819 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8820 using ReturnType = ReturnT;
8828 std::string m_exeName;
8829 std::vector<std::string> m_args;
8832 Args(
int argc,
char const*
const* argv )
8833 : m_exeName(argv[0]),
8834 m_args(argv + 1, argv + argc) {}
8836 Args( std::initializer_list<std::string> args )
8837 : m_exeName( *args.begin() ),
8838 m_args( args.begin()+1, args.end() )
8841 auto exeName()
const -> std::string {
8848 enum class TokenType {
8856 inline auto isOptPrefix(
char c ) ->
bool {
8858 #ifdef CATCH_PLATFORM_WINDOWS 8866 using Iterator = std::vector<std::string>::const_iterator;
8869 std::vector<Token> m_tokenBuffer;
8872 m_tokenBuffer.resize( 0 );
8875 while( it != itEnd && it->empty() )
8879 auto const &next = *it;
8880 if( isOptPrefix( next[0] ) ) {
8881 auto delimiterPos = next.find_first_of(
" :=" );
8882 if( delimiterPos != std::string::npos ) {
8883 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8884 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8886 if( next[1] !=
'-' && next.size() > 2 ) {
8887 std::string opt =
"- ";
8888 for(
size_t i = 1; i < next.size(); ++i ) {
8890 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8893 m_tokenBuffer.push_back( { TokenType::Option, next } );
8897 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8903 explicit TokenStream( Args
const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8905 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8909 explicit operator bool()
const {
8910 return !m_tokenBuffer.empty() || it != itEnd;
8913 auto count()
const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8915 auto operator*()
const -> Token {
8916 assert( !m_tokenBuffer.empty() );
8917 return m_tokenBuffer.front();
8920 auto operator->()
const -> Token
const * {
8921 assert( !m_tokenBuffer.empty() );
8922 return &m_tokenBuffer.front();
8925 auto operator++() -> TokenStream & {
8926 if( m_tokenBuffer.size() >= 2 ) {
8927 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8940 Ok, LogicError, RuntimeError
8944 ResultBase( Type type ) : m_type( type ) {}
8945 virtual ~ResultBase() =
default;
8947 virtual void enforceOk()
const = 0;
8952 template<
typename T>
8953 class ResultValueBase :
public ResultBase {
8955 auto value()
const -> T
const & {
8961 ResultValueBase( Type type ) : ResultBase( type ) {}
8963 ResultValueBase( ResultValueBase
const &other ) : ResultBase( other ) {
8964 if( m_type == ResultBase::Ok )
8965 new( &m_value ) T( other.m_value );
8968 ResultValueBase( Type, T
const &value ) : ResultBase( Ok ) {
8969 new( &m_value ) T( value );
8972 auto operator=( ResultValueBase
const &other ) -> ResultValueBase & {
8973 if( m_type == ResultBase::Ok )
8975 ResultBase::operator=(other);
8976 if( m_type == ResultBase::Ok )
8977 new( &m_value ) T( other.m_value );
8981 ~ResultValueBase()
override {
8992 class ResultValueBase<void> :
public ResultBase {
8994 using ResultBase::ResultBase;
8997 template<
typename T =
void>
8998 class BasicResult :
public ResultValueBase<T> {
9000 template<
typename U>
9001 explicit BasicResult( BasicResult<U>
const &other )
9002 : ResultValueBase<T>( other.type() ),
9003 m_errorMessage( other.errorMessage() )
9005 assert( type() != ResultBase::Ok );
9008 template<
typename U>
9009 static auto ok( U
const &value ) -> BasicResult {
return { ResultBase::Ok, value }; }
9010 static auto ok() -> BasicResult {
return { ResultBase::Ok }; }
9011 static auto logicError( std::string
const &message ) -> BasicResult {
return { ResultBase::LogicError, message }; }
9012 static auto runtimeError( std::string
const &message ) -> BasicResult {
return { ResultBase::RuntimeError, message }; }
9014 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9015 auto type()
const -> ResultBase::Type {
return m_type; }
9016 auto errorMessage()
const -> std::string {
return m_errorMessage; }
9019 void enforceOk()
const override {
9023 assert( m_type != ResultBase::LogicError );
9024 assert( m_type != ResultBase::RuntimeError );
9025 if( m_type != ResultBase::Ok )
9029 std::string m_errorMessage;
9031 BasicResult( ResultBase::Type type, std::string
const &message )
9032 : ResultValueBase<T>(type),
9033 m_errorMessage(message)
9035 assert( m_type != ResultBase::Ok );
9038 using ResultValueBase<T>::ResultValueBase;
9039 using ResultBase::m_type;
9042 enum class ParseResultType {
9043 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9049 ParseState( ParseResultType type, TokenStream
const &remainingTokens )
9051 m_remainingTokens( remainingTokens )
9054 auto type()
const -> ParseResultType {
return m_type; }
9055 auto remainingTokens()
const -> TokenStream {
return m_remainingTokens; }
9058 ParseResultType m_type;
9059 TokenStream m_remainingTokens;
9062 using Result = BasicResult<void>;
9063 using ParserResult = BasicResult<ParseResultType>;
9064 using InternalParseResult = BasicResult<ParseState>;
9066 struct HelpColumns {
9071 template<
typename T>
9072 inline auto convertInto( std::string
const &source, T& target ) -> ParserResult {
9073 std::stringstream ss;
9077 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9079 return ParserResult::ok( ParseResultType::Matched );
9081 inline auto convertInto( std::string
const &source, std::string& target ) -> ParserResult {
9083 return ParserResult::ok( ParseResultType::Matched );
9085 inline auto convertInto( std::string
const &source,
bool &target ) -> ParserResult {
9086 std::string srcLC = source;
9087 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
unsigned char c ) {
return static_cast<char>( std::tolower(c) ); } );
9088 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9090 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9093 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9094 return ParserResult::ok( ParseResultType::Matched );
9096 #ifdef CLARA_CONFIG_OPTIONAL_TYPE 9097 template<
typename T>
9098 inline auto convertInto( std::string
const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9100 auto result = convertInto( source, temp );
9102 target = std::move(temp);
9105 #endif // CLARA_CONFIG_OPTIONAL_TYPE 9116 virtual ~BoundRef() =
default;
9117 virtual auto isContainer()
const ->
bool {
return false; }
9118 virtual auto isFlag()
const ->
bool {
return false; }
9120 struct BoundValueRefBase : BoundRef {
9121 virtual auto setValue( std::string
const &arg ) -> ParserResult = 0;
9123 struct BoundFlagRefBase : BoundRef {
9124 virtual auto setFlag(
bool flag ) -> ParserResult = 0;
9125 virtual auto isFlag()
const ->
bool {
return true; }
9128 template<
typename T>
9129 struct BoundValueRef : BoundValueRefBase {
9132 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9134 auto setValue( std::string
const &arg ) -> ParserResult
override {
9135 return convertInto( arg, m_ref );
9139 template<
typename T>
9140 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9141 std::vector<T> &m_ref;
9143 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9145 auto isContainer()
const ->
bool override {
return true; }
9147 auto setValue( std::string
const &arg ) -> ParserResult
override {
9149 auto result = convertInto( arg, temp );
9151 m_ref.push_back( temp );
9156 struct BoundFlagRef : BoundFlagRefBase {
9159 explicit BoundFlagRef(
bool &ref ) : m_ref( ref ) {}
9161 auto setFlag(
bool flag ) -> ParserResult
override {
9163 return ParserResult::ok( ParseResultType::Matched );
9167 template<
typename ReturnType>
9168 struct LambdaInvoker {
9169 static_assert( std::is_same<ReturnType, ParserResult>::value,
"Lambda must return void or clara::ParserResult" );
9171 template<
typename L,
typename ArgType>
9172 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9173 return lambda( arg );
9178 struct LambdaInvoker<void> {
9179 template<
typename L,
typename ArgType>
9180 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9182 return ParserResult::ok( ParseResultType::Matched );
9186 template<
typename ArgType,
typename L>
9187 inline auto invokeLambda( L
const &lambda, std::string
const &arg ) -> ParserResult {
9189 auto result = convertInto( arg, temp );
9192 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9195 template<
typename L>
9196 struct BoundLambda : BoundValueRefBase {
9199 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9200 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9202 auto setValue( std::string
const &arg ) -> ParserResult
override {
9203 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9207 template<
typename L>
9208 struct BoundFlagLambda : BoundFlagRefBase {
9211 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9212 static_assert( std::is_same<
typename UnaryLambdaTraits<L>::ArgType,
bool>::value,
"flags must be boolean" );
9214 explicit BoundFlagLambda( L
const &lambda ) : m_lambda( lambda ) {}
9216 auto setFlag(
bool flag ) -> ParserResult
override {
9217 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9221 enum class Optionality { Optional, Required };
9227 virtual ~ParserBase() =
default;
9228 virtual auto validate()
const -> Result {
return Result::ok(); }
9229 virtual auto parse( std::string
const& exeName, TokenStream
const &tokens)
const -> InternalParseResult = 0;
9230 virtual auto cardinality()
const ->
size_t {
return 1; }
9232 auto parse( Args
const &args )
const -> InternalParseResult {
9233 return parse( args.exeName(), TokenStream( args ) );
9237 template<
typename DerivedT>
9238 class ComposableParserImpl :
public ParserBase {
9240 template<
typename T>
9241 auto operator|( T
const &other )
const -> Parser;
9243 template<
typename T>
9244 auto operator+( T
const &other )
const -> Parser;
9248 template<
typename DerivedT>
9249 class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9251 Optionality m_optionality = Optionality::Optional;
9252 std::shared_ptr<BoundRef> m_ref;
9254 std::string m_description;
9256 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &ref ) : m_ref( ref ) {}
9259 template<
typename T>
9260 ParserRefImpl( T &ref, std::string
const &hint )
9261 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9265 template<
typename LambdaT>
9266 ParserRefImpl( LambdaT
const &ref, std::string
const &hint )
9267 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9271 auto operator()( std::string
const &description ) -> DerivedT & {
9272 m_description = description;
9273 return static_cast<DerivedT &
>( *this );
9276 auto optional() -> DerivedT & {
9277 m_optionality = Optionality::Optional;
9278 return static_cast<DerivedT &
>( *this );
9281 auto required() -> DerivedT & {
9282 m_optionality = Optionality::Required;
9283 return static_cast<DerivedT &
>( *this );
9286 auto isOptional()
const ->
bool {
9287 return m_optionality == Optionality::Optional;
9290 auto cardinality()
const ->
size_t override {
9291 if( m_ref->isContainer() )
9297 auto hint()
const -> std::string {
return m_hint; }
9300 class ExeName :
public ComposableParserImpl<ExeName> {
9301 std::shared_ptr<std::string> m_name;
9302 std::shared_ptr<BoundValueRefBase> m_ref;
9304 template<
typename LambdaT>
9305 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9306 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9310 ExeName() : m_name( std::make_shared<std::string>(
"<executable>" ) ) {}
9312 explicit ExeName( std::string &ref ) : ExeName() {
9313 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9316 template<
typename LambdaT>
9317 explicit ExeName( LambdaT
const& lambda ) : ExeName() {
9318 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9322 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9323 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9326 auto name()
const -> std::string {
return *m_name; }
9327 auto set( std::string
const& newName ) -> ParserResult {
9329 auto lastSlash = newName.find_last_of(
"\\/" );
9330 auto filename = ( lastSlash == std::string::npos )
9332 : newName.substr( lastSlash+1 );
9336 return m_ref->setValue( filename );
9338 return ParserResult::ok( ParseResultType::Matched );
9342 class Arg :
public ParserRefImpl<Arg> {
9344 using ParserRefImpl::ParserRefImpl;
9346 auto parse( std::string
const &, TokenStream
const &tokens )
const -> InternalParseResult
override {
9347 auto validationResult = validate();
9348 if( !validationResult )
9349 return InternalParseResult( validationResult );
9351 auto remainingTokens = tokens;
9352 auto const &token = *remainingTokens;
9353 if( token.type != TokenType::Argument )
9354 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9356 assert( !m_ref->isFlag() );
9357 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9359 auto result = valueRef->setValue( remainingTokens->token );
9361 return InternalParseResult( result );
9363 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9367 inline auto normaliseOpt( std::string
const &optName ) -> std::string {
9368 #ifdef CATCH_PLATFORM_WINDOWS 9369 if( optName[0] ==
'/' )
9370 return "-" + optName.substr( 1 );
9376 class Opt :
public ParserRefImpl<Opt> {
9378 std::vector<std::string> m_optNames;
9381 template<
typename LambdaT>
9382 explicit Opt( LambdaT
const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9384 explicit Opt(
bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9386 template<
typename LambdaT>
9387 Opt( LambdaT
const &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9389 template<
typename T>
9390 Opt( T &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9392 auto operator[]( std::string
const &optName ) -> Opt & {
9393 m_optNames.push_back( optName );
9397 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9398 std::ostringstream oss;
9400 for(
auto const &opt : m_optNames ) {
9407 if( !m_hint.empty() )
9408 oss <<
" <" << m_hint <<
">";
9409 return { { oss.str(), m_description } };
9412 auto isMatch( std::string
const &optToken )
const ->
bool {
9413 auto normalisedToken = normaliseOpt( optToken );
9414 for(
auto const &name : m_optNames ) {
9415 if( normaliseOpt( name ) == normalisedToken )
9421 using ParserBase::parse;
9423 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9424 auto validationResult = validate();
9425 if( !validationResult )
9426 return InternalParseResult( validationResult );
9428 auto remainingTokens = tokens;
9429 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9430 auto const &token = *remainingTokens;
9431 if( isMatch(token.token ) ) {
9432 if( m_ref->isFlag() ) {
9433 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>( m_ref.get() );
9434 auto result = flagRef->setFlag(
true );
9436 return InternalParseResult( result );
9437 if( result.value() == ParseResultType::ShortCircuitAll )
9438 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9440 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9442 if( !remainingTokens )
9443 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9444 auto const &argToken = *remainingTokens;
9445 if( argToken.type != TokenType::Argument )
9446 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9447 auto result = valueRef->setValue( argToken.token );
9449 return InternalParseResult( result );
9450 if( result.value() == ParseResultType::ShortCircuitAll )
9451 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9453 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9456 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9459 auto validate()
const -> Result
override {
9460 if( m_optNames.empty() )
9461 return Result::logicError(
"No options supplied to Opt" );
9462 for(
auto const &name : m_optNames ) {
9464 return Result::logicError(
"Option name cannot be empty" );
9465 #ifdef CATCH_PLATFORM_WINDOWS 9466 if( name[0] !=
'-' && name[0] !=
'/' )
9467 return Result::logicError(
"Option name must begin with '-' or '/'" );
9469 if( name[0] !=
'-' )
9470 return Result::logicError(
"Option name must begin with '-'" );
9473 return ParserRefImpl::validate();
9478 Help(
bool &showHelpFlag )
9479 : Opt([&](
bool flag ) {
9480 showHelpFlag = flag;
9481 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9484 static_cast<Opt &
>( *this )
9485 (
"display usage information")
9486 [
"-?"][
"-h"][
"--help"]
9491 struct Parser : ParserBase {
9493 mutable ExeName m_exeName;
9494 std::vector<Opt> m_options;
9495 std::vector<Arg> m_args;
9497 auto operator|=( ExeName
const &exeName ) -> Parser & {
9498 m_exeName = exeName;
9502 auto operator|=( Arg
const &arg ) -> Parser & {
9503 m_args.push_back(arg);
9507 auto operator|=( Opt
const &opt ) -> Parser & {
9508 m_options.push_back(opt);
9512 auto operator|=( Parser
const &other ) -> Parser & {
9513 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9514 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9518 template<
typename T>
9519 auto operator|( T
const &other )
const -> Parser {
9520 return Parser( *
this ) |= other;
9524 template<
typename T>
9525 auto operator+=( T
const &other ) -> Parser & {
return operator|=( other ); }
9526 template<
typename T>
9527 auto operator+( T
const &other )
const -> Parser {
return operator|( other ); }
9529 auto getHelpColumns()
const -> std::vector<HelpColumns> {
9530 std::vector<HelpColumns> cols;
9531 for (
auto const &o : m_options) {
9532 auto childCols = o.getHelpColumns();
9533 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9538 void writeToStream( std::ostream &os )
const {
9539 if (!m_exeName.name().empty()) {
9540 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9541 bool required =
true, first =
true;
9542 for(
auto const &arg : m_args ) {
9547 if( arg.isOptional() && required ) {
9551 os <<
"<" << arg.hint() <<
">";
9552 if( arg.cardinality() == 0 )
9557 if( !m_options.empty() )
9559 os <<
"\n\nwhere options are:" << std::endl;
9562 auto rows = getHelpColumns();
9563 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9564 size_t optWidth = 0;
9565 for(
auto const &cols : rows )
9566 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9568 optWidth = (std::min)(optWidth, consoleWidth/2);
9570 for(
auto const &cols : rows ) {
9572 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9573 TextFlow::Spacer(4) +
9574 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9575 os << row << std::endl;
9579 friend auto operator<<( std::ostream &os, Parser
const &parser ) -> std::ostream& {
9580 parser.writeToStream( os );
9584 auto validate()
const -> Result
override {
9585 for(
auto const &opt : m_options ) {
9586 auto result = opt.validate();
9590 for(
auto const &arg : m_args ) {
9591 auto result = arg.validate();
9595 return Result::ok();
9598 using ParserBase::parse;
9600 auto parse( std::string
const& exeName, TokenStream
const &tokens )
const -> InternalParseResult
override {
9603 ParserBase
const* parser =
nullptr;
9606 const size_t totalParsers = m_options.size() + m_args.size();
9607 assert( totalParsers < 512 );
9609 ParserInfo parseInfos[512];
9613 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9614 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9617 m_exeName.set( exeName );
9619 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9620 while( result.value().remainingTokens() ) {
9621 bool tokenParsed =
false;
9623 for(
size_t i = 0; i < totalParsers; ++i ) {
9624 auto& parseInfo = parseInfos[i];
9625 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9626 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9629 if (result.value().type() != ParseResultType::NoMatch) {
9637 if( result.value().type() == ParseResultType::ShortCircuitAll )
9640 return InternalParseResult::runtimeError(
"Unrecognised token: " + result.value().remainingTokens()->token );
9647 template<
typename DerivedT>
9648 template<
typename T>
9649 auto ComposableParserImpl<DerivedT>::operator|( T
const &other )
const -> Parser {
9650 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9655 using detail::Parser;
9667 using detail::ExeName;
9673 using detail::ParseResultType;
9676 using detail::ParserResult;
9682 #pragma clang diagnostic pop 9686 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9687 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9688 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH 9694 clara::Parser makeCommandLineParser( ConfigData& config );
9704 clara::Parser makeCommandLineParser( ConfigData& config ) {
9706 using namespace clara;
9708 auto const setWarning = [&]( std::string
const& warning ) {
9709 auto warningSet = [&]() {
9710 if( warning ==
"NoAssertions" )
9711 return WarnAbout::NoAssertions;
9713 if ( warning ==
"NoTests" )
9714 return WarnAbout::NoTests;
9716 return WarnAbout::Nothing;
9719 if (warningSet == WarnAbout::Nothing)
9720 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9721 config.warnings =
static_cast<WarnAbout::What
>( config.warnings | warningSet );
9722 return ParserResult::ok( ParseResultType::Matched );
9724 auto const loadTestNamesFromFile = [&]( std::string
const& filename ) {
9725 std::ifstream f( filename.c_str() );
9727 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'" );
9730 while( std::getline( f, line ) ) {
9732 if( !line.empty() && !startsWith( line,
'#' ) ) {
9733 if( !startsWith( line,
'"' ) )
9734 line =
'"' + line +
'"';
9735 config.testsOrTags.push_back( line );
9736 config.testsOrTags.emplace_back(
"," );
9740 if(!config.testsOrTags.empty())
9741 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9743 return ParserResult::ok( ParseResultType::Matched );
9745 auto const setTestOrder = [&]( std::string
const& order ) {
9746 if( startsWith(
"declared", order ) )
9747 config.runOrder = RunTests::InDeclarationOrder;
9748 else if( startsWith(
"lexical", order ) )
9749 config.runOrder = RunTests::InLexicographicalOrder;
9750 else if( startsWith(
"random", order ) )
9751 config.runOrder = RunTests::InRandomOrder;
9753 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'" );
9754 return ParserResult::ok( ParseResultType::Matched );
9756 auto const setRngSeed = [&]( std::string
const& seed ) {
9757 if( seed !=
"time" )
9758 return clara::detail::convertInto( seed, config.rngSeed );
9759 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9760 return ParserResult::ok( ParseResultType::Matched );
9762 auto const setColourUsage = [&]( std::string
const& useColour ) {
9763 auto mode = toLower( useColour );
9766 config.useColour = UseColour::Yes;
9767 else if( mode ==
"no" )
9768 config.useColour = UseColour::No;
9769 else if( mode ==
"auto" )
9770 config.useColour = UseColour::Auto;
9772 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9773 return ParserResult::ok( ParseResultType::Matched );
9775 auto const setWaitForKeypress = [&]( std::string
const& keypress ) {
9776 auto keypressLc = toLower( keypress );
9777 if (keypressLc ==
"never")
9778 config.waitForKeypress = WaitForKeypress::Never;
9779 else if( keypressLc ==
"start" )
9780 config.waitForKeypress = WaitForKeypress::BeforeStart;
9781 else if( keypressLc ==
"exit" )
9782 config.waitForKeypress = WaitForKeypress::BeforeExit;
9783 else if( keypressLc ==
"both" )
9784 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9786 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9787 return ParserResult::ok( ParseResultType::Matched );
9789 auto const setVerbosity = [&]( std::string
const& verbosity ) {
9790 auto lcVerbosity = toLower( verbosity );
9791 if( lcVerbosity ==
"quiet" )
9792 config.verbosity = Verbosity::Quiet;
9793 else if( lcVerbosity ==
"normal" )
9794 config.verbosity = Verbosity::Normal;
9795 else if( lcVerbosity ==
"high" )
9796 config.verbosity = Verbosity::High;
9798 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9799 return ParserResult::ok( ParseResultType::Matched );
9801 auto const setReporter = [&]( std::string
const& reporter ) {
9802 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
9804 auto lcReporter = toLower( reporter );
9805 auto result = factories.find( lcReporter );
9807 if( factories.end() != result )
9808 config.reporterName = lcReporter;
9810 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9811 return ParserResult::ok( ParseResultType::Matched );
9815 = ExeName( config.processName )
9816 | Help( config.showHelp )
9817 | Opt( config.listTests )
9818 ["-l"]["--list-tests"]
9819 (
"list all/matching test cases" )
9820 | Opt( config.listTags )
9821 ["-t"]["--list-tags"]
9822 (
"list all/matching tags" )
9823 | Opt( config.showSuccessfulTests )
9825 (
"include successful tests in output" )
9826 | Opt( config.shouldDebugBreak )
9828 (
"break into debugger on failure" )
9829 | Opt( config.noThrow )
9831 (
"skip exception tests" )
9832 | Opt( config.showInvisibles )
9833 ["-i"]["--invisibles"]
9834 (
"show invisibles (tabs, newlines)" )
9835 | Opt( config.outputFilename,
"filename" )
9837 (
"output filename" )
9838 | Opt( setReporter,
"name" )
9839 ["-r"]["--reporter"]
9840 (
"reporter to use (defaults to console)" )
9841 | Opt( config.name,
"name" )
9844 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9846 (
"abort at first failure" )
9847 | Opt( [&](
int x ){ config.abortAfter = x; },
"no. failures" )
9849 (
"abort after x failures" )
9850 | Opt( setWarning,
"warning name" )
9852 (
"enable warnings" )
9853 | Opt( [&](
bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; },
"yes|no" )
9854 [
"-d"][
"--durations"]
9855 (
"show test durations" )
9856 | Opt( config.minDuration,
"seconds" )
9857 ["-D"]["--min-duration"]
9858 (
"show test durations for tests taking at least the given number of seconds" )
9859 | Opt( loadTestNamesFromFile,
"filename" )
9860 ["-f"]["--input-file"]
9861 (
"load test names to run from a file" )
9862 | Opt( config.filenamesAsTags )
9863 ["-#"]["--filenames-as-tags"]
9864 (
"adds a tag for the filename" )
9865 | Opt( config.sectionsToRun,
"section name" )
9867 (
"specify section to run" )
9868 | Opt( setVerbosity,
"quiet|normal|high" )
9869 ["-v"]["--verbosity"]
9870 (
"set output verbosity" )
9871 | Opt( config.listTestNamesOnly )
9872 ["--list-test-names-only"]
9873 (
"list all/matching test cases names only" )
9874 | Opt( config.listReporters )
9875 ["--list-reporters"]
9876 (
"list all reporters" )
9877 | Opt( setTestOrder,
"decl|lex|rand" )
9879 (
"test case order (defaults to decl)" )
9880 | Opt( setRngSeed,
"'time'|number" )
9882 (
"set a specific seed for random numbers" )
9883 | Opt( setColourUsage,
"yes|no" )
9885 (
"should output be colourised" )
9886 | Opt( config.libIdentify )
9888 (
"report name and version according to libidentify standard" )
9889 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9890 ["--wait-for-keypress"]
9891 (
"waits for a keypress before exiting" )
9892 | Opt( config.benchmarkSamples,
"samples" )
9893 ["--benchmark-samples"]
9894 (
"number of samples to collect (default: 100)" )
9895 | Opt( config.benchmarkResamples,
"resamples" )
9896 ["--benchmark-resamples"]
9897 (
"number of resamples for the bootstrap (default: 100000)" )
9898 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9899 ["--benchmark-confidence-interval"]
9900 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9901 | Opt( config.benchmarkNoAnalysis )
9902 ["--benchmark-no-analysis"]
9903 (
"perform only measurements; do not perform any analysis" )
9904 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9905 ["--benchmark-warmup-time"]
9906 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9907 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9908 (
"which test or tests to use" );
9922 bool SourceLineInfo::operator == (
SourceLineInfo const& other )
const noexcept {
9923 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9925 bool SourceLineInfo::operator < (
SourceLineInfo const& other )
const noexcept {
9928 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9931 std::ostream& operator << ( std::ostream& os,
SourceLineInfo const& info ) {
9933 os << info.file <<
'(' << info.line <<
')';
9935 os << info.file <<
':' << info.line;
9940 std::string StreamEndStop::operator+()
const {
9941 return std::string();
9944 NonCopyable::NonCopyable() =
default;
9945 NonCopyable::~NonCopyable() =
default;
9953 Config::Config( ConfigData
const& data )
9955 m_stream( openStream() )
9961 for (
auto& elem : m_data.testsOrTags) {
9964 for (
auto& elem : m_data.sectionsToRun) {
9968 TestSpecParser parser(ITagAliasRegistry::get());
9969 if (!m_data.testsOrTags.empty()) {
9970 m_hasTestFilters =
true;
9971 for (
auto const& testOrTags : m_data.testsOrTags) {
9972 parser.parse(testOrTags);
9975 m_testSpec = parser.testSpec();
9978 std::string
const& Config::getFilename()
const {
9979 return m_data.outputFilename ;
9982 bool Config::listTests()
const {
return m_data.listTests; }
9983 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
9984 bool Config::listTags()
const {
return m_data.listTags; }
9985 bool Config::listReporters()
const {
return m_data.listReporters; }
9987 std::string Config::getProcessName()
const {
return m_data.processName; }
9988 std::string
const& Config::getReporterName()
const {
return m_data.reporterName; }
9990 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
9991 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
9993 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
9994 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
9996 bool Config::showHelp()
const {
return m_data.showHelp; }
9999 bool Config::allowThrows()
const {
return !m_data.noThrow; }
10000 std::ostream& Config::stream()
const {
return m_stream->stream(); }
10001 std::string Config::name()
const {
return m_data.name.empty() ? m_data.processName : m_data.name; }
10002 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
10003 bool Config::warnAboutMissingAssertions()
const {
return !!(m_data.warnings & WarnAbout::NoAssertions); }
10004 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings & WarnAbout::NoTests); }
10005 ShowDurations::OrNot Config::showDurations()
const {
return m_data.showDurations; }
10006 double Config::minDuration()
const {
return m_data.minDuration; }
10007 RunTests::InWhatOrder Config::runOrder()
const {
return m_data.runOrder; }
10008 unsigned int Config::rngSeed()
const {
return m_data.rngSeed; }
10009 UseColour::YesOrNo Config::useColour()
const {
return m_data.useColour; }
10010 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
10011 int Config::abortAfter()
const {
return m_data.abortAfter; }
10012 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
10013 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
10015 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
10016 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
10017 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
10018 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
10019 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10021 IStream const* Config::openStream() {
10022 return Catch::makeStream(m_data.outputFilename);
10029 #if defined(__clang__) 10030 # pragma clang diagnostic push 10031 # pragma clang diagnostic ignored "-Wexit-time-destructors" 10052 #if defined(CATCH_PLATFORM_WINDOWS) 10054 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) 10055 # define CATCH_DEFINED_NOMINMAX 10058 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) 10059 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN 10060 # define WIN32_LEAN_AND_MEAN 10064 #include <AfxWin.h> 10066 #include <windows.h> 10069 #ifdef CATCH_DEFINED_NOMINMAX 10072 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN 10073 # undef WIN32_LEAN_AND_MEAN 10076 #endif // defined(CATCH_PLATFORM_WINDOWS) 10084 struct IColourImpl {
10085 virtual ~IColourImpl() =
default;
10086 virtual void use( Colour::Code _colourCode ) = 0;
10089 struct NoColourImpl : IColourImpl {
10090 void use( Colour::Code )
override {}
10092 static IColourImpl* instance() {
10093 static NoColourImpl s_instance;
10094 return &s_instance;
10101 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) 10102 # ifdef CATCH_PLATFORM_WINDOWS 10103 # define CATCH_CONFIG_COLOUR_WINDOWS 10105 # define CATCH_CONFIG_COLOUR_ANSI 10109 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) 10114 class Win32ColourImpl :
public IColourImpl {
10116 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10118 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10119 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10120 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10121 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10124 void use( Colour::Code _colourCode )
override {
10125 switch( _colourCode ) {
10126 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
10127 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10128 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
10129 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
10130 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
10131 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10132 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10133 case Colour::Grey:
return setTextAttribute( 0 );
10135 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
10136 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10137 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10138 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10139 case Colour::BrightYellow:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10141 case Colour::Bright: CATCH_INTERNAL_ERROR(
"not a colour" );
10144 CATCH_ERROR(
"Unknown colour requested" );
10149 void setTextAttribute( WORD _textAttribute ) {
10150 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10152 HANDLE stdoutHandle;
10153 WORD originalForegroundAttributes;
10154 WORD originalBackgroundAttributes;
10157 IColourImpl* platformColourInstance() {
10158 static Win32ColourImpl s_instance;
10160 IConfigPtr config = getCurrentContext().getConfig();
10161 UseColour::YesOrNo colourMode = config
10162 ? config->useColour()
10164 if( colourMode == UseColour::Auto )
10165 colourMode = UseColour::Yes;
10166 return colourMode == UseColour::Yes
10168 : NoColourImpl::instance();
10174 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) 10176 #include <unistd.h> 10185 class PosixColourImpl :
public IColourImpl {
10187 void use( Colour::Code _colourCode )
override {
10188 switch( _colourCode ) {
10190 case Colour::White:
return setColour(
"[0m" );
10191 case Colour::Red:
return setColour(
"[0;31m" );
10192 case Colour::Green:
return setColour(
"[0;32m" );
10193 case Colour::Blue:
return setColour(
"[0;34m" );
10194 case Colour::Cyan:
return setColour(
"[0;36m" );
10195 case Colour::Yellow:
return setColour(
"[0;33m" );
10196 case Colour::Grey:
return setColour(
"[1;30m" );
10198 case Colour::LightGrey:
return setColour(
"[0;37m" );
10199 case Colour::BrightRed:
return setColour(
"[1;31m" );
10200 case Colour::BrightGreen:
return setColour(
"[1;32m" );
10201 case Colour::BrightWhite:
return setColour(
"[1;37m" );
10202 case Colour::BrightYellow:
return setColour(
"[1;33m" );
10204 case Colour::Bright: CATCH_INTERNAL_ERROR(
"not a colour" );
10205 default: CATCH_INTERNAL_ERROR(
"Unknown colour requested" );
10208 static IColourImpl* instance() {
10209 static PosixColourImpl s_instance;
10210 return &s_instance;
10214 void setColour(
const char* _escapeCode ) {
10215 getCurrentContext().getConfig()->stream()
10216 <<
'\033' << _escapeCode;
10220 bool useColourOnPlatform() {
10222 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10223 !isDebuggerActive() &&
10225 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) 10226 isatty(STDOUT_FILENO)
10232 IColourImpl* platformColourInstance() {
10234 IConfigPtr config = getCurrentContext().getConfig();
10235 UseColour::YesOrNo colourMode = config
10236 ? config->useColour()
10238 if( colourMode == UseColour::Auto )
10239 colourMode = useColourOnPlatform()
10242 return colourMode == UseColour::Yes
10243 ? PosixColourImpl::instance()
10244 : NoColourImpl::instance();
10250 #else // not Windows or ANSI 10254 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
10258 #endif // Windows/ ANSI/ None 10262 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10263 Colour::Colour( Colour&& other ) noexcept {
10264 m_moved = other.m_moved;
10265 other.m_moved =
true;
10267 Colour& Colour::operator=( Colour&& other ) noexcept {
10268 m_moved = other.m_moved;
10269 other.m_moved =
true;
10273 Colour::~Colour(){
if( !m_moved ) use( None ); }
10275 void Colour::use( Code _colourCode ) {
10276 static IColourImpl* impl = platformColourInstance();
10281 if (impl !=
nullptr) {
10282 impl->use( _colourCode );
10286 std::ostream& operator << ( std::ostream& os, Colour
const& ) {
10292 #if defined(__clang__) 10293 # pragma clang diagnostic pop 10305 return m_resultCapture;
10307 IRunner* getRunner()
override {
10311 IConfigPtr
const& getConfig()
const override {
10315 ~Context()
override;
10318 void setResultCapture(
IResultCapture* resultCapture )
override {
10319 m_resultCapture = resultCapture;
10321 void setRunner(
IRunner* runner )
override {
10324 void setConfig( IConfigPtr
const& config )
override {
10331 IConfigPtr m_config;
10338 void IMutableContext::createContext()
10340 currentContext =
new Context();
10343 void cleanUpContext() {
10344 delete IMutableContext::currentContext;
10345 IMutableContext::currentContext =
nullptr;
10347 IContext::~IContext() =
default;
10348 IMutableContext::~IMutableContext() =
default;
10349 Context::~Context() =
default;
10365 void writeToDebugConsole( std::string
const& text );
10369 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE) 10370 #include <android/log.h> 10373 void writeToDebugConsole( std::string
const& text ) {
10374 __android_log_write( ANDROID_LOG_DEBUG,
"Catch", text.c_str() );
10378 #elif defined(CATCH_PLATFORM_WINDOWS) 10381 void writeToDebugConsole( std::string
const& text ) {
10382 ::OutputDebugStringA( text.c_str() );
10389 void writeToDebugConsole( std::string
const& text ) {
10391 Catch::cout() << text;
10399 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE) 10401 # include <cassert> 10402 # include <sys/types.h> 10403 # include <unistd.h> 10404 # include <cstddef> 10405 # include <ostream> 10407 #ifdef __apple_build_version__ 10410 # include <sys/sysctl.h> 10414 #ifdef __apple_build_version__ 10420 bool isDebuggerActive(){
10422 struct kinfo_proc info;
10428 info.kp_proc.p_flag = 0;
10434 mib[1] = KERN_PROC;
10435 mib[2] = KERN_PROC_PID;
10440 size =
sizeof(info);
10441 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0 ) {
10442 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10448 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10451 bool isDebuggerActive() {
10458 #elif defined(CATCH_PLATFORM_LINUX) 10470 bool isDebuggerActive(){
10474 std::ifstream in(
"/proc/self/status");
10475 for( std::string line; std::getline(in, line); ) {
10476 static const int PREFIX_LEN = 11;
10477 if( line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
10481 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
10488 #elif defined(_MSC_VER) 10489 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10491 bool isDebuggerActive() {
10492 return IsDebuggerPresent() != 0;
10495 #elif defined(__MINGW32__) 10496 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10498 bool isDebuggerActive() {
10499 return IsDebuggerPresent() != 0;
10504 bool isDebuggerActive() {
return false; }
10512 ITransientExpression::~ITransientExpression() =
default;
10514 void formatReconstructedExpression( std::ostream &os, std::string
const& lhs,
StringRef op, std::string
const& rhs ) {
10515 if( lhs.size() + rhs.size() < 40 &&
10516 lhs.find(
'\n') == std::string::npos &&
10517 rhs.find(
'\n') == std::string::npos )
10518 os << lhs <<
" " << op <<
" " << rhs;
10520 os << lhs <<
"\n" << op <<
"\n" << rhs;
10526 #include <stdexcept> 10529 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) 10531 void throw_exception(std::exception
const& e) {
10532 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n" 10533 <<
"The message was: " << e.what() <<
'\n';
10539 void throw_logic_error(std::string
const& msg) {
10540 throw_exception(std::logic_error(msg));
10544 void throw_domain_error(std::string
const& msg) {
10545 throw_exception(std::domain_error(msg));
10549 void throw_runtime_error(std::string
const& msg) {
10550 throw_exception(std::runtime_error(msg));
10565 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const& values );
10569 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10571 EnumInfo
const& registerEnum(
StringRef enumName,
StringRef allEnums, std::vector<int>
const& values)
override;
10574 std::vector<StringRef> parseEnums(
StringRef enums );
10587 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10596 size_t name_start = enumInstance.size();
10597 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10600 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10604 std::vector<StringRef> parseEnums(
StringRef enums ) {
10605 auto enumValues = splitStringRef( enums,
',' );
10606 std::vector<StringRef> parsed;
10607 parsed.reserve( enumValues.size() );
10608 for(
auto const& enumValue : enumValues ) {
10609 parsed.push_back(trim(extractInstanceName(enumValue)));
10614 EnumInfo::~EnumInfo() {}
10616 StringRef EnumInfo::lookup(
int value )
const {
10617 for(
auto const& valueToName : m_values ) {
10618 if( valueToName.first == value )
10619 return valueToName.second;
10621 return "{** unexpected enum value **}"_sr;
10624 std::unique_ptr<EnumInfo> makeEnumInfo(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const& values ) {
10625 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo );
10626 enumInfo->m_name = enumName;
10627 enumInfo->m_values.reserve( values.size() );
10629 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10630 assert( valueNames.size() == values.size() );
10632 for(
auto value : values )
10633 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10638 EnumInfo
const& EnumValuesRegistry::registerEnum(
StringRef enumName,
StringRef allValueNames, std::vector<int>
const& values ) {
10639 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10640 return *m_enumInfos.back();
10652 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10653 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10668 ~ExceptionTranslatorRegistry();
10670 std::string translateActiveException()
const override;
10671 std::string tryTranslators()
const;
10674 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10680 #import "Foundation/Foundation.h" 10685 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10688 void ExceptionTranslatorRegistry::registerTranslator(
const IExceptionTranslator* translator ) {
10689 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10692 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 10693 std::string ExceptionTranslatorRegistry::translateActiveException()
const {
10698 return tryTranslators();
10700 @catch (NSException *exception) {
10701 return Catch::Detail::stringify( [exception description] );
10712 if (std::current_exception() ==
nullptr) {
10713 return "Non C++ exception. Possibly a CLR exception.";
10715 return tryTranslators();
10719 std::rethrow_exception(std::current_exception());
10721 catch( std::exception& ex ) {
10724 catch( std::string& msg ) {
10727 catch(
const char* msg ) {
10731 return "Unknown exception";
10735 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10736 if (m_translators.empty()) {
10737 std::rethrow_exception(std::current_exception());
10739 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10743 #else // ^^ Exceptions are enabled // Exceptions are disabled vv 10744 std::string ExceptionTranslatorRegistry::translateActiveException()
const {
10745 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10748 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10749 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10757 #include <algorithm> 10759 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS ) 10765 void FatalConditionHandler::engage_platform() {}
10766 void FatalConditionHandler::disengage_platform() {}
10767 FatalConditionHandler::FatalConditionHandler() =
default;
10768 FatalConditionHandler::~FatalConditionHandler() =
default;
10772 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS 10774 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS ) 10775 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time" 10776 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS 10778 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) 10782 void reportFatal(
char const *
const message ) {
10783 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10789 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10792 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS 10794 #if defined( CATCH_CONFIG_WINDOWS_SEH ) 10798 struct SignalDefs { DWORD id;
const char* name; };
10803 static SignalDefs signalDefs[] = {
10804 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10805 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10806 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10807 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10810 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10811 for (
auto const& def : signalDefs) {
10812 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10813 reportFatal(def.name);
10818 return EXCEPTION_CONTINUE_SEARCH;
10824 static PVOID exceptionHandlerHandle =
nullptr;
10828 FatalConditionHandler::FatalConditionHandler() {
10829 ULONG guaranteeSize =
static_cast<ULONG
>(minStackSizeForErrors);
10830 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10834 <<
"Failed to reserve piece of stack." 10835 <<
" Stack overflows will not be reported successfully.";
10841 FatalConditionHandler::~FatalConditionHandler() =
default;
10843 void FatalConditionHandler::engage_platform() {
10845 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10846 if (!exceptionHandlerHandle) {
10847 CATCH_RUNTIME_ERROR(
"Could not register vectored exception handler");
10851 void FatalConditionHandler::disengage_platform() {
10852 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10853 CATCH_RUNTIME_ERROR(
"Could not unregister vectored exception handler");
10855 exceptionHandlerHandle =
nullptr;
10860 #endif // CATCH_CONFIG_WINDOWS_SEH 10862 #if defined( CATCH_CONFIG_POSIX_SIGNALS ) 10864 #include <signal.h> 10868 struct SignalDefs {
10873 static SignalDefs signalDefs[] = {
10874 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10875 { SIGILL,
"SIGILL - Illegal instruction signal" },
10876 { SIGFPE,
"SIGFPE - Floating point error signal" },
10877 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10878 { SIGTERM,
"SIGTERM - Termination request signal" },
10879 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10885 #if defined(__GNUC__) 10886 # pragma GCC diagnostic push 10887 # pragma GCC diagnostic ignored "-Wmissing-field-initializers" 10890 static char* altStackMem =
nullptr;
10891 static std::size_t altStackSize = 0;
10892 static stack_t oldSigStack{};
10893 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10895 static void restorePreviousSignalHandlers() {
10900 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
10901 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10904 sigaltstack(&oldSigStack,
nullptr);
10907 static void handleSignal(
int sig ) {
10908 char const * name =
"<unknown signal>";
10909 for (
auto const& def : signalDefs) {
10910 if (sig == def.id) {
10918 restorePreviousSignalHandlers();
10919 reportFatal( name );
10923 FatalConditionHandler::FatalConditionHandler() {
10924 assert(!altStackMem &&
"Cannot initialize POSIX signal handler when one already exists");
10925 if (altStackSize == 0) {
10926 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10928 altStackMem =
new char[altStackSize]();
10931 FatalConditionHandler::~FatalConditionHandler() {
10932 delete[] altStackMem;
10935 altStackMem =
nullptr;
10938 void FatalConditionHandler::engage_platform() {
10940 sigStack.ss_sp = altStackMem;
10941 sigStack.ss_size = altStackSize;
10942 sigStack.ss_flags = 0;
10943 sigaltstack(&sigStack, &oldSigStack);
10944 struct sigaction sa = { };
10946 sa.sa_handler = handleSignal;
10947 sa.sa_flags = SA_ONSTACK;
10948 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
10949 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
10953 #if defined(__GNUC__) 10954 # pragma GCC diagnostic pop 10957 void FatalConditionHandler::disengage_platform() {
10958 restorePreviousSignalHandlers();
10963 #endif // CATCH_CONFIG_POSIX_SIGNALS 10972 IGeneratorTracker::~IGeneratorTracker() {}
10974 const char* GeneratorException::what()
const noexcept {
10978 namespace Generators {
10980 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10983 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10992 IResultCapture::~IResultCapture() =
default;
10998 IConfig::~IConfig() =
default;
11004 IExceptionTranslator::~IExceptionTranslator() =
default;
11005 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() =
default;
11011 IRegistryHub::~IRegistryHub() =
default;
11012 IMutableRegistryHub::~IMutableRegistryHub() =
default;
11021 class ListeningReporter :
public IStreamingReporter {
11022 using Reporters = std::vector<IStreamingReporterPtr>;
11023 Reporters m_listeners;
11024 IStreamingReporterPtr m_reporter =
nullptr;
11025 ReporterPreferences m_preferences;
11028 ListeningReporter();
11030 void addListener( IStreamingReporterPtr&& listener );
11031 void addReporter( IStreamingReporterPtr&& reporter );
11035 ReporterPreferences getPreferences()
const override;
11037 void noMatchingTestCases( std::string
const& spec )
override;
11039 void reportInvalidArguments(std::string
const&arg)
override;
11041 static std::set<Verbosity> getSupportedVerbosities();
11043 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 11044 void benchmarkPreparing(std::string
const& name)
override;
11045 void benchmarkStarting( BenchmarkInfo
const& benchmarkInfo )
override;
11046 void benchmarkEnded( BenchmarkStats<>
const& benchmarkStats )
override;
11047 void benchmarkFailed(std::string
const&)
override;
11048 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 11050 void testRunStarting( TestRunInfo
const& testRunInfo )
override;
11051 void testGroupStarting( GroupInfo
const& groupInfo )
override;
11052 void testCaseStarting(
TestCaseInfo const& testInfo )
override;
11053 void sectionStarting(
SectionInfo const& sectionInfo )
override;
11054 void assertionStarting(
AssertionInfo const& assertionInfo )
override;
11057 bool assertionEnded( AssertionStats
const& assertionStats )
override;
11058 void sectionEnded( SectionStats
const& sectionStats )
override;
11059 void testCaseEnded( TestCaseStats
const& testCaseStats )
override;
11060 void testGroupEnded( TestGroupStats
const& testGroupStats )
override;
11061 void testRunEnded( TestRunStats
const& testRunStats )
override;
11063 void skipTest(
TestCaseInfo const& testInfo )
override;
11064 bool isMulti()
const override;
11073 ReporterConfig::ReporterConfig( IConfigPtr
const& _fullConfig )
11074 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11076 ReporterConfig::ReporterConfig( IConfigPtr
const& _fullConfig, std::ostream& _stream )
11077 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11079 std::ostream& ReporterConfig::stream()
const {
return *m_stream; }
11080 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
11082 TestRunInfo::TestRunInfo( std::string
const& _name ) : name( _name ) {}
11084 GroupInfo::GroupInfo( std::string
const& _name,
11085 std::size_t _groupIndex,
11086 std::size_t _groupsCount )
11088 groupIndex( _groupIndex ),
11089 groupsCounts( _groupsCount )
11092 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
11093 std::vector<MessageInfo>
const& _infoMessages,
11095 : assertionResult( _assertionResult ),
11096 infoMessages( _infoMessages ),
11099 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11101 if( assertionResult.hasMessage() ) {
11104 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11105 builder << assertionResult.getMessage();
11106 builder.m_info.message = builder.m_stream.str();
11108 infoMessages.push_back( builder.m_info );
11112 AssertionStats::~AssertionStats() =
default;
11114 SectionStats::SectionStats(
SectionInfo const& _sectionInfo,
11115 Counts const& _assertions,
11116 double _durationInSeconds,
11117 bool _missingAssertions )
11118 : sectionInfo( _sectionInfo ),
11119 assertions( _assertions ),
11120 durationInSeconds( _durationInSeconds ),
11121 missingAssertions( _missingAssertions )
11124 SectionStats::~SectionStats() =
default;
11126 TestCaseStats::TestCaseStats(
TestCaseInfo const& _testInfo,
11128 std::string
const& _stdOut,
11129 std::string
const& _stdErr,
11131 : testInfo( _testInfo ),
11135 aborting( _aborting )
11138 TestCaseStats::~TestCaseStats() =
default;
11140 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11143 : groupInfo( _groupInfo ),
11145 aborting( _aborting )
11148 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11149 : groupInfo( _groupInfo ),
11153 TestGroupStats::~TestGroupStats() =
default;
11155 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11158 : runInfo( _runInfo ),
11160 aborting( _aborting )
11163 TestRunStats::~TestRunStats() =
default;
11165 void IStreamingReporter::fatalErrorEncountered(
StringRef ) {}
11166 bool IStreamingReporter::isMulti()
const {
return false; }
11168 IReporterFactory::~IReporterFactory() =
default;
11169 IReporterRegistry::~IReporterRegistry() =
default;
11176 IRunner::~IRunner() =
default;
11182 ITestInvoker::~ITestInvoker() =
default;
11183 ITestCaseRegistry::~ITestCaseRegistry() =
default;
11188 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG 11189 #include <crtdbg.h> 11193 LeakDetector::LeakDetector() {
11194 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11195 flag |= _CRTDBG_LEAK_CHECK_DF;
11196 flag |= _CRTDBG_ALLOC_MEM_DF;
11197 _CrtSetDbgFlag(flag);
11198 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11199 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11201 _CrtSetBreakAlloc(-1);
11207 Catch::LeakDetector::LeakDetector() {}
11211 Catch::LeakDetector::~LeakDetector() {
11223 std::size_t listTests( Config
const& config );
11225 std::size_t listTestsNamesOnly( Config
const& config );
11228 void add( std::string
const& spelling );
11229 std::string all()
const;
11231 std::set<std::string> spellings;
11232 std::size_t count = 0;
11235 std::size_t listTags( Config
const& config );
11237 std::size_t listReporters();
11247 using namespace clara::TextFlow;
11252 #include <algorithm> 11257 std::size_t listTests( Config
const& config ) {
11258 TestSpec
const& testSpec = config.testSpec();
11259 if( config.hasTestFilters() )
11260 Catch::cout() <<
"Matching test cases:\n";
11262 Catch::cout() <<
"All available test cases:\n";
11265 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11266 for(
auto const& testCaseInfo : matchedTestCases ) {
11267 Colour::Code colour = testCaseInfo.isHidden()
11268 ? Colour::SecondaryText
11270 Colour colourGuard( colour );
11272 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11273 if( config.verbosity() >= Verbosity::High ) {
11274 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11275 std::string description = testCaseInfo.description;
11276 if( description.empty() )
11277 description =
"(NO DESCRIPTION)";
11278 Catch::cout() << Column( description ).indent(4) << std::endl;
11280 if( !testCaseInfo.tags.empty() )
11281 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) <<
"\n";
11284 if( !config.hasTestFilters() )
11285 Catch::cout() <<
pluralise( matchedTestCases.size(),
"test case" ) <<
'\n' << std::endl;
11287 Catch::cout() <<
pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11288 return matchedTestCases.size();
11291 std::size_t listTestsNamesOnly( Config
const& config ) {
11292 TestSpec
const& testSpec = config.testSpec();
11293 std::size_t matchedTests = 0;
11294 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11295 for(
auto const& testCaseInfo : matchedTestCases ) {
11297 if( startsWith( testCaseInfo.name,
'#' ) )
11298 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11300 Catch::cout() << testCaseInfo.name;
11301 if ( config.verbosity() >= Verbosity::High )
11302 Catch::cout() <<
"\t@" << testCaseInfo.lineInfo;
11303 Catch::cout() << std::endl;
11305 return matchedTests;
11308 void TagInfo::add( std::string
const& spelling ) {
11310 spellings.insert( spelling );
11313 std::string TagInfo::all()
const {
11315 for (
auto const& spelling : spellings) {
11317 size += spelling.size() + 2;
11320 std::string out; out.reserve(size);
11321 for (
auto const& spelling : spellings) {
11329 std::size_t listTags( Config
const& config ) {
11330 TestSpec
const& testSpec = config.testSpec();
11331 if( config.hasTestFilters() )
11332 Catch::cout() <<
"Tags for matching test cases:\n";
11334 Catch::cout() <<
"All available tags:\n";
11337 std::map<std::string, TagInfo> tagCounts;
11339 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11340 for(
auto const& testCase : matchedTestCases ) {
11341 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11342 std::string lcaseTagName = toLower( tagName );
11343 auto countIt = tagCounts.find( lcaseTagName );
11344 if( countIt == tagCounts.end() )
11345 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11346 countIt->second.add( tagName );
11350 for(
auto const& tagCount : tagCounts ) {
11352 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11353 auto str = rss.str();
11354 auto wrapper = Column( tagCount.second.all() )
11355 .initialIndent( 0 )
11356 .indent( str.size() )
11357 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11358 Catch::cout() << str << wrapper <<
'\n';
11360 Catch::cout() <<
pluralise( tagCounts.size(),
"tag" ) <<
'\n' << std::endl;
11361 return tagCounts.size();
11364 std::size_t listReporters() {
11365 Catch::cout() <<
"Available reporters:\n";
11366 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
11367 std::size_t maxNameLen = 0;
11368 for(
auto const& factoryKvp : factories )
11369 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11371 for(
auto const& factoryKvp : factories ) {
11373 << Column( factoryKvp.first +
":" )
11375 .width( 5+maxNameLen )
11376 + Column( factoryKvp.second->getDescription() )
11379 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11382 Catch::cout() << std::endl;
11383 return factories.size();
11388 getCurrentMutableContext().setConfig( config );
11389 if( config->listTests() )
11390 listedCount = listedCount.valueOr(0) + listTests( *config );
11391 if( config->listTestNamesOnly() )
11392 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11393 if( config->listTags() )
11394 listedCount = listedCount.valueOr(0) + listTags( *config );
11395 if( config->listReporters() )
11396 listedCount = listedCount.valueOr(0) + listReporters();
11397 return listedCount;
11405 namespace Matchers {
11408 std::string MatcherUntypedBase::toString()
const {
11409 if( m_cachedToString.empty() )
11410 m_cachedToString = describe();
11411 return m_cachedToString;
11414 MatcherUntypedBase::~MatcherUntypedBase() =
default;
11419 using namespace Matchers;
11427 namespace Matchers {
11428 namespace Exception {
11430 bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11431 return ex.what() == m_message;
11434 std::string ExceptionMessageMatcher::describe()
const {
11435 return "exception message matches \"" + m_message +
"\"";
11452 bool isnan(
float f);
11453 bool isnan(
double d);
11462 template <
typename T>
11463 std::string to_string(T
const& t) {
11464 #if defined(CATCH_CONFIG_CPP11_TO_STRING) 11465 return std::to_string(t);
11475 #include <algorithm> 11481 #include <type_traits> 11488 int32_t convert(
float f) {
11489 static_assert(
sizeof(
float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11491 std::memcpy(&i, &f,
sizeof(f));
11495 int64_t convert(
double d) {
11496 static_assert(
sizeof(
double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11498 std::memcpy(&i, &d,
sizeof(d));
11502 template <
typename FP>
11503 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11506 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11510 auto lc = convert(lhs);
11511 auto rc = convert(rhs);
11513 if ((lc < 0) != (rc < 0)) {
11519 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11520 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11523 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11525 float nextafter(
float x,
float y) {
11526 return ::nextafterf(x, y);
11529 double nextafter(
double x,
double y) {
11530 return ::nextafter(x, y);
11533 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^ 11535 template <
typename FP>
11536 FP step(FP start, FP direction, uint64_t steps) {
11537 for (uint64_t i = 0; i < steps; ++i) {
11538 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) 11539 start = Catch::nextafter(start, direction);
11541 start = std::nextafter(start, direction);
11549 bool marginComparison(
double lhs,
double rhs,
double margin) {
11550 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11553 template <
typename FloatingPo
int>
11554 void write(std::ostream& out, FloatingPoint num) {
11555 out << std::scientific
11556 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11562 namespace Matchers {
11563 namespace Floating {
11565 enum class FloatingPointKind : uint8_t {
11570 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11571 :m_target{ target }, m_margin{ margin } {
11572 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.' 11573 <<
" Margin has to be non-negative.");
11578 bool WithinAbsMatcher::match(
double const& matchee)
const {
11579 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11582 std::string WithinAbsMatcher::describe()
const {
11583 return "is within " + ::Catch::Detail::stringify(m_margin) +
" of " + ::Catch::Detail::stringify(m_target);
11586 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11587 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11588 CATCH_ENFORCE(m_type == FloatingPointKind::Double
11589 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11590 "Provided ULP is impossibly large for a float comparison.");
11593 #if defined(__clang__) 11594 #pragma clang diagnostic push 11596 #pragma clang diagnostic ignored "-Wunreachable-code" 11599 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11601 case FloatingPointKind::Float:
11602 return almostEqualUlps<float>(
static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11603 case FloatingPointKind::Double:
11604 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11606 CATCH_INTERNAL_ERROR(
"Unknown FloatingPointKind value" );
11610 #if defined(__clang__) 11611 #pragma clang diagnostic pop 11614 std::string WithinUlpsMatcher::describe()
const {
11615 std::stringstream ret;
11617 ret <<
"is within " << m_ulps <<
" ULPs of ";
11619 if (m_type == FloatingPointKind::Float) {
11620 write(ret, static_cast<float>(m_target));
11623 write(ret, m_target);
11627 if (m_type == FloatingPointKind::Double) {
11628 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11630 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11633 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11635 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11642 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11644 m_epsilon(epsilon){
11645 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11646 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
"); 11649 bool WithinRelMatcher::match(double const& matchee) const { 11650 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target)); 11651 return marginComparison(matchee, m_target, 11652 std::isinf(relMargin)? 0 : relMargin); 11655 std::string WithinRelMatcher::describe() const { 11656 Catch::ReusableStringStream sstr; 11657 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
"; 11661 }// namespace Floating 11663 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) { 11664 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); 11667 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) { 11668 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); 11671 Floating::WithinAbsMatcher WithinAbs(double target, double margin) { 11672 return Floating::WithinAbsMatcher(target, margin); 11675 Floating::WithinRelMatcher WithinRel(double target, double eps) { 11676 return Floating::WithinRelMatcher(target, eps); 11679 Floating::WithinRelMatcher WithinRel(double target) { 11680 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100); 11683 Floating::WithinRelMatcher WithinRel(float target, float eps) { 11684 return Floating::WithinRelMatcher(target, eps); 11687 Floating::WithinRelMatcher WithinRel(float target) { 11688 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100); 11691 } // namespace Matchers 11692 } // namespace Catch 11693 // end catch_matchers_floating.cpp 11694 // start catch_matchers_generic.cpp 11696 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { 11697 if (desc.empty()) { 11698 return "matches undescribed predicate
"; 11700 return "matches predicate: \
"" + desc +
'"';
11709 namespace Matchers {
11711 namespace StdString {
11713 CasedString::CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity )
11714 : m_caseSensitivity( caseSensitivity ),
11715 m_str( adjustString( str ) )
11717 std::string CasedString::adjustString( std::string
const& str )
const {
11718 return m_caseSensitivity == CaseSensitive::No
11722 std::string CasedString::caseSensitivitySuffix()
const {
11723 return m_caseSensitivity == CaseSensitive::No
11724 ?
" (case insensitive)" 11728 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
11729 : m_comparator( comparator ),
11730 m_operation( operation ) {
11733 std::string StringMatcherBase::describe()
const {
11734 std::string description;
11735 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11736 m_comparator.caseSensitivitySuffix().size());
11737 description += m_operation;
11738 description +=
": \"";
11739 description += m_comparator.m_str;
11740 description +=
"\"";
11741 description += m_comparator.caseSensitivitySuffix();
11742 return description;
11745 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11747 bool EqualsMatcher::match( std::string
const& source )
const {
11748 return m_comparator.adjustString( source ) == m_comparator.m_str;
11751 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11753 bool ContainsMatcher::match( std::string
const& source )
const {
11754 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11757 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11759 bool StartsWithMatcher::match( std::string
const& source )
const {
11760 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11763 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11765 bool EndsWithMatcher::match( std::string
const& source )
const {
11766 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11769 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11771 bool RegexMatcher::match(std::string
const& matchee)
const {
11772 auto flags = std::regex::ECMAScript;
11773 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11774 flags |= std::regex::icase;
11776 auto reg = std::regex(m_regex, flags);
11777 return std::regex_match(matchee, reg);
11780 std::string RegexMatcher::describe()
const {
11781 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)?
" case sensitively" :
" case insensitively");
11811 bool uncaught_exceptions();
11820 MessageInfo::MessageInfo(
StringRef const& _macroName,
11822 ResultWas::OfType _type )
11823 : macroName( _macroName ),
11824 lineInfo( _lineInfo ),
11826 sequence( ++globalCount )
11829 bool MessageInfo::operator==(
MessageInfo const& other )
const {
11830 return sequence == other.sequence;
11833 bool MessageInfo::operator<(
MessageInfo const& other )
const {
11834 return sequence < other.sequence;
11838 unsigned int MessageInfo::globalCount = 0;
11842 Catch::MessageBuilder::MessageBuilder(
StringRef const& macroName,
11844 ResultWas::OfType type )
11845 :m_info(macroName, lineInfo, type) {}
11850 : m_info( builder.m_info ), m_moved()
11852 m_info.message = builder.m_stream.str();
11853 getResultCapture().pushScopedMessage( m_info );
11857 : m_info( old.m_info ), m_moved()
11859 old.m_moved =
true;
11862 ScopedMessage::~ScopedMessage() {
11863 if ( !uncaught_exceptions() && !m_moved ){
11864 getResultCapture().popScopedMessage(m_info);
11869 auto trimmed = [&] (
size_t start,
size_t end) {
11870 while (names[start] ==
',' || isspace(static_cast<unsigned char>(names[start]))) {
11873 while (names[end] ==
',' || isspace(static_cast<unsigned char>(names[end]))) {
11876 return names.substr(start, end - start + 1);
11878 auto skipq = [&] (
size_t start,
char quote) {
11879 for (
auto i = start + 1; i < names.size() ; ++i) {
11880 if (names[i] == quote)
11882 if (names[i] ==
'\\')
11885 CATCH_INTERNAL_ERROR(
"CAPTURE parsing encountered unmatched quote");
11889 std::stack<char> openings;
11890 for (
size_t pos = 0; pos < names.size(); ++pos) {
11891 char c = names[pos];
11909 pos = skipq(pos, c);
11912 if (start != pos && openings.empty()) {
11913 m_messages.emplace_back(macroName, lineInfo, resultType);
11914 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11915 m_messages.back().message +=
" := ";
11920 assert(openings.empty() &&
"Mismatched openings");
11921 m_messages.emplace_back(macroName, lineInfo, resultType);
11922 m_messages.back().message =
static_cast<std::string
>(trimmed(start, names.size() - 1));
11923 m_messages.back().message +=
" := ";
11925 Capturer::~Capturer() {
11926 if ( !uncaught_exceptions() ){
11927 assert( m_captured == m_messages.size() );
11928 for(
size_t i = 0; i < m_captured; ++i )
11929 m_resultCapture.popScopedMessage( m_messages[i] );
11933 void Capturer::captureValue(
size_t index, std::string
const& value ) {
11934 assert( index < m_messages.size() );
11935 m_messages[index].message += value;
11936 m_resultCapture.pushScopedMessage( m_messages[index] );
11945 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11946 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 11954 class RedirectedStream {
11955 std::ostream& m_originalStream;
11956 std::ostream& m_redirectionStream;
11957 std::streambuf* m_prevBuf;
11960 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11961 ~RedirectedStream();
11964 class RedirectedStdOut {
11966 RedirectedStream m_cout;
11968 RedirectedStdOut();
11969 auto str()
const -> std::string;
11975 class RedirectedStdErr {
11977 RedirectedStream m_cerr;
11978 RedirectedStream m_clog;
11980 RedirectedStdErr();
11981 auto str()
const -> std::string;
11984 class RedirectedStreams {
11986 RedirectedStreams(RedirectedStreams
const&) =
delete;
11987 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
11988 RedirectedStreams(RedirectedStreams&&) =
delete;
11989 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
11991 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11992 ~RedirectedStreams();
11994 std::string& m_redirectedCout;
11995 std::string& m_redirectedCerr;
11996 RedirectedStdOut m_redirectedStdOut;
11997 RedirectedStdErr m_redirectedStdErr;
12000 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12008 TempFile(TempFile
const&) =
delete;
12009 TempFile& operator=(TempFile
const&) =
delete;
12010 TempFile(TempFile&&) =
delete;
12011 TempFile& operator=(TempFile&&) =
delete;
12016 std::FILE* getFile();
12017 std::string getContents();
12020 std::FILE* m_file =
nullptr;
12021 #if defined(_MSC_VER) 12022 char m_buffer[L_tmpnam] = { 0 };
12026 class OutputRedirect {
12028 OutputRedirect(OutputRedirect
const&) =
delete;
12029 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
12030 OutputRedirect(OutputRedirect&&) =
delete;
12031 OutputRedirect& operator=(OutputRedirect&&) =
delete;
12033 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12037 int m_originalStdout = -1;
12038 int m_originalStderr = -1;
12039 TempFile m_stdoutFile;
12040 TempFile m_stderrFile;
12041 std::string& m_stdoutDest;
12042 std::string& m_stderrDest;
12049 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H 12055 #include <stdexcept> 12057 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12058 #if defined(_MSC_VER) 12062 #define fileno _fileno 12064 #include <unistd.h> 12070 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12071 : m_originalStream( originalStream ),
12072 m_redirectionStream( redirectionStream ),
12073 m_prevBuf( m_originalStream.rdbuf() )
12075 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12078 RedirectedStream::~RedirectedStream() {
12079 m_originalStream.rdbuf( m_prevBuf );
12082 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
12083 auto RedirectedStdOut::str()
const -> std::string {
return m_rss.str(); }
12085 RedirectedStdErr::RedirectedStdErr()
12086 : m_cerr( Catch::cerr(), m_rss.get() ),
12087 m_clog( Catch::clog(), m_rss.get() )
12089 auto RedirectedStdErr::str()
const -> std::string {
return m_rss.str(); }
12091 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12092 : m_redirectedCout(redirectedCout),
12093 m_redirectedCerr(redirectedCerr)
12096 RedirectedStreams::~RedirectedStreams() {
12097 m_redirectedCout += m_redirectedStdOut.str();
12098 m_redirectedCerr += m_redirectedStdErr.str();
12101 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12103 #if defined(_MSC_VER) 12104 TempFile::TempFile() {
12105 if (tmpnam_s(m_buffer)) {
12106 CATCH_RUNTIME_ERROR(
"Could not get a temp filename");
12108 if (fopen_s(&m_file, m_buffer,
"w+")) {
12110 if (strerror_s(buffer, errno)) {
12111 CATCH_RUNTIME_ERROR(
"Could not translate errno to a string");
12113 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12117 TempFile::TempFile() {
12118 m_file = std::tmpfile();
12120 CATCH_RUNTIME_ERROR(
"Could not create a temp file.");
12126 TempFile::~TempFile() {
12128 std::fclose(m_file);
12131 #if defined(_MSC_VER) 12132 std::remove(m_buffer);
12136 FILE* TempFile::getFile() {
12140 std::string TempFile::getContents() {
12141 std::stringstream sstr;
12142 char buffer[100] = {};
12143 std::rewind(m_file);
12144 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12150 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12151 m_originalStdout(dup(1)),
12152 m_originalStderr(dup(2)),
12153 m_stdoutDest(stdout_dest),
12154 m_stderrDest(stderr_dest) {
12155 dup2(fileno(m_stdoutFile.getFile()), 1);
12156 dup2(fileno(m_stderrFile.getFile()), 2);
12159 OutputRedirect::~OutputRedirect() {
12160 Catch::cout() << std::flush;
12164 Catch::cerr() << std::flush;
12165 Catch::clog() << std::flush;
12168 dup2(m_originalStdout, 1);
12169 dup2(m_originalStderr, 2);
12171 m_stdoutDest += m_stdoutFile.getContents();
12172 m_stderrDest += m_stderrFile.getContents();
12175 #endif // CATCH_CONFIG_NEW_CAPTURE 12179 #if defined(CATCH_CONFIG_NEW_CAPTURE) 12180 #if defined(_MSC_VER) 12193 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN) 12194 bool isnan(
float f) {
12195 return std::isnan(f);
12197 bool isnan(
double d) {
12198 return std::isnan(d);
12202 bool isnan(
float f) {
12203 return std::_isnan(f);
12205 bool isnan(
double d) {
12206 return std::_isnan(d);
12218 #if defined(_MSC_VER) 12219 #pragma warning(push) 12220 #pragma warning(disable:4146) // we negate uint32 during the rotate 12223 uint32_t rotate_right(uint32_t val, uint32_t count) {
12224 const uint32_t mask = 31;
12226 return (val >> count) | (val << (-count & mask));
12229 #if defined(_MSC_VER) 12230 #pragma warning(pop) 12235 SimplePcg32::SimplePcg32(result_type seed_) {
12239 void SimplePcg32::seed(result_type seed_) {
12246 void SimplePcg32::discard(uint64_t skip) {
12249 for (uint64_t s = 0; s < skip; ++s) {
12250 static_cast<void>((*this)());
12254 SimplePcg32::result_type SimplePcg32::operator()() {
12256 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12257 const auto output = rotate_right(xorshifted, m_state >> 59u);
12260 m_state = m_state * 6364136223846793005ULL + s_inc;
12266 return lhs.m_state == rhs.m_state;
12270 return lhs.m_state != rhs.m_state;
12280 #include <algorithm> 12288 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases );
12291 bool matchTest(
TestCase const& testCase, TestSpec
const& testSpec,
IConfig const& config );
12293 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12295 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
12296 std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config );
12300 virtual ~TestRegistry() =
default;
12302 virtual void registerTest(
TestCase const& testCase );
12304 std::vector<TestCase>
const& getAllTests()
const override;
12305 std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const override;
12308 std::vector<TestCase> m_functions;
12309 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12310 mutable std::vector<TestCase> m_sortedFunctions;
12311 std::size_t m_unnamedCount = 0;
12312 std::ios_base::Init m_ostreamInit;
12318 void(*m_testAsFunction)();
12320 TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept;
12322 void invoke()
const override;
12325 std::string extractClassName(
StringRef const& classOrQualifiedMethodName );
12338 class ReporterRegistry :
public IReporterRegistry {
12342 ~ReporterRegistry()
override;
12344 IStreamingReporterPtr create( std::string
const& name, IConfigPtr
const& config )
const override;
12346 void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory );
12347 void registerListener( IReporterFactoryPtr
const& factory );
12349 FactoryMap
const& getFactories()
const override;
12350 Listeners
const& getListeners()
const override;
12353 FactoryMap m_factories;
12354 Listeners m_listeners;
12381 class TagAliasRegistry :
public ITagAliasRegistry {
12383 ~TagAliasRegistry()
override;
12384 TagAlias
const* find( std::string
const& alias )
const override;
12385 std::string expandAliases( std::string
const& unexpandedTestSpec )
const override;
12386 void add( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo );
12389 std::map<std::string, TagAlias> m_registry;
12398 #include <exception> 12402 class StartupExceptionRegistry {
12403 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 12405 void add(std::exception_ptr
const& exception) noexcept;
12406 std::vector<std::exception_ptr>
const& getExceptions()
const noexcept;
12408 std::vector<std::exception_ptr> m_exceptions;
12419 struct ISingleton {
12420 virtual ~ISingleton();
12423 void addSingleton( ISingleton* singleton );
12424 void cleanupSingletons();
12426 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12427 class Singleton : SingletonImplT,
public ISingleton {
12429 static auto getInternal() -> Singleton* {
12430 static Singleton* s_instance =
nullptr;
12431 if( !s_instance ) {
12432 s_instance =
new Singleton;
12433 addSingleton( s_instance );
12439 static auto get() -> InterfaceT
const& {
12440 return *getInternal();
12442 static auto getMutable() -> MutableInterfaceT& {
12443 return *getInternal();
12458 RegistryHub() =
default;
12459 IReporterRegistry
const& getReporterRegistry()
const override {
12460 return m_reporterRegistry;
12463 return m_testCaseRegistry;
12466 return m_exceptionTranslatorRegistry;
12468 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
12469 return m_tagAliasRegistry;
12471 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12472 return m_exceptionRegistry;
12476 void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory )
override {
12477 m_reporterRegistry.registerReporter( name, factory );
12479 void registerListener( IReporterFactoryPtr
const& factory )
override {
12480 m_reporterRegistry.registerListener( factory );
12482 void registerTest(
TestCase const& testInfo )
override {
12483 m_testCaseRegistry.registerTest( testInfo );
12486 m_exceptionTranslatorRegistry.registerTranslator( translator );
12488 void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo )
override {
12489 m_tagAliasRegistry.add( alias, tag, lineInfo );
12491 void registerStartupException() noexcept
override {
12492 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 12493 m_exceptionRegistry.add(std::current_exception());
12495 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12499 return m_enumValuesRegistry;
12503 TestRegistry m_testCaseRegistry;
12504 ReporterRegistry m_reporterRegistry;
12505 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12506 TagAliasRegistry m_tagAliasRegistry;
12507 StartupExceptionRegistry m_exceptionRegistry;
12508 Detail::EnumValuesRegistry m_enumValuesRegistry;
12512 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12515 return RegistryHubSingleton::get();
12518 return RegistryHubSingleton::getMutable();
12521 cleanupSingletons();
12524 std::string translateActiveException() {
12525 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12534 ReporterRegistry::~ReporterRegistry() =
default;
12536 IStreamingReporterPtr ReporterRegistry::create( std::string
const& name, IConfigPtr
const& config )
const {
12537 auto it = m_factories.find( name );
12538 if( it == m_factories.end() )
12540 return it->second->create( ReporterConfig( config ) );
12543 void ReporterRegistry::registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory ) {
12544 m_factories.emplace(name, factory);
12546 void ReporterRegistry::registerListener( IReporterFactoryPtr
const& factory ) {
12547 m_listeners.push_back( factory );
12550 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12551 return m_factories;
12553 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12554 return m_listeners;
12563 bool isOk( ResultWas::OfType resultType ) {
12564 return ( resultType & ResultWas::FailureBit ) == 0;
12566 bool isJustInfo(
int flags ) {
12567 return flags == ResultWas::Info;
12570 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12571 return static_cast<ResultDisposition::Flags
>(
static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12574 bool shouldContinueOnFailure(
int flags ) {
return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
12575 bool shouldSuppressFailure(
int flags ) {
return ( flags & ResultDisposition::SuppressFail ) != 0; }
12582 #include <algorithm> 12587 namespace Generators {
12589 GeneratorBasePtr m_generator;
12591 GeneratorTracker( TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12592 : TrackerBase( nameAndLocation, ctx, parent )
12594 ~GeneratorTracker();
12596 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation
const& nameAndLocation ) {
12597 std::shared_ptr<GeneratorTracker> tracker;
12599 ITracker& currentTracker = ctx.currentTracker();
12611 if (currentTracker.nameAndLocation() == nameAndLocation) {
12612 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12613 assert(thisTracker);
12614 assert(thisTracker->isGeneratorTracker());
12615 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12616 }
else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12617 assert( childTracker );
12618 assert( childTracker->isGeneratorTracker() );
12619 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12621 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12622 currentTracker.addChild( tracker );
12625 if( !tracker->isComplete() ) {
12633 bool isGeneratorTracker()
const override {
return true; }
12634 auto hasGenerator()
const ->
bool override {
12635 return !!m_generator;
12637 void close()
override {
12638 TrackerBase::close();
12646 const bool should_wait_for_child = [&]() {
12648 if ( m_children.empty() ) {
12653 m_children.begin(),
12655 []( TestCaseTracking::ITrackerPtr tracker ) {
12656 return tracker->hasStarted();
12657 } ) != m_children.end() ) {
12664 auto* parent = m_parent;
12667 while ( !parent->isSectionTracker() ) {
12668 parent = &( parent->parent() );
12671 "Missing root (test case) level section" );
12673 auto const& parentSection =
12674 static_cast<SectionTracker&
>( *parent );
12675 auto const& filters = parentSection.getFilters();
12677 if ( filters.empty() ) {
12681 for (
auto const& child : m_children ) {
12682 if ( child->isSectionTracker() &&
12683 std::find( filters.begin(),
12685 static_cast<SectionTracker&
>( *child )
12686 .trimmedName() ) !=
12698 if ( should_wait_for_child ||
12699 ( m_runState == CompletedSuccessfully &&
12700 m_generator->next() ) ) {
12701 m_children.clear();
12702 m_runState = Executing;
12707 auto getGenerator()
const -> GeneratorBasePtr
const&
override {
12708 return m_generator;
12710 void setGenerator( GeneratorBasePtr&& generator )
override {
12711 m_generator = std::move( generator );
12714 GeneratorTracker::~GeneratorTracker() {}
12717 RunContext::RunContext(IConfigPtr
const& _config, IStreamingReporterPtr&& reporter)
12718 : m_runInfo(_config->name()),
12719 m_context(getCurrentMutableContext()),
12721 m_reporter(std::move(reporter)),
12723 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12725 m_context.setRunner(
this);
12726 m_context.setConfig(m_config);
12727 m_context.setResultCapture(
this);
12728 m_reporter->testRunStarting(m_runInfo);
12731 RunContext::~RunContext() {
12732 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12735 void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12736 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12739 void RunContext::testGroupEnded(std::string
const& testSpec,
Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12740 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12744 Totals prevTotals = m_totals;
12746 std::string redirectedCout;
12747 std::string redirectedCerr;
12749 auto const& testInfo = testCase.getTestCaseInfo();
12751 m_reporter->testCaseStarting(testInfo);
12753 m_activeTestCase = &testCase;
12755 ITracker& rootTracker = m_trackerContext.startRun();
12756 assert(rootTracker.isSectionTracker());
12757 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12759 m_trackerContext.startCycle();
12760 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12761 runCurrentTest(redirectedCout, redirectedCerr);
12762 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12764 Totals deltaTotals = m_totals.delta(prevTotals);
12765 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12766 deltaTotals.assertions.failed++;
12767 deltaTotals.testCases.passed--;
12768 deltaTotals.testCases.failed++;
12770 m_totals.testCases += deltaTotals.testCases;
12771 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12777 m_activeTestCase =
nullptr;
12778 m_testCaseTracker =
nullptr;
12780 return deltaTotals;
12783 IConfigPtr RunContext::config()
const {
12787 IStreamingReporter& RunContext::reporter()
const {
12788 return *m_reporter;
12791 void RunContext::assertionEnded(AssertionResult
const & result) {
12792 if (result.getResultType() == ResultWas::Ok) {
12793 m_totals.assertions.passed++;
12794 m_lastAssertionPassed =
true;
12795 }
else if (!result.isOk()) {
12796 m_lastAssertionPassed =
false;
12797 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12798 m_totals.assertions.failedButOk++;
12800 m_totals.assertions.failed++;
12803 m_lastAssertionPassed =
true;
12808 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12810 if (result.getResultType() != ResultWas::Warning)
12811 m_messageScopes.clear();
12814 resetAssertionInfo();
12815 m_lastResult = result;
12817 void RunContext::resetAssertionInfo() {
12818 m_lastAssertionInfo.macroName =
StringRef();
12819 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12822 bool RunContext::sectionStarted(
SectionInfo const & sectionInfo,
Counts & assertions) {
12823 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12824 if (!sectionTracker.isOpen())
12826 m_activeSections.push_back(§ionTracker);
12828 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12830 m_reporter->sectionStarting(sectionInfo);
12832 assertions = m_totals.assertions;
12837 using namespace Generators;
12838 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12839 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12840 m_lastAssertionInfo.lineInfo = lineInfo;
12844 bool RunContext::testForMissingAssertions(
Counts& assertions) {
12845 if (assertions.total() != 0)
12847 if (!m_config->warnAboutMissingAssertions())
12849 if (m_trackerContext.currentTracker().hasChildren())
12851 m_totals.assertions.failed++;
12852 assertions.failed++;
12857 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12858 bool missingAssertions = testForMissingAssertions(assertions);
12860 if (!m_activeSections.empty()) {
12861 m_activeSections.back()->close();
12862 m_activeSections.pop_back();
12865 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12866 m_messages.clear();
12867 m_messageScopes.clear();
12870 void RunContext::sectionEndedEarly(
SectionEndInfo const & endInfo) {
12871 if (m_unfinishedSections.empty())
12872 m_activeSections.back()->fail();
12874 m_activeSections.back()->close();
12875 m_activeSections.pop_back();
12877 m_unfinishedSections.push_back(endInfo);
12880 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 12881 void RunContext::benchmarkPreparing(std::string
const& name) {
12882 m_reporter->benchmarkPreparing(name);
12884 void RunContext::benchmarkStarting( BenchmarkInfo
const& info ) {
12885 m_reporter->benchmarkStarting( info );
12887 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12888 m_reporter->benchmarkEnded( stats );
12890 void RunContext::benchmarkFailed(std::string
const & error) {
12891 m_reporter->benchmarkFailed(error);
12893 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 12895 void RunContext::pushScopedMessage(
MessageInfo const & message) {
12896 m_messages.push_back(message);
12899 void RunContext::popScopedMessage(
MessageInfo const & message) {
12900 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12903 void RunContext::emplaceUnscopedMessage(
MessageBuilder const& builder ) {
12904 m_messageScopes.emplace_back( builder );
12907 std::string RunContext::getCurrentTestName()
const {
12908 return m_activeTestCase
12909 ? m_activeTestCase->getTestCaseInfo().name
12913 const AssertionResult * RunContext::getLastResult()
const {
12914 return &(*m_lastResult);
12917 void RunContext::exceptionEarlyReported() {
12918 m_shouldReportUnexpected =
false;
12921 void RunContext::handleFatalErrorCondition(
StringRef message ) {
12923 m_reporter->fatalErrorEncountered(message);
12927 AssertionResultData tempResult( ResultWas::FatalErrorCondition, {
false } );
12928 tempResult.message =
static_cast<std::string
>(message);
12929 AssertionResult result(m_lastAssertionInfo, tempResult);
12931 assertionEnded(result);
12933 handleUnfinishedSections();
12936 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12937 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12940 assertions.failed = 1;
12941 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12942 m_reporter->sectionEnded(testCaseSectionStats);
12944 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12947 deltaTotals.testCases.failed = 1;
12948 deltaTotals.assertions.failed = 1;
12949 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12954 m_totals.testCases.failed++;
12955 testGroupEnded(std::string(), m_totals, 1, 1);
12956 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12959 bool RunContext::lastAssertionPassed() {
12960 return m_lastAssertionPassed;
12963 void RunContext::assertionPassed() {
12964 m_lastAssertionPassed =
true;
12965 ++m_totals.assertions.passed;
12966 resetAssertionInfo();
12967 m_messageScopes.clear();
12970 bool RunContext::aborting()
const {
12971 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12974 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12975 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12976 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12977 m_reporter->sectionStarting(testCaseSection);
12978 Counts prevAssertions = m_totals.assertions;
12979 double duration = 0;
12980 m_shouldReportUnexpected =
true;
12981 m_lastAssertionInfo = {
"TEST_CASE"_sr, testCaseInfo.lineInfo,
StringRef(), ResultDisposition::Normal };
12983 seedRng(*m_config);
12987 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12988 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) 12989 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12992 invokeActiveTestCase();
12994 OutputRedirect r(redirectedCout, redirectedCerr);
12996 invokeActiveTestCase();
13000 invokeActiveTestCase();
13002 duration = timer.getElapsedSeconds();
13005 } CATCH_CATCH_ALL {
13008 if( m_shouldReportUnexpected ) {
13010 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
13013 Counts assertions = m_totals.assertions - prevAssertions;
13014 bool missingAssertions = testForMissingAssertions(assertions);
13016 m_testCaseTracker->close();
13017 handleUnfinishedSections();
13018 m_messages.clear();
13019 m_messageScopes.clear();
13021 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13022 m_reporter->sectionEnded(testCaseSectionStats);
13025 void RunContext::invokeActiveTestCase() {
13026 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13027 m_activeTestCase->invoke();
13030 void RunContext::handleUnfinishedSections() {
13033 for (
auto it = m_unfinishedSections.rbegin(),
13034 itEnd = m_unfinishedSections.rend();
13038 m_unfinishedSections.clear();
13041 void RunContext::handleExpr(
13046 m_reporter->assertionStarting( info );
13048 bool negated = isFalseTest( info.resultDisposition );
13049 bool result = expr.getResult() != negated;
13052 if (!m_includeSuccessfulResults) {
13056 reportExpr(info, ResultWas::Ok, &expr, negated);
13060 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
13061 populateReaction( reaction );
13064 void RunContext::reportExpr(
13066 ResultWas::OfType resultType,
13070 m_lastAssertionInfo = info;
13071 AssertionResultData data( resultType,
LazyExpression( negated ) );
13073 AssertionResult assertionResult{ info, data };
13074 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13076 assertionEnded( assertionResult );
13079 void RunContext::handleMessage(
13081 ResultWas::OfType resultType,
13085 m_reporter->assertionStarting( info );
13087 m_lastAssertionInfo = info;
13089 AssertionResultData data( resultType,
LazyExpression(
false ) );
13090 data.message =
static_cast<std::string
>(message);
13091 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13092 assertionEnded( assertionResult );
13093 if( !assertionResult.isOk() )
13094 populateReaction( reaction );
13096 void RunContext::handleUnexpectedExceptionNotThrown(
13100 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13103 void RunContext::handleUnexpectedInflightException(
13105 std::string
const& message,
13108 m_lastAssertionInfo = info;
13110 AssertionResultData data( ResultWas::ThrewException,
LazyExpression(
false ) );
13111 data.message = message;
13112 AssertionResult assertionResult{ info, data };
13113 assertionEnded( assertionResult );
13114 populateReaction( reaction );
13118 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13119 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13122 void RunContext::handleIncomplete(
13125 m_lastAssertionInfo = info;
13127 AssertionResultData data( ResultWas::ThrewException,
LazyExpression(
false ) );
13128 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13129 AssertionResult assertionResult{ info, data };
13130 assertionEnded( assertionResult );
13132 void RunContext::handleNonExpr(
13134 ResultWas::OfType resultType,
13137 m_lastAssertionInfo = info;
13139 AssertionResultData data( resultType,
LazyExpression(
false ) );
13140 AssertionResult assertionResult{ info, data };
13141 assertionEnded( assertionResult );
13143 if( !assertionResult.isOk() )
13144 populateReaction( reaction );
13148 if (
auto* capture = getCurrentContext().getResultCapture())
13151 CATCH_INTERNAL_ERROR(
"No result capture instance");
13154 void seedRng(
IConfig const& config) {
13155 if (config.rngSeed() != 0) {
13156 std::srand(config.rngSeed());
13157 rng().seed(config.rngSeed());
13161 unsigned int rngSeed() {
13162 return getCurrentContext().getConfig()->rngSeed();
13173 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13178 Section::~Section() {
13179 if( m_sectionIncluded ) {
13180 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13181 if( uncaught_exceptions() )
13182 getResultCapture().sectionEndedEarly( endInfo );
13184 getResultCapture().sectionEnded( endInfo );
13189 Section::operator bool()
const {
13190 return m_sectionIncluded;
13199 SectionInfo::SectionInfo
13201 std::string
const& _name )
13203 lineInfo( _lineInfo )
13220 ~Session()
override;
13222 void showHelp()
const;
13223 void libIdentify();
13225 int applyCommandLine(
int argc,
char const *
const * argv );
13226 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13227 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13230 void useConfigData( ConfigData
const& configData );
13232 template<
typename CharT>
13233 int run(
int argc, CharT
const *
const argv[]) {
13234 if (m_startupExceptions)
13236 int returnCode = applyCommandLine(argc, argv);
13237 if (returnCode == 0)
13238 returnCode = run();
13244 clara::Parser
const& cli()
const;
13245 void cli( clara::Parser
const& newParser );
13246 ConfigData& configData();
13251 clara::Parser m_cli;
13252 ConfigData m_configData;
13253 std::shared_ptr<Config> m_config;
13254 bool m_startupExceptions =
false;
13268 Version( Version
const& ) =
delete;
13269 Version& operator=( Version
const& ) =
delete;
13270 Version(
unsigned int _majorVersion,
13271 unsigned int _minorVersion,
13272 unsigned int _patchNumber,
13273 char const *
const _branchName,
13274 unsigned int _buildNumber );
13276 unsigned int const majorVersion;
13277 unsigned int const minorVersion;
13278 unsigned int const patchNumber;
13281 char const *
const branchName;
13282 unsigned int const buildNumber;
13284 friend std::ostream& operator << ( std::ostream& os, Version
const& version );
13287 Version
const& libraryVersion();
13294 #include <iterator> 13299 const int MaxExitCode = 255;
13301 IStreamingReporterPtr createReporter(std::string
const& reporterName, IConfigPtr
const& config) {
13302 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13303 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13308 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13309 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13310 return createReporter(config->getReporterName(), config);
13318 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13319 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13320 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13321 for (
auto const& listener : listeners) {
13322 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13324 multi.addReporter(createReporter(config->getReporterName(), config));
13330 explicit TestGroup(std::shared_ptr<Config>
const& config)
13332 , m_context{config, makeReporter(config)}
13334 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13335 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13336 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13338 if (m_matches.empty() && invalidArgs.empty()) {
13339 for (
auto const&
test : allTestCases)
13340 if (!
test.isHidden())
13341 m_tests.emplace(&
test);
13343 for (
auto const& match : m_matches)
13344 m_tests.insert(match.tests.begin(), match.tests.end());
13349 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13351 m_context.testGroupStarting(m_config->name(), 1, 1);
13352 for (
auto const& testCase : m_tests) {
13353 if (!m_context.aborting())
13354 totals += m_context.runTest(*testCase);
13356 m_context.reporter().skipTest(*testCase);
13359 for (
auto const& match : m_matches) {
13360 if (match.tests.empty()) {
13361 m_context.reporter().noMatchingTestCases(match.name);
13366 if (!invalidArgs.empty()) {
13367 for (
auto const& invalidArg: invalidArgs)
13368 m_context.reporter().reportInvalidArguments(invalidArg);
13371 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13376 using Tests = std::set<TestCase const*>;
13378 std::shared_ptr<Config> m_config;
13379 RunContext m_context;
13381 TestSpec::Matches m_matches;
13385 auto& tests =
const_cast<std::vector<TestCase>&
>(getAllTestCasesSorted(config));
13386 for (
auto& testCase : tests) {
13387 auto tags = testCase.tags;
13389 std::string filename = testCase.lineInfo.file;
13390 auto lastSlash = filename.find_last_of(
"\\/");
13391 if (lastSlash != std::string::npos) {
13392 filename.erase(0, lastSlash);
13397 filename.insert(0,
"#");
13400 auto lastDot = filename.find_last_of(
'.');
13401 if (lastDot != std::string::npos) {
13402 filename.erase(lastDot);
13405 tags.push_back(std::move(filename));
13406 setTags(testCase, tags);
13412 Session::Session() {
13413 static bool alreadyInstantiated =
false;
13414 if( alreadyInstantiated ) {
13415 CATCH_TRY { CATCH_INTERNAL_ERROR(
"Only one instance of Catch::Session can ever be used" ); }
13416 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13420 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13421 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13422 if ( !exceptions.empty() ) {
13424 getCurrentMutableContext().setConfig(m_config);
13426 m_startupExceptions =
true;
13427 Colour colourGuard( Colour::Red );
13428 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13430 for (
const auto& ex_ptr : exceptions ) {
13432 std::rethrow_exception(ex_ptr);
13433 }
catch ( std::exception
const& ex ) {
13434 Catch::cerr() << Column( ex.what() ).indent(2) <<
'\n';
13440 alreadyInstantiated =
true;
13441 m_cli = makeCommandLineParser( m_configData );
13443 Session::~Session() {
13447 void Session::showHelp()
const {
13449 <<
"\nCatch v" << libraryVersion() <<
"\n" 13450 << m_cli << std::endl
13451 <<
"For more detailed usage please see the project docs\n" << std::endl;
13453 void Session::libIdentify() {
13455 << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n" 13456 << std::left << std::setw(16) <<
"category: " <<
"testframework\n" 13457 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n" 13458 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13461 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13462 if( m_startupExceptions )
13465 auto result = m_cli.parse( clara::Args( argc, argv ) );
13468 getCurrentMutableContext().setConfig(m_config);
13470 << Colour( Colour::Red )
13471 <<
"\nError(s) in input:\n" 13472 << Column( result.errorMessage() ).indent( 2 )
13474 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13475 return MaxExitCode;
13478 if( m_configData.showHelp )
13480 if( m_configData.libIdentify )
13486 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE) 13487 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13489 char **utf8Argv =
new char *[ argc ];
13491 for (
int i = 0; i < argc; ++i ) {
13492 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr );
13494 utf8Argv[ i ] =
new char[ bufSize ];
13496 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13499 int returnCode = applyCommandLine( argc, utf8Argv );
13501 for (
int i = 0; i < argc; ++i )
13502 delete [] utf8Argv[ i ];
13504 delete [] utf8Argv;
13510 void Session::useConfigData( ConfigData
const& configData ) {
13511 m_configData = configData;
13515 int Session::run() {
13516 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13517 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13518 static_cast<void>(std::getchar());
13520 int exitCode = runInternal();
13521 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13522 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13523 static_cast<void>(std::getchar());
13528 clara::Parser
const& Session::cli()
const {
13531 void Session::cli( clara::Parser
const& newParser ) {
13534 ConfigData& Session::configData() {
13535 return m_configData;
13537 Config& Session::config() {
13539 m_config = std::make_shared<Config>( m_configData );
13543 int Session::runInternal() {
13544 if( m_startupExceptions )
13547 if (m_configData.showHelp || m_configData.libIdentify) {
13554 seedRng( *m_config );
13556 if( m_configData.filenamesAsTags )
13557 applyFilenamesAsTags( *m_config );
13561 return static_cast<int>( *listed );
13563 TestGroup tests { m_config };
13564 auto const totals = tests.execute();
13566 if( m_config->warnAboutNoTests() && totals.error == -1 )
13572 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13574 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13575 catch( std::exception& ex ) {
13576 Catch::cerr() << ex.what() << std::endl;
13577 return MaxExitCode;
13591 static auto getSingletons() -> std::vector<ISingleton*>*& {
13592 static std::vector<ISingleton*>* g_singletons =
nullptr;
13593 if( !g_singletons )
13594 g_singletons =
new std::vector<ISingleton*>();
13595 return g_singletons;
13599 ISingleton::~ISingleton() {}
13601 void addSingleton(ISingleton* singleton ) {
13602 getSingletons()->push_back( singleton );
13604 void cleanupSingletons() {
13605 auto& singletons = getSingletons();
13606 for(
auto singleton : *singletons )
13609 singletons =
nullptr;
13616 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 13618 void StartupExceptionRegistry::add( std::exception_ptr
const& exception ) noexcept {
13620 m_exceptions.push_back(exception);
13621 } CATCH_CATCH_ALL {
13627 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions()
const noexcept {
13628 return m_exceptions;
13637 #include <iostream> 13645 Catch::IStream::~IStream() =
default;
13647 namespace Detail {
namespace {
13648 template<
typename WriterF, std::
size_t bufferSize=256>
13649 class StreamBufImpl :
public std::streambuf {
13650 char data[bufferSize];
13655 setp( data, data +
sizeof(data) );
13658 ~StreamBufImpl() noexcept {
13659 StreamBufImpl::sync();
13663 int overflow(
int c )
override {
13667 if( pbase() == epptr() )
13668 m_writer( std::string( 1, static_cast<char>( c ) ) );
13670 sputc( static_cast<char>( c ) );
13675 int sync()
override {
13676 if( pbase() != pptr() ) {
13677 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13678 setp( pbase(), epptr() );
13686 struct OutputDebugWriter {
13688 void operator()( std::string
const&str ) {
13689 writeToDebugConsole( str );
13695 class FileStream :
public IStream {
13696 mutable std::ofstream m_ofs;
13699 m_ofs.open( filename.c_str() );
13700 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13702 ~FileStream()
override =
default;
13704 std::ostream& stream()
const override {
13711 class CoutStream :
public IStream {
13712 mutable std::ostream m_os;
13716 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13717 ~CoutStream()
override =
default;
13720 std::ostream& stream()
const override {
return m_os; }
13725 class DebugOutStream :
public IStream {
13726 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13727 mutable std::ostream m_os;
13730 : m_streamBuf(
new StreamBufImpl<OutputDebugWriter>() ),
13731 m_os( m_streamBuf.get() )
13734 ~DebugOutStream()
override =
default;
13737 std::ostream& stream()
const override {
return m_os; }
13745 if( filename.empty() )
13746 return new Detail::CoutStream();
13747 else if( filename[0] ==
'%' ) {
13748 if( filename ==
"%debug" )
13749 return new Detail::DebugOutStream();
13751 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13754 return new Detail::FileStream( filename );
13758 struct StringStreams {
13759 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13760 std::vector<std::size_t> m_unused;
13761 std::ostringstream m_referenceStream;
13763 auto add() -> std::size_t {
13764 if( m_unused.empty() ) {
13765 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13766 return m_streams.size()-1;
13769 auto index = m_unused.back();
13770 m_unused.pop_back();
13775 void release( std::size_t index ) {
13776 m_streams[index]->copyfmt( m_referenceStream );
13777 m_unused.push_back(index);
13781 ReusableStringStream::ReusableStringStream()
13782 : m_index( Singleton<StringStreams>::getMutable().add() ),
13783 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].
get() )
13786 ReusableStringStream::~ReusableStringStream() {
13787 static_cast<std::ostringstream*
>( m_oss )->str(
"");
13789 Singleton<StringStreams>::getMutable().release( m_index );
13792 auto ReusableStringStream::str()
const -> std::string {
13793 return static_cast<std::ostringstream*
>( m_oss )->str();
13798 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions 13799 std::ostream& cout() {
return std::cout; }
13800 std::ostream& cerr() {
return std::cerr; }
13801 std::ostream& clog() {
return std::clog; }
13807 #include <algorithm> 13816 char toLowerCh(
char c) {
13817 return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13821 bool startsWith( std::string
const& s, std::string
const& prefix ) {
13822 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13824 bool startsWith( std::string
const& s,
char prefix ) {
13825 return !s.empty() && s[0] == prefix;
13827 bool endsWith( std::string
const& s, std::string
const& suffix ) {
13828 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13830 bool endsWith( std::string
const& s,
char suffix ) {
13831 return !s.empty() && s[s.size()-1] == suffix;
13833 bool contains( std::string
const& s, std::string
const& infix ) {
13834 return s.find( infix ) != std::string::npos;
13836 void toLowerInPlace( std::string& s ) {
13837 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13839 std::string toLower( std::string
const& s ) {
13840 std::string lc = s;
13841 toLowerInPlace( lc );
13844 std::string trim( std::string
const& str ) {
13845 static char const* whitespaceChars =
"\n\r\t ";
13846 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13847 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13849 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13853 const auto is_ws = [](
char c) {
13854 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r';
13856 size_t real_begin = 0;
13857 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13858 size_t real_end = ref.size();
13859 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13861 return ref.substr(real_begin, real_end - real_begin);
13864 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
13865 bool replaced =
false;
13866 std::size_t i = str.find( replaceThis );
13867 while( i != std::string::npos ) {
13869 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13870 if( i < str.size()-withThis.size() )
13871 i = str.find( replaceThis, i+withThis.size() );
13873 i = std::string::npos;
13878 std::vector<StringRef> splitStringRef(
StringRef str,
char delimiter ) {
13879 std::vector<StringRef> subStrings;
13880 std::size_t start = 0;
13881 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13882 if( str[pos] == delimiter ) {
13883 if( pos - start > 1 )
13884 subStrings.push_back( str.substr( start, pos-start ) );
13888 if( start < str.size() )
13889 subStrings.push_back( str.substr( start, str.size()-start ) );
13893 pluralise::pluralise( std::size_t count, std::string
const& label )
13894 : m_count( count ),
13898 std::ostream& operator << ( std::ostream& os,
pluralise const& pluraliser ) {
13899 os << pluraliser.m_count <<
' ' << pluraliser.m_label;
13900 if( pluraliser.m_count != 1 )
13909 #include <algorithm> 13915 StringRef::StringRef(
char const* rawChars ) noexcept
13916 :
StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13919 auto StringRef::c_str()
const ->
char const* {
13920 CATCH_ENFORCE(isNullTerminated(),
"Called StringRef::c_str() on a non-null-terminated instance");
13923 auto StringRef::data()
const noexcept ->
char const* {
13927 auto StringRef::substr( size_type start, size_type size )
const noexcept ->
StringRef {
13928 if (start < m_size) {
13929 return StringRef(m_start + start, (std::min)(m_size - start, size));
13934 auto StringRef::operator == (
StringRef const& other )
const noexcept ->
bool {
13935 return m_size == other.m_size
13936 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13939 auto operator << ( std::ostream& os,
StringRef const& str ) -> std::ostream& {
13940 return os.write(str.data(), str.size());
13943 auto operator+=( std::string& lhs,
StringRef const& rhs ) -> std::string& {
13944 lhs.append(rhs.data(), rhs.size());
13953 TagAlias::TagAlias(std::string
const & _tag,
SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13960 RegistrarForTagAliases::RegistrarForTagAliases(
char const* alias,
char const* tag,
SourceLineInfo const& lineInfo) {
13962 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13963 } CATCH_CATCH_ALL {
13965 getMutableRegistryHub().registerStartupException();
13977 TagAliasRegistry::~TagAliasRegistry() {}
13979 TagAlias
const* TagAliasRegistry::find( std::string
const& alias )
const {
13980 auto it = m_registry.find( alias );
13981 if( it != m_registry.end() )
13982 return &(it->second);
13987 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
13988 std::string expandedTestSpec = unexpandedTestSpec;
13989 for(
auto const& registryKvp : m_registry ) {
13990 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13991 if( pos != std::string::npos ) {
13992 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13993 registryKvp.second.tag +
13994 expandedTestSpec.substr( pos + registryKvp.first.size() );
13997 return expandedTestSpec;
14000 void TagAliasRegistry::add( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) {
14001 CATCH_ENFORCE( startsWith(alias,
"[@") && endsWith(alias,
']'),
14002 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
14004 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14005 "error: tag alias, '" << alias <<
"' already registered.\n" 14006 <<
"\tFirst seen at: " << find(alias)->lineInfo <<
"\n" 14007 <<
"\tRedefined at: " << lineInfo );
14010 ITagAliasRegistry::~ITagAliasRegistry() {}
14012 ITagAliasRegistry
const& ITagAliasRegistry::get() {
14013 return getRegistryHub().getTagAliasRegistry();
14021 #include <exception> 14022 #include <algorithm> 14028 TestCaseInfo::SpecialProperties parseSpecialTag( std::string
const& tag ) {
14029 if( startsWith( tag,
'.' ) ||
14031 return TestCaseInfo::IsHidden;
14032 else if( tag ==
"!throws" )
14033 return TestCaseInfo::Throws;
14034 else if( tag ==
"!shouldfail" )
14035 return TestCaseInfo::ShouldFail;
14036 else if( tag ==
"!mayfail" )
14037 return TestCaseInfo::MayFail;
14038 else if( tag ==
"!nonportable" )
14039 return TestCaseInfo::NonPortable;
14040 else if( tag ==
"!benchmark" )
14041 return static_cast<TestCaseInfo::SpecialProperties
>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
14043 return TestCaseInfo::None;
14045 bool isReservedTag( std::string
const& tag ) {
14046 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
14048 void enforceNotReservedTag( std::string
const& tag,
SourceLineInfo const& _lineInfo ) {
14049 CATCH_ENFORCE( !isReservedTag(tag),
14050 "Tag name: [" << tag <<
"] is not allowed.\n" 14051 <<
"Tag names starting with non alphanumeric characters are reserved\n" 14057 std::string
const& _className,
14061 bool isHidden =
false;
14064 std::vector<std::string> tags;
14065 std::string desc, tag;
14066 bool inTag =
false;
14067 for (
char c : nameAndTags.tags) {
14076 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14077 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14079 else if( prop == TestCaseInfo::None )
14080 enforceNotReservedTag( tag, _lineInfo );
14085 if (startsWith(tag,
'.') && tag.size() > 1) {
14088 tags.push_back( tag );
14098 tags.insert( tags.end(), {
".",
"!hide" } );
14101 TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
14102 return TestCase( _testCase, std::move(info) );
14105 void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14106 std::sort(begin(tags), end(tags));
14107 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14108 testCaseInfo.lcaseTags.clear();
14110 for(
auto const& tag : tags ) {
14111 std::string lcaseTag = toLower( tag );
14112 testCaseInfo.properties =
static_cast<TestCaseInfo::SpecialProperties
>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14113 testCaseInfo.lcaseTags.push_back( lcaseTag );
14115 testCaseInfo.tags = std::move(tags);
14118 TestCaseInfo::TestCaseInfo( std::string
const& _name,
14119 std::string
const& _className,
14120 std::string
const& _description,
14121 std::vector<std::string>
const& _tags,
14124 className( _className ),
14125 description( _description ),
14126 lineInfo( _lineInfo ),
14129 setTags( *
this, _tags );
14132 bool TestCaseInfo::isHidden()
const {
14133 return ( properties & IsHidden ) != 0;
14135 bool TestCaseInfo::throws()
const {
14136 return ( properties & Throws ) != 0;
14138 bool TestCaseInfo::okToFail()
const {
14139 return ( properties & (ShouldFail | MayFail ) ) != 0;
14141 bool TestCaseInfo::expectedToFail()
const {
14142 return ( properties & (ShouldFail ) ) != 0;
14145 std::string TestCaseInfo::tagsAsString()
const {
14148 std::size_t full_size = 2 * tags.size();
14149 for (
const auto& tag : tags) {
14150 full_size += tag.size();
14152 ret.reserve(full_size);
14153 for (
const auto& tag : tags) {
14154 ret.push_back(
'[');
14156 ret.push_back(
']');
14164 TestCase TestCase::withName( std::string
const& _newName )
const {
14166 other.name = _newName;
14170 void TestCase::invoke()
const {
14174 bool TestCase::operator == (
TestCase const& other )
const {
14175 return test.get() == other.test.get() &&
14176 name == other.name &&
14177 className == other.className;
14180 bool TestCase::operator < (
TestCase const& other )
const {
14181 return name < other.name;
14193 #include <algorithm> 14199 struct TestHasher {
14200 using hash_t = uint64_t;
14202 explicit TestHasher( hash_t hashSuffix ):
14203 m_hashSuffix{ hashSuffix } {}
14205 uint32_t operator()(
TestCase const& t )
const {
14207 const hash_t prime = 1099511628211u;
14208 hash_t hash = 14695981039346656037u;
14209 for (
const char c : t.name ) {
14213 hash ^= m_hashSuffix;
14215 const uint32_t low{
static_cast<uint32_t
>( hash ) };
14216 const uint32_t high{
static_cast<uint32_t
>( hash >> 32 ) };
14221 hash_t m_hashSuffix;
14225 std::vector<TestCase> sortTests(
IConfig const& config, std::vector<TestCase>
const& unsortedTestCases ) {
14226 switch( config.runOrder() ) {
14227 case RunTests::InDeclarationOrder:
14231 case RunTests::InLexicographicalOrder: {
14232 std::vector<TestCase> sorted = unsortedTestCases;
14233 std::sort( sorted.begin(), sorted.end() );
14237 case RunTests::InRandomOrder: {
14239 TestHasher h{ config.rngSeed() };
14241 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14242 std::vector<hashedTest> indexed_tests;
14243 indexed_tests.reserve( unsortedTestCases.size() );
14245 for (
auto const& testCase : unsortedTestCases) {
14246 indexed_tests.emplace_back(h(testCase), &testCase);
14249 std::sort(indexed_tests.begin(), indexed_tests.end(),
14250 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14251 if (lhs.first == rhs.first) {
14252 return lhs.second->name < rhs.second->name;
14254 return lhs.first < rhs.first;
14257 std::vector<TestCase> sorted;
14258 sorted.reserve( indexed_tests.size() );
14260 for (
auto const& hashed : indexed_tests) {
14261 sorted.emplace_back(*hashed.second);
14267 return unsortedTestCases;
14270 bool isThrowSafe(
TestCase const& testCase,
IConfig const& config ) {
14271 return !testCase.throws() || config.allowThrows();
14274 bool matchTest(
TestCase const& testCase, TestSpec
const& testSpec,
IConfig const& config ) {
14275 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14278 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14279 std::set<TestCase> seenFunctions;
14280 for(
auto const&
function : functions ) {
14281 auto prev = seenFunctions.insert(
function );
14282 CATCH_ENFORCE( prev.second,
14283 "error: TEST_CASE( \"" <<
function.name <<
"\" ) already defined.\n" 14284 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n" 14285 <<
"\tRedefined at " <<
function.getTestCaseInfo().lineInfo );
14289 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config ) {
14290 std::vector<TestCase> filtered;
14291 filtered.reserve( testCases.size() );
14292 for (
auto const& testCase : testCases) {
14293 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14294 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14295 filtered.push_back(testCase);
14300 std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config ) {
14301 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14304 void TestRegistry::registerTest(
TestCase const& testCase ) {
14305 std::string name = testCase.getTestCaseInfo().name;
14306 if( name.empty() ) {
14308 rss <<
"Anonymous test case " << ++m_unnamedCount;
14309 return registerTest( testCase.withName( rss.str() ) );
14311 m_functions.push_back( testCase );
14314 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14315 return m_functions;
14317 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted(
IConfig const& config )
const {
14318 if( m_sortedFunctions.empty() )
14319 enforceNoDuplicateTestCases( m_functions );
14321 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14322 m_sortedFunctions = sortTests( config, m_functions );
14323 m_currentSortOrder = config.runOrder();
14325 return m_sortedFunctions;
14329 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14331 void TestInvokerAsFunction::invoke()
const {
14332 m_testAsFunction();
14335 std::string extractClassName(
StringRef const& classOrQualifiedMethodName ) {
14336 std::string className(classOrQualifiedMethodName);
14337 if( startsWith( className,
'&' ) )
14339 std::size_t lastColons = className.rfind(
"::" );
14340 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14341 if( penultimateColons == std::string::npos )
14342 penultimateColons = 1;
14343 className = className.substr( penultimateColons, lastColons-penultimateColons );
14352 #include <algorithm> 14354 #include <stdexcept> 14358 #if defined(__clang__) 14359 # pragma clang diagnostic push 14360 # pragma clang diagnostic ignored "-Wexit-time-destructors" 14364 namespace TestCaseTracking {
14366 NameAndLocation::NameAndLocation( std::string
const& _name,
SourceLineInfo const& _location )
14368 location( _location )
14371 ITracker::~ITracker() =
default;
14373 ITracker& TrackerContext::startRun() {
14374 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}", CATCH_INTERNAL_LINEINFO ), *
this, nullptr );
14375 m_currentTracker =
nullptr;
14376 m_runState = Executing;
14377 return *m_rootTracker;
14380 void TrackerContext::endRun() {
14381 m_rootTracker.reset();
14382 m_currentTracker =
nullptr;
14383 m_runState = NotStarted;
14386 void TrackerContext::startCycle() {
14387 m_currentTracker = m_rootTracker.get();
14388 m_runState = Executing;
14390 void TrackerContext::completeCycle() {
14391 m_runState = CompletedCycle;
14394 bool TrackerContext::completedCycle()
const {
14395 return m_runState == CompletedCycle;
14397 ITracker& TrackerContext::currentTracker() {
14398 return *m_currentTracker;
14400 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14401 m_currentTracker = tracker;
14404 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14405 ITracker(nameAndLocation),
14410 bool TrackerBase::isComplete()
const {
14411 return m_runState == CompletedSuccessfully || m_runState == Failed;
14413 bool TrackerBase::isSuccessfullyCompleted()
const {
14414 return m_runState == CompletedSuccessfully;
14416 bool TrackerBase::isOpen()
const {
14417 return m_runState != NotStarted && !isComplete();
14419 bool TrackerBase::hasChildren()
const {
14420 return !m_children.empty();
14423 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14424 m_children.push_back( child );
14427 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14428 auto it = std::find_if( m_children.begin(), m_children.end(),
14429 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14431 tracker->nameAndLocation().location == nameAndLocation.location &&
14432 tracker->nameAndLocation().name == nameAndLocation.name;
14434 return( it != m_children.end() )
14438 ITracker& TrackerBase::parent() {
14439 assert( m_parent );
14443 void TrackerBase::openChild() {
14444 if( m_runState != ExecutingChildren ) {
14445 m_runState = ExecutingChildren;
14447 m_parent->openChild();
14451 bool TrackerBase::isSectionTracker()
const {
return false; }
14452 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14454 void TrackerBase::open() {
14455 m_runState = Executing;
14458 m_parent->openChild();
14461 void TrackerBase::close() {
14464 while( &m_ctx.currentTracker() != this )
14465 m_ctx.currentTracker().close();
14467 switch( m_runState ) {
14468 case NeedsAnotherRun:
14472 m_runState = CompletedSuccessfully;
14474 case ExecutingChildren:
14475 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const& t){
return t->isComplete(); }) )
14476 m_runState = CompletedSuccessfully;
14480 case CompletedSuccessfully:
14482 CATCH_INTERNAL_ERROR(
"Illogical state: " << m_runState );
14485 CATCH_INTERNAL_ERROR(
"Unknown state: " << m_runState );
14488 m_ctx.completeCycle();
14490 void TrackerBase::fail() {
14491 m_runState = Failed;
14493 m_parent->markAsNeedingAnotherRun();
14495 m_ctx.completeCycle();
14497 void TrackerBase::markAsNeedingAnotherRun() {
14498 m_runState = NeedsAnotherRun;
14501 void TrackerBase::moveToParent() {
14502 assert( m_parent );
14503 m_ctx.setCurrentTracker( m_parent );
14505 void TrackerBase::moveToThis() {
14506 m_ctx.setCurrentTracker(
this );
14509 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14510 : TrackerBase( nameAndLocation, ctx, parent ),
14511 m_trimmed_name(trim(nameAndLocation.name))
14514 while( !parent->isSectionTracker() )
14515 parent = &parent->parent();
14517 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14518 addNextFilters( parentSection.m_filters );
14522 bool SectionTracker::isComplete()
const {
14523 bool complete =
true;
14525 if (m_filters.empty()
14526 || m_filters[0] ==
"" 14527 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14528 complete = TrackerBase::isComplete();
14533 bool SectionTracker::isSectionTracker()
const {
return true; }
14535 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14536 std::shared_ptr<SectionTracker> section;
14538 ITracker& currentTracker = ctx.currentTracker();
14539 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14540 assert( childTracker );
14541 assert( childTracker->isSectionTracker() );
14542 section = std::static_pointer_cast<SectionTracker>( childTracker );
14545 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14546 currentTracker.addChild( section );
14548 if( !ctx.completedCycle() )
14549 section->tryOpen();
14553 void SectionTracker::tryOpen() {
14554 if( !isComplete() )
14558 void SectionTracker::addInitialFilters( std::vector<std::string>
const& filters ) {
14559 if( !filters.empty() ) {
14560 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14561 m_filters.emplace_back(
"");
14562 m_filters.emplace_back(
"");
14563 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14566 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14567 if( filters.size() > 1 )
14568 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14571 std::vector<std::string>
const& SectionTracker::getFilters()
const {
14575 std::string
const& SectionTracker::trimmedName()
const {
14576 return m_trimmed_name;
14581 using TestCaseTracking::ITracker;
14582 using TestCaseTracking::TrackerContext;
14583 using TestCaseTracking::SectionTracker;
14587 #if defined(__clang__) 14588 # pragma clang diagnostic pop 14595 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept ->
ITestInvoker* {
14596 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14599 NameAndTags::NameAndTags(
StringRef const& name_ ,
StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14603 getMutableRegistryHub()
14607 extractClassName( classOrMethod ),
14610 } CATCH_CATCH_ALL {
14612 getMutableRegistryHub().registerStartupException();
14616 AutoReg::~AutoReg() =
default;
14621 #include <algorithm> 14628 TestSpec::Pattern::Pattern( std::string
const& name )
14632 TestSpec::Pattern::~Pattern() =
default;
14634 std::string
const& TestSpec::Pattern::name()
const {
14638 TestSpec::NamePattern::NamePattern( std::string
const& name, std::string
const& filterString )
14639 : Pattern( filterString )
14640 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14643 bool TestSpec::NamePattern::matches(
TestCaseInfo const& testCase )
const {
14644 return m_wildcardPattern.matches( testCase.name );
14647 TestSpec::TagPattern::TagPattern( std::string
const& tag, std::string
const& filterString )
14648 : Pattern( filterString )
14649 , m_tag( toLower( tag ) )
14652 bool TestSpec::TagPattern::matches(
TestCaseInfo const& testCase )
const {
14653 return std::find(begin(testCase.lcaseTags),
14654 end(testCase.lcaseTags),
14655 m_tag) != end(testCase.lcaseTags);
14658 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14659 : Pattern( underlyingPattern->name() )
14660 , m_underlyingPattern( underlyingPattern )
14663 bool TestSpec::ExcludedPattern::matches(
TestCaseInfo const& testCase )
const {
14664 return !m_underlyingPattern->matches( testCase );
14667 bool TestSpec::Filter::matches(
TestCaseInfo const& testCase )
const {
14668 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const& p ){
return p->matches( testCase ); } );
14671 std::string TestSpec::Filter::name()
const {
14673 for(
auto const& p : m_patterns )
14678 bool TestSpec::hasFilters()
const {
14679 return !m_filters.empty();
14682 bool TestSpec::matches(
TestCaseInfo const& testCase )
const {
14683 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const& f ){
return f.matches( testCase ); } );
14686 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase>
const& testCases,
IConfig const& config )
const 14688 Matches matches( m_filters.size() );
14689 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter
const& filter ){
14690 std::vector<TestCase const*> currentMatches;
14691 for(
auto const&
test : testCases )
14692 if( isThrowSafe(
test, config ) && filter.matches(
test ) )
14693 currentMatches.emplace_back( &
test );
14694 return FilterMatch{ filter.name(), currentMatches };
14699 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14700 return (m_invalidArgs);
14709 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14711 TestSpecParser& TestSpecParser::parse( std::string
const& arg ) {
14713 m_exclusion =
false;
14714 m_arg = m_tagAliases->expandAliases( arg );
14715 m_escapeChars.clear();
14716 m_substring.reserve(m_arg.size());
14717 m_patternName.reserve(m_arg.size());
14718 m_realPatternPos = 0;
14720 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14722 if( !visitChar( m_arg[m_pos] ) ){
14723 m_testSpec.m_invalidArgs.push_back(arg);
14729 TestSpec TestSpecParser::testSpec() {
14733 bool TestSpecParser::visitChar(
char c ) {
14734 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14736 addCharToPattern(c);
14738 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14744 if( processNoneChar( c ) )
14748 processNameChar( c );
14752 addCharToPattern(c);
14757 if( processOtherChar( c ) )
14763 if( !isControlChar( c ) ) {
14764 m_patternName += c;
14765 m_realPatternPos++;
14771 bool TestSpecParser::processNoneChar(
char c ) {
14776 m_exclusion =
true;
14779 startNewMode( Tag );
14782 startNewMode( QuotedName );
14785 startNewMode( Name );
14789 void TestSpecParser::processNameChar(
char c ) {
14791 if( m_substring ==
"exclude:" )
14792 m_exclusion =
true;
14795 startNewMode( Tag );
14798 bool TestSpecParser::processOtherChar(
char c ) {
14799 if( !isControlChar( c ) )
14805 void TestSpecParser::startNewMode( Mode mode ) {
14808 void TestSpecParser::endMode() {
14812 return addNamePattern();
14814 return addTagPattern();
14816 revertBackToLastMode();
14820 return startNewMode( None );
14823 void TestSpecParser::escape() {
14825 m_mode = EscapedName;
14826 m_escapeChars.push_back(m_realPatternPos);
14828 bool TestSpecParser::isControlChar(
char c )
const {
14841 return c ==
'[' || c ==
']';
14845 void TestSpecParser::addFilter() {
14846 if( !m_currentFilter.m_patterns.empty() ) {
14847 m_testSpec.m_filters.push_back( m_currentFilter );
14848 m_currentFilter = TestSpec::Filter();
14852 void TestSpecParser::saveLastMode() {
14856 void TestSpecParser::revertBackToLastMode() {
14860 bool TestSpecParser::separate() {
14861 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14864 m_pos = m_arg.size();
14865 m_substring.clear();
14866 m_patternName.clear();
14867 m_realPatternPos = 0;
14875 std::string TestSpecParser::preprocessPattern() {
14876 std::string token = m_patternName;
14877 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14878 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14879 m_escapeChars.clear();
14880 if (startsWith(token,
"exclude:")) {
14881 m_exclusion =
true;
14882 token = token.substr(8);
14885 m_patternName.clear();
14886 m_realPatternPos = 0;
14891 void TestSpecParser::addNamePattern() {
14892 auto token = preprocessPattern();
14894 if (!token.empty()) {
14895 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14897 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14898 m_currentFilter.m_patterns.push_back(pattern);
14900 m_substring.clear();
14901 m_exclusion =
false;
14905 void TestSpecParser::addTagPattern() {
14906 auto token = preprocessPattern();
14908 if (!token.empty()) {
14911 if (token.size() > 1 && token[0] ==
'.') {
14912 token.erase(token.begin());
14913 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14915 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14917 m_currentFilter.m_patterns.push_back(pattern);
14920 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14923 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14925 m_currentFilter.m_patterns.push_back(pattern);
14927 m_substring.clear();
14928 m_exclusion =
false;
14932 TestSpec parseTestSpec( std::string
const& arg ) {
14933 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14942 static const uint64_t nanosecondsInSecond = 1000000000;
14946 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14947 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14951 auto estimateClockResolution() -> uint64_t {
14953 static const uint64_t iterations = 1000000;
14955 auto startTime = getCurrentNanosecondsSinceEpoch();
14957 for( std::size_t i = 0; i < iterations; ++i ) {
14960 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14962 ticks = getCurrentNanosecondsSinceEpoch();
14963 }
while( ticks == baseTicks );
14965 auto delta = ticks - baseTicks;
14971 if (ticks > startTime + 3 * nanosecondsInSecond) {
14972 return sum / ( i + 1u );
14978 return sum/iterations;
14981 auto getEstimatedClockResolution() -> uint64_t {
14982 static auto s_resolution = estimateClockResolution();
14983 return s_resolution;
14986 void Timer::start() {
14987 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14989 auto Timer::getElapsedNanoseconds()
const -> uint64_t {
14990 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14992 auto Timer::getElapsedMicroseconds()
const -> uint64_t {
14993 return getElapsedNanoseconds()/1000;
14995 auto Timer::getElapsedMilliseconds()
const ->
unsigned int {
14996 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14998 auto Timer::getElapsedSeconds()
const ->
double {
14999 return getElapsedMicroseconds()/1000000.0;
15006 #if defined(__clang__) 15007 # pragma clang diagnostic push 15008 # pragma clang diagnostic ignored "-Wexit-time-destructors" 15009 # pragma clang diagnostic ignored "-Wglobal-constructors" 15013 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) 15014 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER 15024 const std::string unprintableString =
"{?}";
15027 const int hexThreshold = 255;
15029 struct Endianness {
15030 enum Arch { Big, Little };
15032 static Arch which() {
15036 auto value = *
reinterpret_cast<char*
>(&one);
15037 return value ? Little : Big;
15042 std::string rawMemoryToString(
const void *
object, std::size_t size ) {
15044 int i = 0, end =
static_cast<int>( size ), inc = 1;
15045 if( Endianness::which() == Endianness::Little ) {
15050 unsigned char const *bytes =
static_cast<unsigned char const *
>(object);
15052 rss <<
"0x" << std::setfill(
'0') << std::hex;
15053 for( ; i != end; i += inc )
15054 rss << std::setw(2) <<
static_cast<unsigned>(bytes[i]);
15059 template<
typename T>
15060 std::string fpToString( T value,
int precision ) {
15061 if (Catch::isnan(value)) {
15066 rss << std::setprecision( precision )
15069 std::string d = rss.str();
15070 std::size_t i = d.find_last_not_of(
'0' );
15071 if( i != std::string::npos && i != d.size()-1 ) {
15074 d = d.substr( 0, i+1 );
15086 if (!getCurrentContext().getConfig()->showInvisibles()) {
15087 return '"' + str +
'"';
15090 std::string s(
"\"");
15091 for (
char c : str) {
15108 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW 15110 return ::Catch::Detail::stringify(std::string{ str });
15116 return ::Catch::Detail::stringify(std::string{ str });
15118 return{
"{null string}" };
15123 return ::Catch::Detail::stringify(std::string{ str });
15125 return{
"{null string}" };
15129 #ifdef CATCH_CONFIG_WCHAR 15132 s.reserve(wstr.size());
15133 for (
auto c : wstr) {
15134 s += (c <= 0xff) ? static_cast<char>(c) :
'?';
15136 return ::Catch::Detail::stringify(s);
15139 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW 15147 return ::Catch::Detail::stringify(std::wstring{ str });
15149 return{
"{null string}" };
15154 return ::Catch::Detail::stringify(std::wstring{ str });
15156 return{
"{null string}" };
15161 #if defined(CATCH_CONFIG_CPP17_BYTE) 15164 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15166 #endif // defined(CATCH_CONFIG_CPP17_BYTE) 15169 return ::Catch::Detail::stringify(static_cast<long long>(value));
15172 return ::Catch::Detail::stringify(static_cast<long long>(value));
15177 if (value > Detail::hexThreshold) {
15178 rss <<
" (0x" << std::hex << value <<
')';
15184 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15187 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15192 if (value > Detail::hexThreshold) {
15193 rss <<
" (0x" << std::hex << value <<
')';
15199 return b ?
"true" :
"false";
15203 if (value ==
'\r') {
15205 }
else if (value ==
'\f') {
15207 }
else if (value ==
'\n') {
15209 }
else if (value ==
'\t') {
15211 }
else if (
'\0' <= value && value <
' ') {
15212 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15214 char chstr[] =
"' '";
15220 return ::Catch::Detail::stringify(static_cast<signed char>(c));
15223 return ::Catch::Detail::stringify(static_cast<char>(c));
15233 return fpToString(value, precision) +
'f';
15239 return fpToString(value, precision);
15242 std::string ratio_string<std::atto>::symbol() {
return "a"; }
15243 std::string ratio_string<std::femto>::symbol() {
return "f"; }
15244 std::string ratio_string<std::pico>::symbol() {
return "p"; }
15245 std::string ratio_string<std::nano>::symbol() {
return "n"; }
15246 std::string ratio_string<std::micro>::symbol() {
return "u"; }
15247 std::string ratio_string<std::milli>::symbol() {
return "m"; }
15251 #if defined(__clang__) 15252 # pragma clang diagnostic pop 15260 Counts Counts::operator - (
Counts const& other )
const {
15262 diff.passed = passed - other.passed;
15263 diff.failed = failed - other.failed;
15264 diff.failedButOk = failedButOk - other.failedButOk;
15269 passed += other.passed;
15270 failed += other.failed;
15271 failedButOk += other.failedButOk;
15275 std::size_t Counts::total()
const {
15276 return passed + failed + failedButOk;
15278 bool Counts::allPassed()
const {
15279 return failed == 0 && failedButOk == 0;
15281 bool Counts::allOk()
const {
15282 return failed == 0;
15285 Totals Totals::operator - (
Totals const& other )
const {
15287 diff.assertions = assertions - other.assertions;
15288 diff.testCases = testCases - other.testCases;
15293 assertions += other.assertions;
15294 testCases += other.testCases;
15298 Totals Totals::delta(
Totals const& prevTotals )
const {
15299 Totals diff = *
this - prevTotals;
15300 if( diff.assertions.failed > 0 )
15301 ++diff.testCases.failed;
15302 else if( diff.assertions.failedButOk > 0 )
15303 ++diff.testCases.failedButOk;
15305 ++diff.testCases.passed;
15322 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP 15323 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP 15325 #if defined(_MSC_VER) 15326 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer 15327 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 15331 #include <exception> 15333 #if defined(__cpp_lib_uncaught_exceptions) \ 15334 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15336 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 15337 #endif // __cpp_lib_uncaught_exceptions 15339 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \ 15340 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \ 15341 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15343 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS 15346 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP 15348 #include <exception> 15351 bool uncaught_exceptions() {
15352 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) 15354 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) 15355 return std::uncaught_exceptions() > 0;
15357 return std::uncaught_exception();
15369 (
unsigned int _majorVersion,
15370 unsigned int _minorVersion,
15371 unsigned int _patchNumber,
15372 char const *
const _branchName,
15373 unsigned int _buildNumber )
15374 : majorVersion( _majorVersion ),
15375 minorVersion( _minorVersion ),
15376 patchNumber( _patchNumber ),
15377 branchName( _branchName ),
15378 buildNumber( _buildNumber )
15381 std::ostream& operator << ( std::ostream& os, Version
const& version ) {
15382 os << version.majorVersion <<
'.' 15383 << version.minorVersion <<
'.' 15384 << version.patchNumber;
15386 if (version.branchName[0]) {
15387 os <<
'-' << version.branchName
15388 <<
'.' << version.buildNumber;
15393 Version
const& libraryVersion() {
15394 static Version version( 2, 13, 9,
"", 0 );
15404 WildcardPattern::WildcardPattern( std::string
const& pattern,
15405 CaseSensitive::Choice caseSensitivity )
15406 : m_caseSensitivity( caseSensitivity ),
15407 m_pattern( normaliseString( pattern ) )
15409 if( startsWith( m_pattern,
'*' ) ) {
15410 m_pattern = m_pattern.substr( 1 );
15411 m_wildcard = WildcardAtStart;
15413 if( endsWith( m_pattern,
'*' ) ) {
15414 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15415 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15419 bool WildcardPattern::matches( std::string
const& str )
const {
15420 switch( m_wildcard ) {
15422 return m_pattern == normaliseString( str );
15423 case WildcardAtStart:
15424 return endsWith( normaliseString( str ), m_pattern );
15425 case WildcardAtEnd:
15426 return startsWith( normaliseString( str ), m_pattern );
15427 case WildcardAtBothEnds:
15428 return contains( normaliseString( str ), m_pattern );
15430 CATCH_INTERNAL_ERROR(
"Unknown enum" );
15434 std::string WildcardPattern::normaliseString( std::string
const& str )
const {
15435 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15442 #include <type_traits> 15448 size_t trailingBytes(
unsigned char c) {
15449 if ((c & 0xE0) == 0xC0) {
15452 if ((c & 0xF0) == 0xE0) {
15455 if ((c & 0xF8) == 0xF0) {
15458 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15461 uint32_t headerValue(
unsigned char c) {
15462 if ((c & 0xE0) == 0xC0) {
15465 if ((c & 0xF0) == 0xE0) {
15468 if ((c & 0xF8) == 0xF0) {
15471 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15474 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15475 std::ios_base::fmtflags f(os.flags());
15477 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15478 <<
static_cast<int>(c);
15482 bool shouldNewline(XmlFormatting fmt) {
15483 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15486 bool shouldIndent(XmlFormatting fmt) {
15487 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15492 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15493 return static_cast<XmlFormatting
>(
15494 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15495 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15499 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15500 return static_cast<XmlFormatting
>(
15501 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15502 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15506 XmlEncode::XmlEncode( std::string
const& str, ForWhat forWhat )
15508 m_forWhat( forWhat )
15511 void XmlEncode::encodeTo( std::ostream& os )
const {
15515 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15516 unsigned char c = m_str[idx];
15518 case '<': os <<
"<";
break;
15519 case '&': os <<
"&";
break;
15523 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15530 if (m_forWhat == ForAttributes)
15541 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15542 hexEscapeChar(os, c);
15560 hexEscapeChar(os, c);
15564 auto encBytes = trailingBytes(c);
15566 if (idx + encBytes - 1 >= m_str.size()) {
15567 hexEscapeChar(os, c);
15574 uint32_t value = headerValue(c);
15575 for (std::size_t n = 1; n < encBytes; ++n) {
15576 unsigned char nc = m_str[idx + n];
15577 valid &= ((nc & 0xC0) == 0x80);
15578 value = (value << 6) | (nc & 0x3F);
15586 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15587 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15589 (value >= 0x110000)
15591 hexEscapeChar(os, c);
15596 for (std::size_t n = 0; n < encBytes; ++n) {
15597 os << m_str[idx + n];
15599 idx += encBytes - 1;
15605 std::ostream& operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15606 xmlEncode.encodeTo( os );
15610 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15611 : m_writer( writer ),
15615 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15616 : m_writer( other.m_writer ),
15619 other.m_writer =
nullptr;
15620 other.m_fmt = XmlFormatting::None;
15622 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15624 m_writer->endElement();
15626 m_writer = other.m_writer;
15627 other.m_writer =
nullptr;
15628 m_fmt = other.m_fmt;
15629 other.m_fmt = XmlFormatting::None;
15633 XmlWriter::ScopedElement::~ScopedElement() {
15635 m_writer->endElement(m_fmt);
15639 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string
const& text, XmlFormatting fmt ) {
15640 m_writer->writeText( text, fmt );
15644 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15646 writeDeclaration();
15649 XmlWriter::~XmlWriter() {
15650 while (!m_tags.empty()) {
15653 newlineIfNecessary();
15656 XmlWriter& XmlWriter::startElement( std::string
const& name, XmlFormatting fmt ) {
15658 newlineIfNecessary();
15659 if (shouldIndent(fmt)) {
15663 m_os <<
'<' << name;
15664 m_tags.push_back( name );
15665 m_tagIsOpen =
true;
15666 applyFormatting(fmt);
15670 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string
const& name, XmlFormatting fmt ) {
15671 ScopedElement scoped(
this, fmt );
15672 startElement( name, fmt );
15676 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15677 m_indent = m_indent.substr(0, m_indent.size() - 2);
15679 if( m_tagIsOpen ) {
15681 m_tagIsOpen =
false;
15683 newlineIfNecessary();
15684 if (shouldIndent(fmt)) {
15687 m_os <<
"</" << m_tags.back() <<
">";
15689 m_os << std::flush;
15690 applyFormatting(fmt);
15695 XmlWriter& XmlWriter::writeAttribute( std::string
const& name, std::string
const& attribute ) {
15696 if( !name.empty() && !attribute.empty() )
15697 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15701 XmlWriter& XmlWriter::writeAttribute( std::string
const& name,
bool attribute ) {
15702 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15706 XmlWriter& XmlWriter::writeText( std::string
const& text, XmlFormatting fmt) {
15707 if( !text.empty() ){
15708 bool tagWasOpen = m_tagIsOpen;
15710 if (tagWasOpen && shouldIndent(fmt)) {
15713 m_os << XmlEncode( text );
15714 applyFormatting(fmt);
15719 XmlWriter& XmlWriter::writeComment( std::string
const& text, XmlFormatting fmt) {
15721 if (shouldIndent(fmt)) {
15724 m_os <<
"<!--" << text <<
"-->";
15725 applyFormatting(fmt);
15729 void XmlWriter::writeStylesheetRef( std::string
const& url ) {
15730 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15733 XmlWriter& XmlWriter::writeBlankLine() {
15739 void XmlWriter::ensureTagClosed() {
15740 if( m_tagIsOpen ) {
15741 m_os << '>
' << std::flush; 15742 newlineIfNecessary(); 15743 m_tagIsOpen = false; 15747 void XmlWriter::applyFormatting(XmlFormatting fmt) { 15748 m_needsNewline = shouldNewline(fmt); 15751 void XmlWriter::writeDeclaration() { 15752 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; 15755 void XmlWriter::newlineIfNecessary() { 15756 if( m_needsNewline ) { 15758 m_needsNewline = false; 15762 // end catch_xmlwriter.cpp 15763 // start catch_reporter_bases.cpp 15772 void prepareExpandedExpression(AssertionResult& result) { 15773 result.getExpandedExpression(); 15776 // Because formatting using c++ streams is stateful, drop down to C is required 15777 // Alternatively we could use stringstream, but its performance is... not good. 15778 std::string getFormattedDuration( double duration ) { 15779 // Max exponent + 1 is required to represent the whole part 15780 // + 1 for decimal point 15781 // + 3 for the 3 decimal places 15782 // + 1 for null terminator 15783 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; 15784 char buffer[maxDoubleSize]; 15786 // Save previous errno, to prevent sprintf from overwriting it 15789 sprintf_s(buffer, "%.3f", duration); 15791 std::sprintf(buffer, "%.3f", duration); 15793 return std::string(buffer); 15796 bool shouldShowDuration( IConfig const& config, double duration ) { 15797 if ( config.showDurations() == ShowDurations::Always ) { 15800 if ( config.showDurations() == ShowDurations::Never ) { 15803 const double min = config.minDuration(); 15804 return min >= 0 && duration >= min; 15807 std::string serializeFilters( std::vector<std::string> const& container ) { 15808 ReusableStringStream oss; 15810 for (auto&& filter : container) 15822 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) 15823 :StreamingReporterBase(_config) {} 15825 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() { 15826 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; 15829 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} 15831 bool TestEventListenerBase::assertionEnded(AssertionStats const &) { 15835 } // end namespace Catch 15836 // end catch_reporter_bases.cpp 15837 // start catch_reporter_compact.cpp 15841 #ifdef CATCH_PLATFORM_MAC 15842 const char* failedString() { return "FAILED"; } 15843 const char* passedString() { return "PASSED"; } 15845 const char* failedString() { return "failed"; } 15846 const char* passedString() { return "passed"; } 15849 // Colour::LightGrey 15850 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } 15852 std::string bothOrAll( std::size_t count ) { 15853 return count == 1 ? std::string() : 15854 count == 2 ? "both " : "all " ; 15857 } // anon namespace 15861 // Colour, message variants: 15862 // - white: No tests ran. 15863 // - red: Failed [both/all] N test cases, failed [both/all] M assertions. 15864 // - white: Passed [both/all] N test cases (no assertions). 15865 // - red: Failed N tests cases, failed M assertions. 15866 // - green: Passed [both/all] N tests cases with M assertions. 15867 void printTotals(std::ostream& out, const Totals& totals) { 15868 if (totals.testCases.total() == 0) { 15869 out << "No tests ran."; 15870 } else if (totals.testCases.failed == totals.testCases.total()) { 15871 Colour colour(Colour::ResultError); 15872 const std::string qualify_assertions_failed = 15873 totals.assertions.failed == totals.assertions.total() ? 15874 bothOrAll(totals.assertions.failed) : std::string(); 15876 "Failed " << bothOrAll(totals.testCases.failed) 15877 << pluralise(totals.testCases.failed, "test case") << ", " 15878 "failed " << qualify_assertions_failed << 15879 pluralise(totals.assertions.failed, "assertion") << '.
'; 15880 } else if (totals.assertions.total() == 0) { 15882 "Passed " << bothOrAll(totals.testCases.total()) 15883 << pluralise(totals.testCases.total(), "test case") 15884 << " (no assertions)."; 15885 } else if (totals.assertions.failed) { 15886 Colour colour(Colour::ResultError); 15888 "Failed " << pluralise(totals.testCases.failed, "test case") << ", " 15889 "failed " << pluralise(totals.assertions.failed, "assertion") << '.
'; 15891 Colour colour(Colour::ResultSuccess); 15893 "Passed " << bothOrAll(totals.testCases.passed) 15894 << pluralise(totals.testCases.passed, "test case") << 15895 " with " << pluralise(totals.assertions.passed, "assertion") << '.
'; 15899 // Implementation of CompactReporter formatting 15900 class AssertionPrinter { 15902 AssertionPrinter& operator= (AssertionPrinter const&) = delete; 15903 AssertionPrinter(AssertionPrinter const&) = delete; 15904 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) 15906 , result(_stats.assertionResult) 15907 , messages(_stats.infoMessages) 15908 , itMessage(_stats.infoMessages.begin()) 15909 , printInfoMessages(_printInfoMessages) {} 15914 itMessage = messages.begin(); 15916 switch (result.getResultType()) { 15917 case ResultWas::Ok: 15918 printResultType(Colour::ResultSuccess, passedString()); 15919 printOriginalExpression(); 15920 printReconstructedExpression(); 15921 if (!result.hasExpression()) 15922 printRemainingMessages(Colour::None); 15924 printRemainingMessages(); 15926 case ResultWas::ExpressionFailed: 15928 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); 15930 printResultType(Colour::Error, failedString()); 15931 printOriginalExpression(); 15932 printReconstructedExpression(); 15933 printRemainingMessages(); 15935 case ResultWas::ThrewException: 15936 printResultType(Colour::Error, failedString()); 15937 printIssue("unexpected exception with message:"); 15939 printExpressionWas(); 15940 printRemainingMessages(); 15942 case ResultWas::FatalErrorCondition: 15943 printResultType(Colour::Error, failedString()); 15944 printIssue("fatal error condition with message:"); 15946 printExpressionWas(); 15947 printRemainingMessages(); 15949 case ResultWas::DidntThrowException: 15950 printResultType(Colour::Error, failedString()); 15951 printIssue("expected exception, got none"); 15952 printExpressionWas(); 15953 printRemainingMessages(); 15955 case ResultWas::Info: 15956 printResultType(Colour::None, "info"); 15958 printRemainingMessages(); 15960 case ResultWas::Warning: 15961 printResultType(Colour::None, "warning"); 15963 printRemainingMessages(); 15965 case ResultWas::ExplicitFailure: 15966 printResultType(Colour::Error, failedString()); 15967 printIssue("explicitly"); 15968 printRemainingMessages(Colour::None); 15970 // These cases are here to prevent compiler warnings 15971 case ResultWas::Unknown: 15972 case ResultWas::FailureBit: 15973 case ResultWas::Exception: 15974 printResultType(Colour::Error, "** internal error **"); 15980 void printSourceInfo() const { 15981 Colour colourGuard(Colour::FileName); 15982 stream << result.getSourceInfo() << ':
'; 15985 void printResultType(Colour::Code colour, std::string const& passOrFail) const { 15986 if (!passOrFail.empty()) { 15988 Colour colourGuard(colour); 15989 stream << ' ' << passOrFail; 15995 void printIssue(std::string const& issue) const { 15996 stream << ' ' << issue; 15999 void printExpressionWas() { 16000 if (result.hasExpression()) { 16003 Colour colour(dimColour()); 16004 stream << " expression was:"; 16006 printOriginalExpression(); 16010 void printOriginalExpression() const { 16011 if (result.hasExpression()) { 16012 stream << ' ' << result.getExpression(); 16016 void printReconstructedExpression() const { 16017 if (result.hasExpandedExpression()) { 16019 Colour colour(dimColour()); 16020 stream << " for: "; 16022 stream << result.getExpandedExpression(); 16026 void printMessage() { 16027 if (itMessage != messages.end()) { 16028 stream << " '" << itMessage->message << '\''; 16033 void printRemainingMessages(Colour::Code colour = dimColour()) { 16034 if (itMessage == messages.end()) 16037 const auto itEnd = messages.cend(); 16038 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd)); 16041 Colour colourGuard(colour); 16042 stream << " with
" << pluralise(N, "message
") << ':'; 16045 while (itMessage != itEnd) { 16046 // If this assertion is a warning ignore any INFO messages 16047 if (printInfoMessages || itMessage->type != ResultWas::Info) { 16049 if (itMessage != itEnd) { 16050 Colour colourGuard(dimColour()); 16060 std::ostream& stream; 16061 AssertionResult const& result; 16062 std::vector<MessageInfo> messages; 16063 std::vector<MessageInfo>::const_iterator itMessage; 16064 bool printInfoMessages; 16067 } // anon namespace 16069 std::string CompactReporter::getDescription() { 16070 return "Reports
test results on a single line, suitable
for IDEs
"; 16073 void CompactReporter::noMatchingTestCases( std::string const& spec ) { 16074 stream << "No
test cases matched
'" << spec << '\
'' << std::endl;
16077 void CompactReporter::assertionStarting(
AssertionInfo const& ) {}
16079 bool CompactReporter::assertionEnded( AssertionStats
const& _assertionStats ) {
16080 AssertionResult
const& result = _assertionStats.assertionResult;
16082 bool printInfoMessages =
true;
16085 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16086 if( result.getResultType() != ResultWas::Warning )
16088 printInfoMessages =
false;
16091 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16094 stream << std::endl;
16098 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
16099 double dur = _sectionStats.durationInSeconds;
16100 if ( shouldShowDuration( *m_config, dur ) ) {
16101 stream << getFormattedDuration( dur ) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16105 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
16106 printTotals( stream, _testRunStats.totals );
16107 stream <<
'\n' << std::endl;
16108 StreamingReporterBase::testRunEnded( _testRunStats );
16111 CompactReporter::~CompactReporter() {}
16113 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
16122 #if defined(_MSC_VER) 16123 #pragma warning(push) 16124 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 16128 #if defined(__clang__) 16129 # pragma clang diagnostic push 16131 # pragma clang diagnostic ignored "-Wunused-function" 16139 class ConsoleAssertionPrinter {
16141 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter
const&) =
delete;
16142 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
16143 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
16146 result(_stats.assertionResult),
16147 colour(Colour::None),
16148 message(result.getMessage()),
16149 messages(_stats.infoMessages),
16150 printInfoMessages(_printInfoMessages) {
16151 switch (result.getResultType()) {
16152 case ResultWas::Ok:
16153 colour = Colour::Success;
16154 passOrFail =
"PASSED";
16156 if (_stats.infoMessages.size() == 1)
16157 messageLabel =
"with message";
16158 if (_stats.infoMessages.size() > 1)
16159 messageLabel =
"with messages";
16161 case ResultWas::ExpressionFailed:
16162 if (result.isOk()) {
16163 colour = Colour::Success;
16164 passOrFail =
"FAILED - but was ok";
16166 colour = Colour::Error;
16167 passOrFail =
"FAILED";
16169 if (_stats.infoMessages.size() == 1)
16170 messageLabel =
"with message";
16171 if (_stats.infoMessages.size() > 1)
16172 messageLabel =
"with messages";
16174 case ResultWas::ThrewException:
16175 colour = Colour::Error;
16176 passOrFail =
"FAILED";
16177 messageLabel =
"due to unexpected exception with ";
16178 if (_stats.infoMessages.size() == 1)
16179 messageLabel +=
"message";
16180 if (_stats.infoMessages.size() > 1)
16181 messageLabel +=
"messages";
16183 case ResultWas::FatalErrorCondition:
16184 colour = Colour::Error;
16185 passOrFail =
"FAILED";
16186 messageLabel =
"due to a fatal error condition";
16188 case ResultWas::DidntThrowException:
16189 colour = Colour::Error;
16190 passOrFail =
"FAILED";
16191 messageLabel =
"because no exception was thrown where one was expected";
16193 case ResultWas::Info:
16194 messageLabel =
"info";
16196 case ResultWas::Warning:
16197 messageLabel =
"warning";
16199 case ResultWas::ExplicitFailure:
16200 passOrFail =
"FAILED";
16201 colour = Colour::Error;
16202 if (_stats.infoMessages.size() == 1)
16203 messageLabel =
"explicitly with message";
16204 if (_stats.infoMessages.size() > 1)
16205 messageLabel =
"explicitly with messages";
16208 case ResultWas::Unknown:
16209 case ResultWas::FailureBit:
16210 case ResultWas::Exception:
16211 passOrFail =
"** internal error **";
16212 colour = Colour::Error;
16217 void print()
const {
16219 if (stats.totals.assertions.total() > 0) {
16221 printOriginalExpression();
16222 printReconstructedExpression();
16230 void printResultType()
const {
16231 if (!passOrFail.empty()) {
16232 Colour colourGuard(colour);
16233 stream << passOrFail <<
":\n";
16236 void printOriginalExpression()
const {
16237 if (result.hasExpression()) {
16238 Colour colourGuard(Colour::OriginalExpression);
16240 stream << result.getExpressionInMacro();
16244 void printReconstructedExpression()
const {
16245 if (result.hasExpandedExpression()) {
16246 stream <<
"with expansion:\n";
16247 Colour colourGuard(Colour::ReconstructedExpression);
16248 stream << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16251 void printMessage()
const {
16252 if (!messageLabel.empty())
16253 stream << messageLabel <<
':' <<
'\n';
16254 for (
auto const& msg : messages) {
16256 if (printInfoMessages || msg.type != ResultWas::Info)
16257 stream << Column(msg.message).indent(2) <<
'\n';
16260 void printSourceInfo()
const {
16261 Colour colourGuard(Colour::FileName);
16262 stream << result.getSourceInfo() <<
": ";
16265 std::ostream& stream;
16266 AssertionStats
const& stats;
16267 AssertionResult
const& result;
16268 Colour::Code colour;
16269 std::string passOrFail;
16270 std::string messageLabel;
16271 std::string message;
16272 std::vector<MessageInfo> messages;
16273 bool printInfoMessages;
16276 std::size_t makeRatio(std::size_t number, std::size_t total) {
16277 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16278 return (ratio == 0 && number > 0) ? 1 : ratio;
16281 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16282 if (i > j && i > k)
16290 struct ColumnInfo {
16291 enum Justification { Left, Right };
16294 Justification justification;
16296 struct ColumnBreak {};
16297 struct RowBreak {};
16308 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16309 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16310 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16311 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16313 double m_inNanoseconds;
16317 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16318 : m_inNanoseconds(inNanoseconds),
16320 if (m_units == Unit::Auto) {
16321 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16322 m_units = Unit::Nanoseconds;
16323 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16324 m_units = Unit::Microseconds;
16325 else if (m_inNanoseconds < s_nanosecondsInASecond)
16326 m_units = Unit::Milliseconds;
16327 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16328 m_units = Unit::Seconds;
16330 m_units = Unit::Minutes;
16335 auto value()
const ->
double {
16337 case Unit::Microseconds:
16338 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16339 case Unit::Milliseconds:
16340 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16341 case Unit::Seconds:
16342 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16343 case Unit::Minutes:
16344 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16346 return m_inNanoseconds;
16349 auto unitsAsString()
const -> std::string {
16351 case Unit::Nanoseconds:
16353 case Unit::Microseconds:
16355 case Unit::Milliseconds:
16357 case Unit::Seconds:
16359 case Unit::Minutes:
16362 return "** internal error **";
16366 friend auto operator << (std::ostream& os, Duration
const& duration) -> std::ostream& {
16367 return os << duration.value() <<
' ' << duration.unitsAsString();
16372 class TablePrinter {
16373 std::ostream& m_os;
16374 std::vector<ColumnInfo> m_columnInfos;
16375 std::ostringstream m_oss;
16376 int m_currentColumn = -1;
16377 bool m_isOpen =
false;
16380 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16382 m_columnInfos( std::move( columnInfos ) ) {}
16384 auto columnInfos()
const -> std::vector<ColumnInfo>
const& {
16385 return m_columnInfos;
16391 *
this << RowBreak();
16393 Columns headerCols;
16395 for (
auto const& info : m_columnInfos) {
16396 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16397 headerCols += spacer;
16399 m_os << headerCols <<
'\n';
16401 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16406 *
this << RowBreak();
16412 template<
typename T>
16413 friend TablePrinter& operator << (TablePrinter& tp, T
const& value) {
16418 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
16419 auto colStr = tp.m_oss.str();
16420 const auto strSize = colStr.size();
16423 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16424 tp.m_currentColumn = -1;
16427 tp.m_currentColumn++;
16429 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16430 auto padding = (strSize + 1 <
static_cast<std::size_t
>(colInfo.width))
16431 ? std::string(colInfo.width - (strSize + 1),
' ')
16433 if (colInfo.justification == ColumnInfo::Left)
16434 tp.m_os << colStr << padding <<
' ';
16436 tp.m_os << padding << colStr <<
' ';
16440 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
16441 if (tp.m_currentColumn > 0) {
16443 tp.m_currentColumn = -1;
16449 ConsoleReporter::ConsoleReporter(ReporterConfig
const& config)
16450 : StreamingReporterBase(config),
16451 m_tablePrinter(
new TablePrinter(config.stream(),
16452 [&config]() -> std::vector<ColumnInfo> {
16453 if (config.fullConfig()->benchmarkNoAnalysis())
16456 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16457 {
" samples", 14, ColumnInfo::Right },
16458 {
" iterations", 14, ColumnInfo::Right },
16459 {
" mean", 14, ColumnInfo::Right }
16465 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16466 {
"samples mean std dev", 14, ColumnInfo::Right },
16467 {
"iterations low mean low std dev", 14, ColumnInfo::Right },
16468 {
"estimated high mean high std dev", 14, ColumnInfo::Right }
16472 ConsoleReporter::~ConsoleReporter() =
default;
16474 std::string ConsoleReporter::getDescription() {
16475 return "Reports test results as plain lines of text";
16478 void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16479 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16482 void ConsoleReporter::reportInvalidArguments(std::string
const&arg){
16483 stream <<
"Invalid Filter: " << arg << std::endl;
16486 void ConsoleReporter::assertionStarting(
AssertionInfo const&) {}
16488 bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16489 AssertionResult
const& result = _assertionStats.assertionResult;
16491 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16494 if (!includeResults && result.getResultType() != ResultWas::Warning)
16499 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16501 stream << std::endl;
16505 void ConsoleReporter::sectionStarting(
SectionInfo const& _sectionInfo) {
16506 m_tablePrinter->close();
16507 m_headerPrinted =
false;
16508 StreamingReporterBase::sectionStarting(_sectionInfo);
16510 void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16511 m_tablePrinter->close();
16512 if (_sectionStats.missingAssertions) {
16514 Colour colour(Colour::ResultError);
16515 if (m_sectionStack.size() > 1)
16516 stream <<
"\nNo assertions in section";
16518 stream <<
"\nNo assertions in test case";
16519 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16521 double dur = _sectionStats.durationInSeconds;
16522 if (shouldShowDuration(*m_config, dur)) {
16523 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16525 if (m_headerPrinted) {
16526 m_headerPrinted =
false;
16528 StreamingReporterBase::sectionEnded(_sectionStats);
16531 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 16532 void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16533 lazyPrintWithoutClosingBenchmarkTable();
16535 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16537 bool firstLine =
true;
16538 for (
auto line : nameCol) {
16540 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16544 (*m_tablePrinter) << line << ColumnBreak();
16548 void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16549 (*m_tablePrinter) << info.samples << ColumnBreak()
16550 << info.iterations << ColumnBreak();
16551 if (!m_config->benchmarkNoAnalysis())
16552 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16554 void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16555 if (m_config->benchmarkNoAnalysis())
16557 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16561 (*m_tablePrinter) << ColumnBreak()
16562 << Duration(stats.mean.point.count()) << ColumnBreak()
16563 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16564 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16565 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16566 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16567 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16571 void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16572 Colour colour(Colour::Red);
16574 <<
"Benchmark failed (" << error <<
')' 16575 << ColumnBreak() << RowBreak();
16577 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 16579 void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16580 m_tablePrinter->close();
16581 StreamingReporterBase::testCaseEnded(_testCaseStats);
16582 m_headerPrinted =
false;
16584 void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16585 if (currentGroupInfo.used) {
16586 printSummaryDivider();
16587 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16588 printTotals(_testGroupStats.totals);
16589 stream <<
'\n' << std::endl;
16591 StreamingReporterBase::testGroupEnded(_testGroupStats);
16593 void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16594 printTotalsDivider(_testRunStats.totals);
16595 printTotals(_testRunStats.totals);
16596 stream << std::endl;
16597 StreamingReporterBase::testRunEnded(_testRunStats);
16599 void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16600 StreamingReporterBase::testRunStarting(_testInfo);
16601 printTestFilters();
16604 void ConsoleReporter::lazyPrint() {
16606 m_tablePrinter->close();
16607 lazyPrintWithoutClosingBenchmarkTable();
16610 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16612 if (!currentTestRunInfo.used)
16613 lazyPrintRunInfo();
16614 if (!currentGroupInfo.used)
16615 lazyPrintGroupInfo();
16617 if (!m_headerPrinted) {
16618 printTestCaseAndSectionHeader();
16619 m_headerPrinted =
true;
16622 void ConsoleReporter::lazyPrintRunInfo() {
16623 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16624 Colour colour(Colour::SecondaryText);
16625 stream << currentTestRunInfo->name
16626 <<
" is a Catch v" << libraryVersion() <<
" host application.\n" 16627 <<
"Run with -? for options\n\n";
16629 if (m_config->rngSeed() != 0)
16630 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16632 currentTestRunInfo.used =
true;
16634 void ConsoleReporter::lazyPrintGroupInfo() {
16635 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16636 printClosedHeader(
"Group: " + currentGroupInfo->name);
16637 currentGroupInfo.used =
true;
16640 void ConsoleReporter::printTestCaseAndSectionHeader() {
16641 assert(!m_sectionStack.empty());
16642 printOpenHeader(currentTestCaseInfo->name);
16644 if (m_sectionStack.size() > 1) {
16645 Colour colourGuard(Colour::Headers);
16648 it = m_sectionStack.begin() + 1,
16649 itEnd = m_sectionStack.end();
16650 for (; it != itEnd; ++it)
16651 printHeaderString(it->name, 2);
16656 stream << getLineOfChars<
'-'>() <<
'\n';
16657 Colour colourGuard(Colour::FileName);
16658 stream << lineInfo <<
'\n';
16659 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16662 void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16663 printOpenHeader(_name);
16664 stream << getLineOfChars<
'.'>() <<
'\n';
16666 void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16667 stream << getLineOfChars<
'-'>() <<
'\n';
16669 Colour colourGuard(Colour::Headers);
16670 printHeaderString(_name);
16676 void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16677 std::size_t i = _string.find(
": ");
16678 if (i != std::string::npos)
16682 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16685 struct SummaryColumn {
16687 SummaryColumn( std::string _label, Colour::Code _colour )
16688 : label( std::move( _label ) ),
16689 colour( _colour ) {}
16690 SummaryColumn addRow( std::size_t count ) {
16693 std::string row = rss.str();
16694 for (
auto& oldRow : rows) {
16695 while (oldRow.size() < row.size())
16696 oldRow =
' ' + oldRow;
16697 while (oldRow.size() > row.size())
16700 rows.push_back(row);
16705 Colour::Code colour;
16706 std::vector<std::string> rows;
16710 void ConsoleReporter::printTotals(
Totals const& totals ) {
16711 if (totals.testCases.total() == 0) {
16712 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16713 }
else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16714 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16716 <<
pluralise(totals.assertions.passed,
"assertion") <<
" in " 16717 <<
pluralise(totals.testCases.passed,
"test case") <<
')' 16721 std::vector<SummaryColumn> columns;
16722 columns.push_back(SummaryColumn(
"", Colour::None)
16723 .addRow(totals.testCases.total())
16724 .addRow(totals.assertions.total()));
16725 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16726 .addRow(totals.testCases.passed)
16727 .addRow(totals.assertions.passed));
16728 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16729 .addRow(totals.testCases.failed)
16730 .addRow(totals.assertions.failed));
16731 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16732 .addRow(totals.testCases.failedButOk)
16733 .addRow(totals.assertions.failedButOk));
16735 printSummaryRow(
"test cases", columns, 0);
16736 printSummaryRow(
"assertions", columns, 1);
16739 void ConsoleReporter::printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row) {
16740 for (
auto col : cols) {
16741 std::string value = col.rows[row];
16742 if (col.label.empty()) {
16743 stream << label <<
": ";
16747 stream << Colour(Colour::Warning) <<
"- none -";
16748 }
else if (value !=
"0") {
16749 stream << Colour(Colour::LightGrey) <<
" | ";
16750 stream << Colour(col.colour)
16751 << value <<
' ' << col.label;
16757 void ConsoleReporter::printTotalsDivider(
Totals const& totals) {
16758 if (totals.testCases.total() > 0) {
16759 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16760 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16761 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16762 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16763 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16764 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16765 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16767 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16768 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16769 if (totals.testCases.allPassed())
16770 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16772 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16774 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16778 void ConsoleReporter::printSummaryDivider() {
16779 stream << getLineOfChars<
'-'>() <<
'\n';
16782 void ConsoleReporter::printTestFilters() {
16783 if (m_config->testSpec().hasFilters()) {
16784 Colour guard(Colour::BrightYellow);
16785 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16789 CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16793 #if defined(_MSC_VER) 16794 #pragma warning(pop) 16797 #if defined(__clang__) 16798 # pragma clang diagnostic pop 16806 #include <algorithm> 16812 std::string getCurrentTimestamp() {
16816 std::time(&rawtime);
16817 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16820 std::tm timeInfo = {};
16821 gmtime_s(&timeInfo, &rawtime);
16824 timeInfo = std::gmtime(&rawtime);
16827 char timeStamp[timeStampSize];
16828 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16831 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16833 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16835 return std::string(timeStamp, timeStampSize-1);
16838 std::string fileNameTag(
const std::vector<std::string> &tags) {
16839 auto it = std::find_if(begin(tags),
16841 [] (std::string
const& tag) {
return tag.front() ==
'#'; });
16842 if (it != tags.end())
16843 return it->substr(1);
16844 return std::string();
16851 std::string formatDuration(
double seconds ) {
16853 rss << std::fixed << std::setprecision( 3 ) << seconds;
16859 JunitReporter::JunitReporter( ReporterConfig
const& _config )
16860 : CumulativeReporterBase( _config ),
16861 xml( _config.stream() )
16863 m_reporterPrefs.shouldRedirectStdOut =
true;
16864 m_reporterPrefs.shouldReportAllAssertions =
true;
16867 JunitReporter::~JunitReporter() {}
16869 std::string JunitReporter::getDescription() {
16870 return "Reports test results in an XML format that looks like Ant's junitreport target";
16873 void JunitReporter::noMatchingTestCases( std::string
const& ) {}
16875 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16876 CumulativeReporterBase::testRunStarting( runInfo );
16877 xml.startElement(
"testsuites" );
16880 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16881 suiteTimer.start();
16882 stdOutForSuite.clear();
16883 stdErrForSuite.clear();
16884 unexpectedExceptions = 0;
16885 CumulativeReporterBase::testGroupStarting( groupInfo );
16888 void JunitReporter::testCaseStarting(
TestCaseInfo const& testCaseInfo ) {
16889 m_okToFail = testCaseInfo.okToFail();
16892 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16893 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16894 unexpectedExceptions++;
16895 return CumulativeReporterBase::assertionEnded( assertionStats );
16898 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16899 stdOutForSuite += testCaseStats.stdOut;
16900 stdErrForSuite += testCaseStats.stdErr;
16901 CumulativeReporterBase::testCaseEnded( testCaseStats );
16904 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16905 double suiteTime = suiteTimer.getElapsedSeconds();
16906 CumulativeReporterBase::testGroupEnded( testGroupStats );
16907 writeGroup( *m_testGroups.back(), suiteTime );
16910 void JunitReporter::testRunEndedCumulative() {
16914 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16915 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
16917 TestGroupStats
const& stats = groupNode.value;
16918 xml.writeAttribute(
"name", stats.groupInfo.name );
16919 xml.writeAttribute(
"errors", unexpectedExceptions );
16920 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16921 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16922 xml.writeAttribute(
"hostname",
"tbd" );
16923 if( m_config->showDurations() == ShowDurations::Never )
16924 xml.writeAttribute(
"time",
"" );
16926 xml.writeAttribute(
"time", formatDuration( suiteTime ) );
16927 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16930 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16931 auto properties = xml.scopedElement(
"properties");
16932 if (m_config->hasTestFilters()) {
16933 xml.scopedElement(
"property")
16934 .writeAttribute(
"name",
"filters")
16935 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16937 if (m_config->rngSeed() != 0) {
16938 xml.scopedElement(
"property")
16939 .writeAttribute(
"name",
"random-seed")
16940 .writeAttribute(
"value", m_config->rngSeed());
16945 for(
auto const& child : groupNode.children )
16946 writeTestCase( *child );
16948 xml.scopedElement(
"system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16949 xml.scopedElement(
"system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16952 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16953 TestCaseStats
const& stats = testCaseNode.value;
16957 assert( testCaseNode.children.size() == 1 );
16958 SectionNode
const& rootSection = *testCaseNode.children.front();
16960 std::string className = stats.testInfo.className;
16962 if( className.empty() ) {
16963 className = fileNameTag(stats.testInfo.tags);
16964 if ( className.empty() )
16965 className =
"global";
16968 if ( !m_config->name().empty() )
16969 className = m_config->name() +
"." + className;
16971 writeSection( className,
"", rootSection, stats.testInfo.okToFail() );
16974 void JunitReporter::writeSection( std::string
const& className,
16975 std::string
const& rootName,
16976 SectionNode
const& sectionNode,
16977 bool testOkToFail) {
16978 std::string name = trim( sectionNode.stats.sectionInfo.name );
16979 if( !rootName.empty() )
16980 name = rootName +
'/' + name;
16982 if( !sectionNode.assertions.empty() ||
16983 !sectionNode.stdOut.empty() ||
16984 !sectionNode.stdErr.empty() ) {
16985 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
16986 if( className.empty() ) {
16987 xml.writeAttribute(
"classname", name );
16988 xml.writeAttribute(
"name",
"root" );
16991 xml.writeAttribute(
"classname", className );
16992 xml.writeAttribute(
"name", name );
16994 xml.writeAttribute(
"time", formatDuration( sectionNode.stats.durationInSeconds ) );
16999 xml.writeAttribute(
"status",
"run" );
17001 if (sectionNode.stats.assertions.failedButOk) {
17002 xml.scopedElement(
"skipped")
17003 .writeAttribute(
"message",
"TEST_CASE tagged with !mayfail");
17006 writeAssertions( sectionNode );
17008 if( !sectionNode.stdOut.empty() )
17009 xml.scopedElement(
"system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
17010 if( !sectionNode.stdErr.empty() )
17011 xml.scopedElement(
"system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
17013 for(
auto const& childNode : sectionNode.childSections )
17014 if( className.empty() )
17015 writeSection( name,
"", *childNode, testOkToFail );
17017 writeSection( className, name, *childNode, testOkToFail );
17020 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
17021 for(
auto const& assertion : sectionNode.assertions )
17022 writeAssertion( assertion );
17025 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
17026 AssertionResult
const& result = stats.assertionResult;
17027 if( !result.isOk() ) {
17028 std::string elementName;
17029 switch( result.getResultType() ) {
17030 case ResultWas::ThrewException:
17031 case ResultWas::FatalErrorCondition:
17032 elementName =
"error";
17034 case ResultWas::ExplicitFailure:
17035 case ResultWas::ExpressionFailed:
17036 case ResultWas::DidntThrowException:
17037 elementName =
"failure";
17041 case ResultWas::Info:
17042 case ResultWas::Warning:
17043 case ResultWas::Ok:
17044 case ResultWas::Unknown:
17045 case ResultWas::FailureBit:
17046 case ResultWas::Exception:
17047 elementName =
"internalError";
17051 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17053 xml.writeAttribute(
"message", result.getExpression() );
17054 xml.writeAttribute(
"type", result.getTestMacroName() );
17057 if (stats.totals.assertions.total() > 0) {
17058 rss <<
"FAILED" <<
":\n";
17059 if (result.hasExpression()) {
17061 rss << result.getExpressionInMacro();
17064 if (result.hasExpandedExpression()) {
17065 rss <<
"with expansion:\n";
17066 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
17072 if( !result.getMessage().empty() )
17073 rss << result.getMessage() <<
'\n';
17074 for(
auto const& msg : stats.infoMessages )
17075 if( msg.type == ResultWas::Info )
17076 rss << msg.message <<
'\n';
17078 rss <<
"at " << result.getSourceInfo();
17079 xml.writeText( rss.str(), XmlFormatting::Newline );
17083 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
17093 ListeningReporter::ListeningReporter() {
17095 m_preferences.shouldReportAllAssertions =
true;
17098 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17099 m_listeners.push_back( std::move( listener ) );
17102 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17103 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
17104 m_reporter = std::move( reporter );
17105 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17108 ReporterPreferences ListeningReporter::getPreferences()
const {
17109 return m_preferences;
17112 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17113 return std::set<Verbosity>{ };
17116 void ListeningReporter::noMatchingTestCases( std::string
const& spec ) {
17117 for (
auto const& listener : m_listeners ) {
17118 listener->noMatchingTestCases( spec );
17120 m_reporter->noMatchingTestCases( spec );
17123 void ListeningReporter::reportInvalidArguments(std::string
const&arg){
17124 for (
auto const& listener : m_listeners ) {
17125 listener->reportInvalidArguments( arg );
17127 m_reporter->reportInvalidArguments( arg );
17130 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17131 void ListeningReporter::benchmarkPreparing( std::string
const& name ) {
17132 for (
auto const& listener : m_listeners) {
17133 listener->benchmarkPreparing(name);
17135 m_reporter->benchmarkPreparing(name);
17137 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
17138 for (
auto const& listener : m_listeners ) {
17139 listener->benchmarkStarting( benchmarkInfo );
17141 m_reporter->benchmarkStarting( benchmarkInfo );
17143 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
17144 for (
auto const& listener : m_listeners ) {
17145 listener->benchmarkEnded( benchmarkStats );
17147 m_reporter->benchmarkEnded( benchmarkStats );
17150 void ListeningReporter::benchmarkFailed( std::string
const& error ) {
17151 for (
auto const& listener : m_listeners) {
17152 listener->benchmarkFailed(error);
17154 m_reporter->benchmarkFailed(error);
17156 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17158 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
17159 for (
auto const& listener : m_listeners ) {
17160 listener->testRunStarting( testRunInfo );
17162 m_reporter->testRunStarting( testRunInfo );
17165 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17166 for (
auto const& listener : m_listeners ) {
17167 listener->testGroupStarting( groupInfo );
17169 m_reporter->testGroupStarting( groupInfo );
17172 void ListeningReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17173 for (
auto const& listener : m_listeners ) {
17174 listener->testCaseStarting( testInfo );
17176 m_reporter->testCaseStarting( testInfo );
17179 void ListeningReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17180 for (
auto const& listener : m_listeners ) {
17181 listener->sectionStarting( sectionInfo );
17183 m_reporter->sectionStarting( sectionInfo );
17186 void ListeningReporter::assertionStarting(
AssertionInfo const& assertionInfo ) {
17187 for (
auto const& listener : m_listeners ) {
17188 listener->assertionStarting( assertionInfo );
17190 m_reporter->assertionStarting( assertionInfo );
17194 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17195 for(
auto const& listener : m_listeners ) {
17196 static_cast<void>( listener->assertionEnded( assertionStats ) );
17198 return m_reporter->assertionEnded( assertionStats );
17201 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
17202 for (
auto const& listener : m_listeners ) {
17203 listener->sectionEnded( sectionStats );
17205 m_reporter->sectionEnded( sectionStats );
17208 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17209 for (
auto const& listener : m_listeners ) {
17210 listener->testCaseEnded( testCaseStats );
17212 m_reporter->testCaseEnded( testCaseStats );
17215 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17216 for (
auto const& listener : m_listeners ) {
17217 listener->testGroupEnded( testGroupStats );
17219 m_reporter->testGroupEnded( testGroupStats );
17222 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17223 for (
auto const& listener : m_listeners ) {
17224 listener->testRunEnded( testRunStats );
17226 m_reporter->testRunEnded( testRunStats );
17229 void ListeningReporter::skipTest(
TestCaseInfo const& testInfo ) {
17230 for (
auto const& listener : m_listeners ) {
17231 listener->skipTest( testInfo );
17233 m_reporter->skipTest( testInfo );
17236 bool ListeningReporter::isMulti()
const {
17244 #if defined(_MSC_VER) 17245 #pragma warning(push) 17246 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch 17252 XmlReporter::XmlReporter( ReporterConfig
const& _config )
17253 : StreamingReporterBase( _config ),
17254 m_xml(_config.stream())
17256 m_reporterPrefs.shouldRedirectStdOut =
true;
17257 m_reporterPrefs.shouldReportAllAssertions =
true;
17260 XmlReporter::~XmlReporter() =
default;
17262 std::string XmlReporter::getDescription() {
17263 return "Reports test results as an XML document";
17266 std::string XmlReporter::getStylesheetRef()
const {
17267 return std::string();
17270 void XmlReporter::writeSourceInfo(
SourceLineInfo const& sourceInfo ) {
17272 .writeAttribute(
"filename", sourceInfo.file )
17273 .writeAttribute(
"line", sourceInfo.line );
17276 void XmlReporter::noMatchingTestCases( std::string
const& s ) {
17277 StreamingReporterBase::noMatchingTestCases( s );
17280 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17281 StreamingReporterBase::testRunStarting( testInfo );
17282 std::string stylesheetRef = getStylesheetRef();
17283 if( !stylesheetRef.empty() )
17284 m_xml.writeStylesheetRef( stylesheetRef );
17285 m_xml.startElement(
"Catch" );
17286 if( !m_config->name().empty() )
17287 m_xml.writeAttribute(
"name", m_config->name() );
17288 if (m_config->testSpec().hasFilters())
17289 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17290 if( m_config->rngSeed() != 0 )
17291 m_xml.scopedElement(
"Randomness" )
17292 .writeAttribute(
"seed", m_config->rngSeed() );
17295 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17296 StreamingReporterBase::testGroupStarting( groupInfo );
17297 m_xml.startElement(
"Group" )
17298 .writeAttribute(
"name", groupInfo.name );
17301 void XmlReporter::testCaseStarting(
TestCaseInfo const& testInfo ) {
17302 StreamingReporterBase::testCaseStarting(testInfo);
17303 m_xml.startElement(
"TestCase" )
17304 .writeAttribute(
"name", trim( testInfo.name ) )
17305 .writeAttribute(
"description", testInfo.description )
17306 .writeAttribute(
"tags", testInfo.tagsAsString() );
17308 writeSourceInfo( testInfo.lineInfo );
17310 if ( m_config->showDurations() == ShowDurations::Always )
17311 m_testCaseTimer.start();
17312 m_xml.ensureTagClosed();
17315 void XmlReporter::sectionStarting(
SectionInfo const& sectionInfo ) {
17316 StreamingReporterBase::sectionStarting( sectionInfo );
17317 if( m_sectionDepth++ > 0 ) {
17318 m_xml.startElement(
"Section" )
17319 .writeAttribute(
"name", trim( sectionInfo.name ) );
17320 writeSourceInfo( sectionInfo.lineInfo );
17321 m_xml.ensureTagClosed();
17325 void XmlReporter::assertionStarting(
AssertionInfo const& ) { }
17327 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17329 AssertionResult
const& result = assertionStats.assertionResult;
17331 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17333 if( includeResults || result.getResultType() == ResultWas::Warning ) {
17335 for(
auto const& msg : assertionStats.infoMessages ) {
17336 if( msg.type == ResultWas::Info && includeResults ) {
17337 m_xml.scopedElement(
"Info" )
17338 .writeText( msg.message );
17339 }
else if ( msg.type == ResultWas::Warning ) {
17340 m_xml.scopedElement(
"Warning" )
17341 .writeText( msg.message );
17347 if( !includeResults && result.getResultType() != ResultWas::Warning )
17351 if( result.hasExpression() ) {
17352 m_xml.startElement(
"Expression" )
17353 .writeAttribute(
"success", result.succeeded() )
17354 .writeAttribute(
"type", result.getTestMacroName() );
17356 writeSourceInfo( result.getSourceInfo() );
17358 m_xml.scopedElement(
"Original" )
17359 .writeText( result.getExpression() );
17360 m_xml.scopedElement(
"Expanded" )
17361 .writeText( result.getExpandedExpression() );
17365 switch( result.getResultType() ) {
17366 case ResultWas::ThrewException:
17367 m_xml.startElement(
"Exception" );
17368 writeSourceInfo( result.getSourceInfo() );
17369 m_xml.writeText( result.getMessage() );
17370 m_xml.endElement();
17372 case ResultWas::FatalErrorCondition:
17373 m_xml.startElement(
"FatalErrorCondition" );
17374 writeSourceInfo( result.getSourceInfo() );
17375 m_xml.writeText( result.getMessage() );
17376 m_xml.endElement();
17378 case ResultWas::Info:
17379 m_xml.scopedElement(
"Info" )
17380 .writeText( result.getMessage() );
17382 case ResultWas::Warning:
17385 case ResultWas::ExplicitFailure:
17386 m_xml.startElement(
"Failure" );
17387 writeSourceInfo( result.getSourceInfo() );
17388 m_xml.writeText( result.getMessage() );
17389 m_xml.endElement();
17395 if( result.hasExpression() )
17396 m_xml.endElement();
17401 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17402 StreamingReporterBase::sectionEnded( sectionStats );
17403 if( --m_sectionDepth > 0 ) {
17404 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
17405 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17406 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17407 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17409 if ( m_config->showDurations() == ShowDurations::Always )
17410 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17412 m_xml.endElement();
17416 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17417 StreamingReporterBase::testCaseEnded( testCaseStats );
17418 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
17419 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17421 if ( m_config->showDurations() == ShowDurations::Always )
17422 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17424 if( !testCaseStats.stdOut.empty() )
17425 m_xml.scopedElement(
"StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17426 if( !testCaseStats.stdErr.empty() )
17427 m_xml.scopedElement(
"StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17429 m_xml.endElement();
17432 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17433 StreamingReporterBase::testGroupEnded( testGroupStats );
17435 m_xml.scopedElement(
"OverallResults" )
17436 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17437 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17438 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17439 m_xml.scopedElement(
"OverallResultsCases")
17440 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed )
17441 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed )
17442 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk );
17443 m_xml.endElement();
17446 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17447 StreamingReporterBase::testRunEnded( testRunStats );
17448 m_xml.scopedElement(
"OverallResults" )
17449 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17450 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17451 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17452 m_xml.scopedElement(
"OverallResultsCases")
17453 .writeAttribute(
"successes", testRunStats.totals.testCases.passed )
17454 .writeAttribute(
"failures", testRunStats.totals.testCases.failed )
17455 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk );
17456 m_xml.endElement();
17459 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17460 void XmlReporter::benchmarkPreparing(std::string
const& name) {
17461 m_xml.startElement(
"BenchmarkResults")
17462 .writeAttribute(
"name", name);
17465 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &info) {
17466 m_xml.writeAttribute(
"samples", info.samples)
17467 .writeAttribute(
"resamples", info.resamples)
17468 .writeAttribute(
"iterations", info.iterations)
17469 .writeAttribute(
"clockResolution", info.clockResolution)
17470 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17471 .writeComment(
"All values in nano seconds");
17474 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17475 m_xml.startElement(
"mean")
17476 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17477 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17478 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17479 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17480 m_xml.endElement();
17481 m_xml.startElement(
"standardDeviation")
17482 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17483 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17484 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17485 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17486 m_xml.endElement();
17487 m_xml.startElement(
"outliers")
17488 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17489 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17490 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17491 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17492 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17493 m_xml.endElement();
17494 m_xml.endElement();
17497 void XmlReporter::benchmarkFailed(std::string
const &error) {
17498 m_xml.scopedElement(
"failed").
17499 writeAttribute(
"message", error);
17500 m_xml.endElement();
17502 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17504 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17508 #if defined(_MSC_VER) 17509 #pragma warning(pop) 17514 LeakDetector leakDetector;
17518 #pragma clang diagnostic pop 17524 #ifdef CATCH_CONFIG_MAIN 17529 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) 17531 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17534 int main (
int argc,
char * argv[]) {
17537 return Catch::Session().run( argc, argv );
17543 int main (
int argc,
char *
const argv[]) {
17544 #if !CATCH_ARC_ENABLED 17545 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17548 Catch::registerTestMethods();
17549 int result = Catch::Session().run( argc, (
char**)argv );
17551 #if !CATCH_ARC_ENABLED 17563 #if !defined(CATCH_CONFIG_IMPL_ONLY) 17565 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED 17566 # undef CLARA_CONFIG_MAIN 17569 #if !defined(CATCH_CONFIG_DISABLE) 17572 #ifdef CATCH_CONFIG_PREFIX_ALL 17574 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17575 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17577 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17578 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17579 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17580 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17581 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17582 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17583 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17585 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17586 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17587 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17588 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17589 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17591 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17592 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17593 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17594 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17595 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17596 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17597 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17599 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17600 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17602 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17603 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17605 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) 17606 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg ) 17607 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17608 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) 17610 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17611 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17612 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17613 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17614 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17615 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17616 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17617 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17618 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17620 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17622 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17623 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17624 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17625 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17626 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17627 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17628 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17629 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17630 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17632 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17633 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17634 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17635 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17636 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17637 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17638 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17639 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17642 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17643 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) 17644 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) 17646 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) 17647 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) 17651 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) 17652 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17653 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17654 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17655 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17656 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17657 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17658 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17660 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17661 #define CATCH_BENCHMARK(...) \ 17662 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__,,)) 17663 #define CATCH_BENCHMARK_ADVANCED(name) \ 17664 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name) 17665 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17670 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17671 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17673 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17674 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) 17675 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) 17676 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17677 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) 17678 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17679 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17681 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17682 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) 17683 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17684 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17685 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) 17687 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17688 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) 17689 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17690 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17691 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) 17692 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17693 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17695 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17696 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) 17698 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) 17699 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17701 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) 17702 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) 17703 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) 17704 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) 17706 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) 17707 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17708 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) 17709 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) 17710 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) 17711 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) 17712 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) 17713 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17714 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) 17715 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() 17717 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17718 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17719 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) 17720 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17721 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17722 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) 17723 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) 17724 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17725 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) 17726 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__) 17727 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17729 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) 17730 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) ) 17731 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17732 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17733 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) 17734 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) ) 17735 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17736 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) ) 17737 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) ) 17738 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) 17741 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) 17742 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) 17743 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) 17745 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) 17746 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) 17751 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) 17754 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) 17755 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) 17757 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) 17758 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) 17759 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) 17760 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) 17761 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) 17762 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) 17764 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING) 17765 #define BENCHMARK(...) \ 17766 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__,,)) 17767 #define BENCHMARK_ADVANCED(name) \ 17768 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name) 17769 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING 17773 #else // CATCH_CONFIG_DISABLE 17777 #ifdef CATCH_CONFIG_PREFIX_ALL 17779 #define CATCH_REQUIRE( ... ) (void)(0) 17780 #define CATCH_REQUIRE_FALSE( ... ) (void)(0) 17782 #define CATCH_REQUIRE_THROWS( ... ) (void)(0) 17783 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17784 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17785 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17786 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17787 #endif// CATCH_CONFIG_DISABLE_MATCHERS 17788 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) 17790 #define CATCH_CHECK( ... ) (void)(0) 17791 #define CATCH_CHECK_FALSE( ... ) (void)(0) 17792 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) 17793 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17794 #define CATCH_CHECK_NOFAIL( ... ) (void)(0) 17796 #define CATCH_CHECK_THROWS( ... ) (void)(0) 17797 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17798 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17799 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17800 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17801 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17802 #define CATCH_CHECK_NOTHROW( ... ) (void)(0) 17804 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17805 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0) 17807 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) 17808 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17810 #define CATCH_INFO( msg ) (void)(0) 17811 #define CATCH_UNSCOPED_INFO( msg ) (void)(0) 17812 #define CATCH_WARN( msg ) (void)(0) 17813 #define CATCH_CAPTURE( msg ) (void)(0) 17815 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17816 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17817 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) 17818 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) 17819 #define CATCH_SECTION( ... ) 17820 #define CATCH_DYNAMIC_SECTION( ... ) 17821 #define CATCH_FAIL( ... ) (void)(0) 17822 #define CATCH_FAIL_CHECK( ... ) (void)(0) 17823 #define CATCH_SUCCEED( ... ) (void)(0) 17825 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17827 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17828 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17829 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17830 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17831 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17832 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17833 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17834 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17835 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17837 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17838 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17839 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17840 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17841 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17842 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17843 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17844 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17848 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17849 #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 ) 17850 #define CATCH_GIVEN( desc ) 17851 #define CATCH_AND_GIVEN( desc ) 17852 #define CATCH_WHEN( desc ) 17853 #define CATCH_AND_WHEN( desc ) 17854 #define CATCH_THEN( desc ) 17855 #define CATCH_AND_THEN( desc ) 17857 #define CATCH_STATIC_REQUIRE( ... ) (void)(0) 17858 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) 17863 #define REQUIRE( ... ) (void)(0) 17864 #define REQUIRE_FALSE( ... ) (void)(0) 17866 #define REQUIRE_THROWS( ... ) (void)(0) 17867 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) 17868 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) 17869 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17870 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17871 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17872 #define REQUIRE_NOTHROW( ... ) (void)(0) 17874 #define CHECK( ... ) (void)(0) 17875 #define CHECK_FALSE( ... ) (void)(0) 17876 #define CHECKED_IF( ... ) if (__VA_ARGS__) 17877 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) 17878 #define CHECK_NOFAIL( ... ) (void)(0) 17880 #define CHECK_THROWS( ... ) (void)(0) 17881 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) 17882 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0) 17883 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17884 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) 17885 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17886 #define CHECK_NOTHROW( ... ) (void)(0) 17888 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS) 17889 #define CHECK_THAT( arg, matcher ) (void)(0) 17891 #define REQUIRE_THAT( arg, matcher ) (void)(0) 17892 #endif // CATCH_CONFIG_DISABLE_MATCHERS 17894 #define INFO( msg ) (void)(0) 17895 #define UNSCOPED_INFO( msg ) (void)(0) 17896 #define WARN( msg ) (void)(0) 17897 #define CAPTURE( ... ) (void)(0) 17899 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17900 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17901 #define METHOD_AS_TEST_CASE( method, ... ) 17902 #define REGISTER_TEST_CASE( Function, ... ) (void)(0) 17903 #define SECTION( ... ) 17904 #define DYNAMIC_SECTION( ... ) 17905 #define FAIL( ... ) (void)(0) 17906 #define FAIL_CHECK( ... ) (void)(0) 17907 #define SUCCEED( ... ) (void)(0) 17908 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ )) 17910 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR 17911 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) 17912 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) 17913 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__) 17914 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) 17915 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17916 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17917 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17918 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17920 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) ) 17921 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) ) 17922 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17923 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) ) 17924 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17925 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) 17926 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17927 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) 17930 #define STATIC_REQUIRE( ... ) (void)(0) 17931 #define STATIC_REQUIRE_FALSE( ... ) (void)(0) 17935 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) 17938 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ) ) 17939 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className ) 17941 #define GIVEN( desc ) 17942 #define AND_GIVEN( desc ) 17943 #define WHEN( desc ) 17944 #define AND_WHEN( desc ) 17945 #define THEN( desc ) 17946 #define AND_THEN( desc ) 17952 #endif // ! CATCH_CONFIG_IMPL_ONLY 17958 # ifdef __ICC // icpc defines the __clang__ macro 17959 # pragma warning(pop) 17961 # pragma clang diagnostic pop 17963 #elif defined __GNUC__ 17964 # pragma GCC diagnostic pop 17969 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED Definition: catch.hpp:3262
Definition: catch.hpp:2300
Definition: catch.hpp:4558
Definition: catch.hpp:3564
Definition: catch.hpp:3941
Definition: catch.hpp:4667
Definition: catch.hpp:1396
Definition: catch.hpp:4010
Definition: catch.hpp:4603
Definition: catch.hpp:2526
Definition: catch.hpp:2521
Definition: catch.hpp:486
Definition: catch.hpp:2224
Definition: catch.hpp:2976
Definition: catch.hpp:2616
Definition: catch.hpp:549
Definition: catch.hpp:3859
Definition: catch.hpp:2548
Definition: catch.hpp:3986
Definition: catch.hpp:1615
Definition: catch.hpp:4120
Definition: catch.hpp:3607
Definition: catch.hpp:3967
Definition: catch.hpp:2652
Definition: catch.hpp:2458
Definition: catch.hpp:3495
Definition: catch.hpp:4503
Definition: catch.hpp:3241
A non-owning string class (similar to the forthcoming std::string_view) Note that, because a StringRef may be a substring of another string, it may not be null terminated.
Definition: catch.hpp:606
Definition: catch.hpp:1377
Definition: catch.hpp:986
Definition: catch.hpp:3015
Definition: catch.hpp:3240
Definition: catch.hpp:2894
Definition: catch.hpp:2543
Definition: catch.hpp:4060
Definition: catch.hpp:962
Definition: catch.hpp:3556
Definition: catch.hpp:928
Definition: catch.hpp:534
Definition: catch.hpp:2876
Definition: catch.hpp:4297
Definition: catch.hpp:3239
Definition: catch.hpp:925
Definition: catch.hpp:4498
Definition: memory_leak_test.cpp:28
Definition: catch.hpp:3399
Definition: catch.hpp:2338
Definition: catch.hpp:580
Definition: catch.hpp:2842
Definition: catch.hpp:4156
Definition: catch.hpp:3568
Definition: catch.hpp:3438
Definition: catch.hpp:3953
Definition: catch.hpp:2965
Definition: catch.hpp:4482
Definition: catch.hpp:502
Definition: catch.hpp:3658
Definition: catch.hpp:4409
Definition: catch.hpp:1433
Definition: catch.hpp:3548
Definition: catch.hpp:3010
Definition: catch.hpp:1466
Definition: catch.hpp:491
Definition: catch.hpp:3681
Definition: catch.hpp:1440
Definition: catch.hpp:3454
Definition: catch.hpp:2911
Definition: catch.hpp:4488
Definition: catch.hpp:4512
Definition: catch.hpp:4840
Definition: catch.hpp:3280
Definition: catch.hpp:3538
Definition: catch.hpp:936
Definition: catch.hpp:4712
Definition: catch.hpp:3770
Definition: catch.hpp:1353
Definition: catch.hpp:3628
Definition: catch.hpp:4493
Definition: catch.hpp:4772
Definition: catch.hpp:3919
Definition: catch.hpp:1476
Definition: catch.hpp:572
Definition: catch.hpp:954
Definition: catch.hpp:3243
Definition: catch.hpp:2202
Definition: catch.hpp:3573
Definition: catch.hpp:4625
Definition: catch.hpp:4807
Definition: catch.hpp:4256
Definition: catch.hpp:4200
Definition: catch.hpp:3717
Definition: catch.hpp:2860
Definition: catch.hpp:3845
Definition: catch.hpp:2599
Definition: catch.hpp:2007
Definition: catch.hpp:3078
Definition: catch.hpp:3216
Definition: catch.hpp:4367
Definition: catch.hpp:2627
Definition: catch.hpp:1564
Definition: catch.hpp:3560
Definition: catch.hpp:1998
Definition: catch.hpp:481
Definition: catch.hpp:3429
Definition: catch.hpp:1993
Definition: catch.hpp:2414
Definition: catch.hpp:3021
Definition: catch.hpp:2829
Definition: catch.hpp:4358
Definition: catch.hpp:2641
Definition: catch.hpp:927