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 5
21 # pragma clang system_header
22 #elif defined __GNUC__
23 # pragma GCC system_header
29 # ifdef __ICC // icpc defines the __clang__ macro
30 # pragma warning(push)
31 # pragma warning(disable: 161 1682)
33 # pragma clang diagnostic push
34 # pragma clang diagnostic ignored "-Wpadded"
35 # pragma clang diagnostic ignored "-Wswitch-enum"
36 # pragma clang diagnostic ignored "-Wcovered-switch-default"
38 #elif defined __GNUC__
42 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
44 # pragma GCC diagnostic push
45 # pragma GCC diagnostic ignored "-Wunused-variable"
46 # pragma GCC diagnostic ignored "-Wpadded"
49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
51 # define CATCH_CONFIG_ALL_PARTS
56 #if defined(CATCH_CONFIG_ALL_PARTS)
57 # define CATCH_CONFIG_EXTERNAL_INTERFACES
58 # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
59 # undef CATCH_CONFIG_DISABLE_MATCHERS
61 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
62 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
66 #if !defined(CATCH_CONFIG_IMPL_ONLY)
72 # include <TargetConditionals.h>
73 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
74 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
75 # define CATCH_PLATFORM_MAC
76 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
77 # define CATCH_PLATFORM_IPHONE
80 #elif defined(linux) || defined(__linux) || defined(__linux__)
81 # define CATCH_PLATFORM_LINUX
83 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
84 # define CATCH_PLATFORM_WINDOWS
90 # ifndef CLARA_CONFIG_MAIN
91 # define CLARA_CONFIG_MAIN_NOT_DEFINED
92 # define CLARA_CONFIG_MAIN
128 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
129 # define CATCH_CPP14_OR_GREATER
132 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
133 # define CATCH_CPP17_OR_GREATER
140 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
141 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
142 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
144 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
148 #if defined(__clang__)
150 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
151 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
164 # if !defined(__ibmxl__) && !defined(__CUDACC__)
165 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
168 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
169 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
170 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
172 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
173 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
175 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
176 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
178 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
179 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
181 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
182 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
188 #if !defined(CATCH_PLATFORM_WINDOWS)
189 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
194 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
195 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
199 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
200 # define CATCH_CONFIG_COLOUR_NONE
205 #if defined(__ANDROID__)
206 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
207 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
212 #if defined(__MINGW32__)
213 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
218 #if defined(__ORBIS__)
219 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
231 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
232 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
234 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
241 #if defined(_MSC_VER)
243 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
244 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
248 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
249 # define CATCH_CONFIG_COLOUR_NONE
251 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
257 # if !defined(__clang__) // Handle Clang masquerading for msvc
258 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
259 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
260 # endif // MSVC_TRADITIONAL
265 #if defined(_REENTRANT) || defined(_MSC_VER)
267 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
272 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
273 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
279 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
284 #if defined(__BORLANDC__)
285 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
295 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
296 #define CATCH_INTERNAL_CONFIG_COUNTER
304 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
305 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
306 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
307 #define CATCH_CONFIG_COLOUR_NONE
310 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
311 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
315 #if defined(__has_include)
317 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
318 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
322 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
323 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
324 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
327 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
329 # if __cpp_lib_byte > 0
330 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
332 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
335 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
336 # if defined(__clang__) && (__clang_major__ < 8)
340 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
341 # define CATCH_CONFIG_NO_CPP17_VARIANT
343 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
344 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
346 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
347 # endif // defined(__clang__) && (__clang_major__ < 8)
348 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
349 #endif // defined(__has_include)
351 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
352 # define CATCH_CONFIG_COUNTER
354 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
355 # define CATCH_CONFIG_WINDOWS_SEH
358 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
359 # define CATCH_CONFIG_POSIX_SIGNALS
362 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
363 # define CATCH_CONFIG_WCHAR
366 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
367 # define CATCH_CONFIG_CPP11_TO_STRING
370 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
371 # define CATCH_CONFIG_CPP17_OPTIONAL
374 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
375 # define CATCH_CONFIG_CPP17_STRING_VIEW
378 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
379 # define CATCH_CONFIG_CPP17_VARIANT
382 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
383 # define CATCH_CONFIG_CPP17_BYTE
386 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
387 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
390 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
391 # define CATCH_CONFIG_NEW_CAPTURE
394 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
395 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
398 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
399 # define CATCH_CONFIG_POLYFILL_ISNAN
402 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
403 # define CATCH_CONFIG_USE_ASYNC
406 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
407 # define CATCH_CONFIG_ANDROID_LOGWRITE
410 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
411 # define CATCH_CONFIG_GLOBAL_NEXTAFTER
416 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
417 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
419 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
420 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
422 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
423 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
425 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
426 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
428 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
429 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
431 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
432 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
437 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
438 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
441 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
442 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
443 #elif defined(__clang__) && (__clang_major__ < 5)
444 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
447 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
448 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
451 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
452 #define CATCH_TRY if ((true))
453 #define CATCH_CATCH_ALL if ((false))
454 #define CATCH_CATCH_ANON(type) if ((false))
456 #define CATCH_TRY try
457 #define CATCH_CATCH_ALL catch (...)
458 #define CATCH_CATCH_ANON(type) catch (type)
461 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
462 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
466 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
467 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
468 #ifdef CATCH_CONFIG_COUNTER
469 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
471 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
541 #define CATCH_INTERNAL_LINEINFO \
542 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
553 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
554 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
555 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
556 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
557 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
571 virtual void invoke ()
const = 0;
580 virtual std::vector<TestCase>
const&
getAllTests()
const = 0;
586 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
610 static constexpr
char const*
const s_empty =
"";
616 constexpr
StringRef() noexcept = default;
618 StringRef(
char const* rawChars ) noexcept;
626 :
m_start( stdString.c_str() ),
627 m_size( stdString.size() )
630 explicit operator std::string()
const {
637 return !(*
this == other);
646 constexpr
auto empty() const noexcept ->
bool {
655 auto c_str() const ->
char const*;
664 auto
data() const noexcept ->
char const*;
675 auto operator += ( std::string& lhs, StringRef
const& sr ) -> std::string&;
676 auto operator << ( std::ostream& os, StringRef
const& sr ) -> std::ostream&;
678 constexpr
auto operator "" _sr(
char const* rawChars, std::size_t size ) noexcept ->
StringRef {
683 constexpr
auto operator "" _catch_sr(
char const* rawChars, std::size_t size ) noexcept ->
Catch::StringRef {
691 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
692 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
693 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
694 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
695 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
696 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
698 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
699 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
701 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
702 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
704 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
707 #define CATCH_REC_END(...)
708 #define CATCH_REC_OUT
710 #define CATCH_EMPTY()
711 #define CATCH_DEFER(id) id CATCH_EMPTY()
713 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
714 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
715 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
716 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
717 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
718 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
720 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
721 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
722 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
724 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
725 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
726 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
731 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
733 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
735 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
736 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
737 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
738 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
739 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
740 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
741 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
742 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
745 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
746 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
747 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
750 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
751 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
753 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
755 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
756 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
757 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
759 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
760 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
763 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
764 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
766 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
767 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
768 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
769 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
770 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
771 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
772 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
773 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
774 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
775 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
776 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
778 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
780 #define INTERNAL_CATCH_TYPE_GEN\
781 template<typename...> struct TypeList {};\
782 template<typename...Ts>\
783 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
784 template<template<typename...> class...> struct TemplateTypeList{};\
785 template<template<typename...> class...Cs>\
786 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
787 template<typename...>\
789 template<typename...>\
791 template<template<typename...> class, typename...>\
793 template<template<typename...> class, typename>\
796 template<typename T> \
797 struct append<T> { using type = T; };\
798 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
799 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
800 template< template<typename...> class L1, typename...E1, typename...Rest>\
801 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
803 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
804 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
805 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
806 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
808 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
809 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
810 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
811 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
813 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
814 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
815 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
816 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
817 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
818 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
819 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
821 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
822 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
824 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
825 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
826 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
828 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
829 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
830 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
831 static void TestName()
832 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
833 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
834 static void TestName()
836 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
837 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
838 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
839 static void TestName()
840 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
841 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
842 static void TestName()
844 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
845 template<typename Type>\
846 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
848 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
851 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
852 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
853 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
855 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
858 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
859 template<typename Type>\
860 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
862 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
865 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
866 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
867 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
869 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
872 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
873 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
874 template<typename TestType> \
875 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
879 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
880 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
881 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
885 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
886 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
887 template<typename TestType> \
888 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
889 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
890 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
891 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
893 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
894 #define INTERNAL_CATCH_NTTP_0
895 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
896 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
897 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
898 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
899 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
900 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
901 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
902 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
904 #define INTERNAL_CATCH_NTTP_0(signature)
905 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
906 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
907 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
908 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
909 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
910 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
911 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
912 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
919 #include <type_traits>
927 template <
typename Fun,
typename... Args>
929 template <
typename...>
930 std::false_type
static test(...);
933 template <
typename T>
936 template <
typename Fun,
typename... Args>
937 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
939 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
942 template <
typename Func,
typename... U>
946 template <
typename Func,
typename... U>
947 using FunctionReturnType =
typename std::remove_reference<
typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
971 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept -> ITestInvoker*;
991 #if defined(CATCH_CONFIG_DISABLE)
992 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
993 static void TestName()
994 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
996 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1000 void TestName::test()
1001 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1002 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1003 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1005 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1006 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1009 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1011 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1012 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1013 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1015 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1016 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1019 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1020 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1021 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1023 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1024 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1027 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1028 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1029 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1031 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1032 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1035 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1036 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1037 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1039 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1040 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1045 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1046 static void TestName(); \
1047 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1048 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1049 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \
1050 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1051 static void TestName()
1052 #define INTERNAL_CATCH_TESTCASE( ... ) \
1053 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1056 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1057 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1058 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1059 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } \
1060 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1063 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1064 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1065 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1067 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1070 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \
1072 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1073 void TestName::test()
1074 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1075 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1078 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1079 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1080 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1081 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \
1082 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1085 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1086 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1087 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1088 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1089 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1090 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1092 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1093 INTERNAL_CATCH_TYPE_GEN\
1094 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1095 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1096 template<typename...Types> \
1100 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1101 using expander = int[];\
1102 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... }; \
1105 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1106 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1111 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1112 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1114 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1115 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1116 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1118 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1119 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1122 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1123 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1124 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1126 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1127 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1130 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1131 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1132 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1133 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1134 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1135 template<typename TestType> static void TestFuncName(); \
1137 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1138 INTERNAL_CATCH_TYPE_GEN \
1139 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1140 template<typename... Types> \
1142 void reg_tests() { \
1144 using expander = int[]; \
1145 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1146 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1147 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1148 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };\
1151 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1152 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1159 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1160 template<typename TestType> \
1161 static void TestFuncName()
1163 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1164 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1165 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
1167 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1168 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
1171 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1172 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1173 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
1175 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1176 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1179 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1180 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1181 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1182 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1183 template<typename TestType> static void TestFunc(); \
1185 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1186 INTERNAL_CATCH_TYPE_GEN\
1187 template<typename... Types> \
1189 void reg_tests() { \
1191 using expander = int[]; \
1192 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };\
1195 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1196 using TestInit = typename convert<TestName, TmplList>::type; \
1202 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1203 template<typename TestType> \
1204 static void TestFunc()
1206 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1207 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
1209 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1210 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1211 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1212 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1213 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1215 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1216 INTERNAL_CATCH_TYPE_GEN\
1217 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1218 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1219 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1220 template<typename...Types> \
1221 struct TestNameClass{\
1224 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1225 using expander = int[];\
1226 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... }; \
1229 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1230 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1235 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1236 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1238 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1239 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1240 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1242 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1243 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1246 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1247 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1248 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1250 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1251 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1254 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1255 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1256 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1257 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1258 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1259 template<typename TestType> \
1260 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1264 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1265 INTERNAL_CATCH_TYPE_GEN \
1266 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1267 template<typename...Types>\
1268 struct TestNameClass{\
1271 using expander = int[];\
1272 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1273 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1274 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1275 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... }; \
1278 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1279 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
1286 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1287 template<typename TestType> \
1288 void TestName<TestType>::test()
1290 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1291 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1292 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
1294 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1295 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
1298 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1299 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1300 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
1302 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1303 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
1306 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1307 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1308 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1309 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1310 template<typename TestType> \
1311 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1315 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1316 INTERNAL_CATCH_TYPE_GEN\
1317 template<typename...Types>\
1318 struct TestNameClass{\
1321 using expander = int[];\
1322 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... }; \
1325 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1326 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1332 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1333 template<typename TestType> \
1334 void TestName<TestType>::test()
1336 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1337 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
1415 #include <type_traits>
1425 std::ostream&
cout();
1426 std::ostream&
cerr();
1427 std::ostream&
clog();
1433 virtual std::ostream&
stream()
const = 0;
1445 auto str() const ->
std::
string;
1447 template<typename T>
1479 template<
typename E>
1481 static_assert(
sizeof(
int) >=
sizeof(E),
"Cannot serialize enum to int");
1482 std::vector<int> intValues;
1483 intValues.reserve(
values.size() );
1484 for(
auto enumValue :
values )
1485 intValues.push_back(
static_cast<int>( enumValue ) );
1494 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1495 #include <string_view>
1501 #import <Foundation/Foundation.h>
1503 #ifdef __has_feature
1504 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1506 #define CATCH_ARC_ENABLED 0
1509 void arcSafeRelease( NSObject* obj );
1510 id performOptionalSelector(
id obj,
SEL sel );
1512 #if !CATCH_ARC_ENABLED
1513 inline void arcSafeRelease( NSObject* obj ) {
1516 inline id performOptionalSelector(
id obj,
SEL sel ) {
1517 if( [obj respondsToSelector: sel] )
1518 return [obj performSelector: sel];
1521 #define CATCH_UNSAFE_UNRETAINED
1522 #define CATCH_ARC_STRONG
1524 inline void arcSafeRelease( NSObject* ){}
1525 inline id performOptionalSelector(
id obj,
SEL sel ) {
1527 #pragma clang diagnostic push
1528 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1530 if( [obj respondsToSelector: sel] )
1531 return [obj performSelector: sel];
1533 #pragma clang diagnostic pop
1537 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1538 #define CATCH_ARC_STRONG __strong
1545 #pragma warning(push)
1546 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1556 template<
typename T>
1561 template<
typename T>
1563 template<
typename Stream,
typename U>
1564 static auto test(
int)
1565 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1567 template<
typename,
typename>
1568 static auto test(...)->std::false_type;
1571 static const bool value = decltype(test<std::ostream, const T&>(0))::
value;
1574 template<
typename E>
1577 template<
typename T>
1578 typename std::enable_if<
1583 template<
typename T>
1584 typename std::enable_if<
1590 template<
typename T>
1591 typename std::enable_if<
1597 #if defined(_MANAGED)
1598 template<
typename T>
1600 std::string clrReferenceToString( T^ ref ) {
1602 return std::string(
"null");
1603 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1604 cli::pin_ptr<System::Byte> p = &bytes[0];
1605 return std::string(
reinterpret_cast<char const *
>(p), bytes->Length);
1612 template <
typename T,
typename =
void>
1614 template <
typename Fake = T>
1621 rss.operator<<(
value);
1625 template <
typename Fake = T>
1629 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1632 return CATCH_CONFIG_FALLBACK_STRINGIFIER(
value);
1641 template <
typename T>
1643 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1646 template<
typename E>
1651 #if defined(_MANAGED)
1652 template <
typename T>
1654 return ::Catch::StringMaker<T^>::convert(e);
1664 static std::string
convert(
const std::string& str);
1667 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1670 static std::string
convert(std::string_view str);
1676 static std::string convert(
char const * str);
1680 static std::string convert(
char * str);
1683 #ifdef CATCH_CONFIG_WCHAR
1686 static std::string
convert(
const std::wstring& wstr);
1689 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1692 static std::string
convert(std::wstring_view str);
1698 static std::string convert(
wchar_t const * str);
1702 static std::string convert(
wchar_t * str);
1716 static std::string
convert(
signed char const* str) {
1722 static std::string
convert(
unsigned char const* str) {
1727 #if defined(CATCH_CONFIG_CPP17_BYTE)
1729 struct StringMaker<
std::byte> {
1732 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1760 static std::string
convert(
bool b);
1765 static std::string
convert(
char c);
1769 static std::string
convert(
signed char c);
1773 static std::string
convert(
unsigned char c);
1778 static std::string
convert(std::nullptr_t);
1793 template <
typename T>
1795 template <
typename U>
1805 template <
typename R,
typename C>
1816 #if defined(_MANAGED)
1817 template <
typename T>
1818 struct StringMaker<T^> {
1819 static std::string convert( T^ ref ) {
1820 return ::Catch::Detail::clrReferenceToString(ref);
1826 template<
typename InputIterator,
typename Sentinel = InputIterator>
1830 if (first != last) {
1832 for (++first; first != last; ++first)
1842 struct StringMaker<NSString*> {
1843 static std::string convert(NSString * nsstring) {
1846 return std::string(
"@") + [nsstring UTF8String];
1850 struct StringMaker<NSObject*> {
1851 static std::string convert(NSObject* nsObject) {
1857 inline std::string
stringify( NSString* nsstring ) {
1870 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1871 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1872 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1873 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1874 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1875 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1879 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1882 template<
typename T1,
typename T2>
1883 struct StringMaker<
std::pair<T1, T2> > {
1884 static std::string
convert(
const std::pair<T1, T2>& pair) {
1885 ReusableStringStream rss;
1895 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1897 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1900 template<
typename T>
1901 struct StringMaker<
std::optional<T> > {
1902 static std::string
convert(
const std::optional<T>& optional) {
1903 ReusableStringStream rss;
1904 if (optional.has_value()) {
1913 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1916 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1925 struct TupleElementPrinter {
1926 static void print(
const Tuple& tuple, std::ostream& os) {
1927 os << (N ?
", " :
" ")
1929 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1937 struct TupleElementPrinter<Tuple, N, false> {
1938 static void print(
const Tuple&, std::ostream&) {}
1943 template<
typename ...Types>
1944 struct StringMaker<
std::tuple<Types...>> {
1945 static std::string
convert(
const std::tuple<Types...>& tuple) {
1946 ReusableStringStream rss;
1948 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1954 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1956 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1960 struct StringMaker<
std::monostate> {
1961 static std::string
convert(
const std::monostate&) {
1966 template<
typename... Elements>
1967 struct StringMaker<
std::variant<Elements...>> {
1968 static std::string
convert(
const std::variant<Elements...>& variant) {
1969 if (variant.valueless_by_exception()) {
1970 return "{valueless variant}";
1973 [](
const auto&
value) {
1982 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1990 template <
typename...>
1995 template <
typename T,
typename =
void>
1999 template <
typename T>
2004 template <
typename T>
2008 #if defined(_MANAGED) // Managed types are never ranges
2009 template <
typename T>
2011 static const bool value =
false;
2015 template<
typename Range>
2021 template<
typename Allocator>
2037 template<
typename R>
2038 struct StringMaker<R, typename
std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2044 template <
typename T,
int SZ>
2054 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2061 template <
class Ratio>
2062 struct ratio_string {
2063 static std::string symbol();
2066 template <
class Ratio>
2067 std::string ratio_string<Ratio>::symbol() {
2069 rss <<
'[' << Ratio::num <<
'/'
2070 << Ratio::den <<
']';
2074 struct ratio_string<
std::atto> {
2075 static std::string symbol();
2078 struct ratio_string<
std::femto> {
2079 static std::string symbol();
2082 struct ratio_string<
std::pico> {
2083 static std::string symbol();
2086 struct ratio_string<
std::nano> {
2087 static std::string symbol();
2090 struct ratio_string<
std::micro> {
2091 static std::string symbol();
2094 struct ratio_string<
std::milli> {
2095 static std::string symbol();
2100 template<
typename Value,
typename Ratio>
2101 struct StringMaker<
std::chrono::duration<Value, Ratio>> {
2102 static std::string
convert(std::chrono::duration<Value, Ratio>
const& duration) {
2103 ReusableStringStream rss;
2104 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2108 template<
typename Value>
2109 struct StringMaker<
std::chrono::duration<Value, std::ratio<1>>> {
2110 static std::string
convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2111 ReusableStringStream rss;
2112 rss << duration.count() <<
" s";
2116 template<
typename Value>
2117 struct StringMaker<
std::chrono::duration<Value, std::ratio<60>>> {
2118 static std::string
convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2119 ReusableStringStream rss;
2120 rss << duration.count() <<
" m";
2124 template<
typename Value>
2125 struct StringMaker<
std::chrono::duration<Value, std::ratio<3600>>> {
2126 static std::string
convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2127 ReusableStringStream rss;
2128 rss << duration.count() <<
" h";
2136 template<
typename Clock,
typename Duration>
2137 struct StringMaker<
std::chrono::time_point<Clock, Duration>> {
2138 static std::string
convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2143 template<
typename Duration>
2144 struct StringMaker<
std::chrono::time_point<std::chrono::system_clock, Duration>> {
2145 static std::string
convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2146 auto converted = std::chrono::system_clock::to_time_t(time_point);
2149 std::tm timeInfo = {};
2150 gmtime_s(&timeInfo, &converted);
2152 std::tm* timeInfo = std::gmtime(&converted);
2155 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2156 char timeStamp[timeStampSize];
2157 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2160 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2162 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2164 return std::string(timeStamp);
2168 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2170 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2172 template<> struct StringMaker<enumName> { \
2173 static std::string convert( enumName value ) { \
2174 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2175 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2180 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2183 #pragma warning(pop)
2190 #pragma warning(push)
2191 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2192 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2193 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2194 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2195 #pragma warning(disable:4800) // Forcing result to true or false
2221 template<
typename LhsT,
typename RhsT>
2240 template<
typename T>
2243 "chained comparisons are not supported inside assertions, "
2244 "wrap the expression inside parentheses, or decompose it");
2247 template<
typename T>
2250 "chained comparisons are not supported inside assertions, "
2251 "wrap the expression inside parentheses, or decompose it");
2254 template<
typename T>
2257 "chained comparisons are not supported inside assertions, "
2258 "wrap the expression inside parentheses, or decompose it");
2261 template<
typename T>
2264 "chained comparisons are not supported inside assertions, "
2265 "wrap the expression inside parentheses, or decompose it");
2268 template<
typename T>
2271 "chained comparisons are not supported inside assertions, "
2272 "wrap the expression inside parentheses, or decompose it");
2275 template<
typename T>
2278 "chained comparisons are not supported inside assertions, "
2279 "wrap the expression inside parentheses, or decompose it");
2282 template<
typename T>
2285 "chained comparisons are not supported inside assertions, "
2286 "wrap the expression inside parentheses, or decompose it");
2289 template<
typename T>
2292 "chained comparisons are not supported inside assertions, "
2293 "wrap the expression inside parentheses, or decompose it");
2297 template<
typename LhsT>
2313 template<
typename LhsT,
typename RhsT>
2314 auto compareEqual( LhsT
const& lhs, RhsT
const& rhs ) ->
bool {
return static_cast<bool>(lhs == rhs); }
2315 template<
typename T>
2316 auto compareEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2317 template<
typename T>
2318 auto compareEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2319 template<
typename T>
2320 auto compareEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2321 template<
typename T>
2322 auto compareEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2324 template<
typename LhsT,
typename RhsT>
2325 auto compareNotEqual( LhsT
const& lhs, RhsT&& rhs ) ->
bool {
return static_cast<bool>(lhs != rhs); }
2326 template<
typename T>
2327 auto compareNotEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2328 template<
typename T>
2329 auto compareNotEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2330 template<
typename T>
2331 auto compareNotEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2332 template<
typename T>
2333 auto compareNotEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2335 template<
typename LhsT>
2341 template<
typename RhsT>
2349 template<
typename RhsT>
2357 template<
typename RhsT>
2359 return {
static_cast<bool>(
m_lhs > rhs),
m_lhs,
">", rhs };
2361 template<
typename RhsT>
2363 return {
static_cast<bool>(
m_lhs < rhs),
m_lhs,
"<", rhs };
2365 template<
typename RhsT>
2367 return {
static_cast<bool>(
m_lhs >= rhs),
m_lhs,
">=", rhs };
2369 template<
typename RhsT>
2371 return {
static_cast<bool>(
m_lhs <= rhs),
m_lhs,
"<=", rhs };
2373 template <
typename RhsT>
2375 return {
static_cast<bool>(
m_lhs | rhs),
m_lhs,
"|", rhs };
2377 template <
typename RhsT>
2379 return {
static_cast<bool>(
m_lhs & rhs),
m_lhs,
"&", rhs };
2381 template <
typename RhsT>
2383 return {
static_cast<bool>(
m_lhs ^ rhs),
m_lhs,
"^", rhs };
2386 template<
typename RhsT>
2389 "operator&& is not supported inside assertions, "
2390 "wrap the expression inside parentheses, or decompose it");
2393 template<
typename RhsT>
2396 "operator|| is not supported inside assertions, "
2397 "wrap the expression inside parentheses, or decompose it");
2407 template<
typename T>
2413 template<
typename T>
2426 #pragma warning(pop)
2437 class AssertionResult;
2438 struct AssertionInfo;
2440 struct SectionEndInfo;
2442 struct MessageBuilder;
2444 struct AssertionReaction;
2445 struct SourceLineInfo;
2447 struct ITransientExpression;
2448 struct IGeneratorTracker;
2450 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2451 struct BenchmarkInfo;
2452 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2453 struct BenchmarkStats;
2454 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2461 Counts& assertions ) = 0;
2467 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2468 virtual void benchmarkPreparing( std::string
const& name ) = 0;
2469 virtual void benchmarkStarting( BenchmarkInfo
const& info ) = 0;
2470 virtual void benchmarkEnded( BenchmarkStats<>
const& stats ) = 0;
2471 virtual void benchmarkFailed( std::string
const& error ) = 0;
2472 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2495 std::string
const& message,
2520 struct AssertionResultData;
2536 explicit operator bool()
const;
2564 template<
typename T>
2609 bool operator < (
MessageInfo const& other )
const;
2616 template<
typename T>
2630 template<
typename T>
2653 size_t m_captured = 0;
2658 void captureValue(
size_t index, std::string
const&
value );
2660 template<
typename T>
2665 template<
typename T,
typename... Ts>
2668 captureValues( index+1,
values... );
2675 #if !defined(CATCH_CONFIG_DISABLE)
2677 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2678 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2680 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2683 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2688 #define INTERNAL_CATCH_TRY
2689 #define INTERNAL_CATCH_CATCH( capturer )
2691 #else // CATCH_CONFIG_FAST_COMPILE
2693 #define INTERNAL_CATCH_TRY try
2694 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2698 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2701 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2703 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2704 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2705 INTERNAL_CATCH_TRY { \
2706 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2707 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2708 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2709 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2710 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2711 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2712 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2715 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2716 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2717 if( Catch::getResultCapture().lastAssertionPassed() )
2720 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2721 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2722 if( !Catch::getResultCapture().lastAssertionPassed() )
2725 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2727 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2729 static_cast<void>(__VA_ARGS__); \
2730 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2733 catchAssertionHandler.handleUnexpectedInflightException(); \
2735 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2739 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2741 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2742 if( catchAssertionHandler.allowThrows() ) \
2744 static_cast<void>(__VA_ARGS__); \
2745 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2748 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2751 catchAssertionHandler.handleThrowingCallSkipped(); \
2752 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2756 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2758 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2759 if( catchAssertionHandler.allowThrows() ) \
2761 static_cast<void>(expr); \
2762 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2764 catch( exceptionType const& ) { \
2765 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2768 catchAssertionHandler.handleUnexpectedInflightException(); \
2771 catchAssertionHandler.handleThrowingCallSkipped(); \
2772 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2776 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2778 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2779 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2780 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2784 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2785 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2786 varName.captureValues( 0, __VA_ARGS__ )
2789 #define INTERNAL_CATCH_INFO( macroName, log ) \
2790 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2793 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2794 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2798 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2800 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2801 if( catchAssertionHandler.allowThrows() ) \
2803 static_cast<void>(__VA_ARGS__); \
2804 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2807 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2810 catchAssertionHandler.handleThrowingCallSkipped(); \
2811 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2814 #endif // CATCH_CONFIG_DISABLE
2831 std::size_t total()
const;
2832 bool allPassed()
const;
2835 std::size_t passed = 0;
2836 std::size_t failed = 0;
2837 std::size_t failedButOk = 0;
2861 std::string
const& _name );
2866 std::string
const& _name,
2867 std::string
const& ) :
SectionInfo( _lineInfo, _name ) {}
2893 uint64_t m_nanoseconds = 0;
2896 auto getElapsedNanoseconds() const -> uint64_t;
2897 auto getElapsedMicroseconds() const -> uint64_t;
2898 auto getElapsedMilliseconds() const ->
unsigned int;
2899 auto getElapsedSeconds() const ->
double;
2915 explicit operator bool()
const;
2928 #define INTERNAL_CATCH_SECTION( ... ) \
2929 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2930 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2931 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2932 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2934 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2935 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2936 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2937 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2938 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2951 struct ITestCaseRegistry;
2952 struct IExceptionTranslatorRegistry;
2953 struct IExceptionTranslator;
2954 struct IReporterRegistry;
2955 struct IReporterFactory;
2956 struct ITagAliasRegistry;
2957 struct IMutableEnumValuesRegistry;
2959 class StartupExceptionRegistry;
2966 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2968 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2971 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
2976 virtual void registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory ) = 0;
2978 virtual void registerTest(
TestCase const& testInfo ) = 0;
2980 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) = 0;
2981 virtual void registerStartupException() noexcept = 0;
2993 #if defined(CATCH_CONFIG_DISABLE)
2994 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2995 static std::string translatorName( signature )
2998 #include <exception>
3010 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3020 template<
typename T>
3025 : m_translateFunction( translateFunction )
3028 std::string
translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const override {
3029 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3034 std::rethrow_exception(std::current_exception());
3036 return (*it)->translate( it+1, itEnd );
3039 return m_translateFunction( ex );
3045 std::string(*m_translateFunction)( T& );
3049 template<
typename T>
3058 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3059 static std::string translatorName( signature ); \
3060 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3061 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3062 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3063 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3064 static std::string translatorName( signature )
3066 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3071 #include <type_traits>
3078 bool equalityComparisonImpl(
double other)
const;
3081 void setMargin(
double margin);
3084 void setEpsilon(
double epsilon);
3091 Approx operator-()
const;
3108 auto lhs_v =
static_cast<double>(lhs);
3118 friend bool operator != ( T
const& lhs,
Approx const& rhs ) {
3123 friend bool operator != (
Approx const& lhs, T
const& rhs ) {
3128 friend bool operator <= ( T
const& lhs,
Approx const& rhs ) {
3129 return static_cast<double>(lhs) < rhs.
m_value || lhs == rhs;
3133 friend bool operator <= (
Approx const& lhs, T
const& rhs ) {
3134 return lhs.
m_value <
static_cast<double>(rhs) || lhs == rhs;
3138 friend bool operator >= ( T
const& lhs,
Approx const& rhs ) {
3139 return static_cast<double>(lhs) > rhs.
m_value || lhs == rhs;
3143 friend bool operator >= (
Approx const& lhs, T
const& rhs ) {
3144 return lhs.
m_value >
static_cast<double>(rhs) || lhs == rhs;
3149 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3150 setEpsilon(epsilonAsDouble);
3156 double marginAsDouble =
static_cast<double>(newMargin);
3157 setMargin(marginAsDouble);
3163 m_scale =
static_cast<double>(newScale);
3167 std::string toString()
const;
3177 namespace literals {
3198 bool startsWith( std::string
const& s, std::string
const& prefix );
3199 bool startsWith( std::string
const& s,
char prefix );
3200 bool endsWith( std::string
const& s, std::string
const& suffix );
3201 bool endsWith( std::string
const& s,
char suffix );
3202 bool contains( std::string
const& s, std::string
const& infix );
3204 std::string
toLower( std::string
const& s );
3206 std::string
trim( std::string
const& str );
3208 StringRef
trim(StringRef ref);
3211 std::vector<StringRef>
splitStringRef( StringRef str,
char delimiter );
3212 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
3215 pluralise( std::size_t count, std::string
const& label );
3225 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3234 namespace Matchers {
3246 std::string toString()
const;
3250 virtual std::string describe()
const = 0;
3255 # pragma clang diagnostic push
3256 # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3259 template<
typename ObjectT>
3261 virtual bool match( ObjectT
const& arg )
const = 0;
3264 #if defined(__OBJC__)
3269 virtual bool match( NSString* arg )
const = 0;
3274 # pragma clang diagnostic pop
3277 template<
typename T>
3285 template<
typename ArgT>
3287 bool match( ArgT
const& arg )
const override {
3288 for(
auto matcher : m_matchers ) {
3289 if (!matcher->match(arg))
3295 std::string description;
3296 description.reserve( 4 + m_matchers.size()*32 );
3297 description +=
"( ";
3299 for(
auto matcher : m_matchers ) {
3303 description +=
" and ";
3304 description += matcher->toString();
3306 description +=
" )";
3312 copy.m_matchers.push_back( &other );
3318 template<
typename ArgT>
3321 bool match( ArgT
const& arg )
const override {
3322 for(
auto matcher : m_matchers ) {
3323 if (matcher->match(arg))
3329 std::string description;
3330 description.reserve( 4 + m_matchers.size()*32 );
3331 description +=
"( ";
3333 for(
auto matcher : m_matchers ) {
3337 description +=
" or ";
3338 description += matcher->toString();
3340 description +=
" )";
3346 copy.m_matchers.push_back( &other );
3353 template<
typename ArgT>
3358 bool match( ArgT
const& arg )
const override {
3359 return !m_underlyingMatcher.match( arg );
3363 return "not " + m_underlyingMatcher.toString();
3368 template<
typename T>
3372 template<
typename T>
3376 template<
typename T>
3385 using namespace Matchers;
3394 namespace Matchers {
3395 namespace Exception {
3405 bool match(std::exception
const& ex)
const override;
3407 std::string describe()
const override;
3421 namespace Matchers {
3423 namespace Floating {
3425 enum class FloatingPointKind : uint8_t;
3429 bool match(
double const& matchee)
const override;
3430 std::string describe()
const override;
3438 bool match(
double const& matchee)
const override;
3439 std::string describe()
const override;
3454 bool match(
double const& matchee)
const override;
3455 std::string describe()
const override;
3481 #include <functional>
3485 namespace Matchers {
3492 template <
typename T>
3499 :m_predicate(
std::move(elem)),
3503 bool match( T
const& item )
const override {
3504 return m_predicate(item);
3508 return m_description;
3518 template<
typename T>
3532 namespace Matchers {
3534 namespace StdString {
3539 std::string adjustString( std::string
const& str )
const;
3540 std::string caseSensitivitySuffix()
const;
3548 std::string describe()
const override;
3556 bool match( std::string
const& source )
const override;
3560 bool match( std::string
const& source )
const override;
3564 bool match( std::string
const& source )
const override;
3568 bool match( std::string
const& source )
const override;
3573 bool match( std::string
const& matchee )
const override;
3574 std::string describe()
const override;
3598 #include <algorithm>
3601 namespace Matchers {
3604 template<
typename T,
typename Alloc>
3609 bool match(std::vector<T, Alloc>
const &v)
const override {
3610 for (
auto const& el : v) {
3611 if (el == m_comparator) {
3625 template<
typename T,
typename AllocComp,
typename AllocMatch>
3628 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3630 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3632 if (m_comparator.size() > v.size())
3634 for (
auto const& comparator : m_comparator) {
3635 auto present =
false;
3636 for (
const auto& el : v) {
3637 if (el == comparator) {
3655 template<
typename T,
typename AllocComp,
typename AllocMatch>
3658 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3660 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3665 if (m_comparator.size() != v.size())
3667 for (std::size_t i = 0; i < v.size(); ++i)
3668 if (m_comparator[i] != v[i])
3678 template<
typename T,
typename AllocComp,
typename AllocMatch>
3681 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3683 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3684 if (m_comparator.size() != v.size())
3686 for (std::size_t i = 0; i < v.size(); ++i)
3687 if (m_comparator[i] != approx(v[i]))
3701 approx.
margin(newMargin);
3706 approx.
scale(newScale);
3714 template<
typename T,
typename AllocComp,
typename AllocMatch>
3717 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3718 if (m_target.size() != vec.size()) {
3721 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3736 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3741 template<
typename T,
typename Alloc = std::allocator<T>>
3746 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3751 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3756 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3767 template<
typename ArgT,
typename MatcherT>
3776 m_matcher( matcher ),
3777 m_matcherString( matcherString )
3781 auto matcherAsString = m_matcher.toString();
3784 os << m_matcherString;
3786 os << matcherAsString;
3794 template<
typename ArgT,
typename MatcherT>
3802 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3804 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3805 INTERNAL_CATCH_TRY { \
3806 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3807 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3808 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3812 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3814 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3815 if( catchAssertionHandler.allowThrows() ) \
3817 static_cast<void>(__VA_ARGS__ ); \
3818 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3820 catch( exceptionType const& ex ) { \
3821 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3824 catchAssertionHandler.handleUnexpectedInflightException(); \
3827 catchAssertionHandler.handleThrowingCallSkipped(); \
3828 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3851 virtual bool next() = 0;
3859 virtual auto hasGenerator()
const ->
bool = 0;
3869 #include <exception>
3872 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3873 template <
typename Ex>
3878 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
3892 #define CATCH_MAKE_MSG(...) \
3893 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3895 #define CATCH_INTERNAL_ERROR(...) \
3896 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3898 #define CATCH_ERROR(...) \
3899 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3901 #define CATCH_RUNTIME_ERROR(...) \
3902 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3904 #define CATCH_ENFORCE( condition, ... ) \
3905 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3913 #include <exception>
3918 const char*
const m_msg =
"";
3925 const char* what() const noexcept override final;
3928 namespace Generators {
3932 template<
typename T,
typename... Args>
3934 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
3938 template<
typename T>
3946 virtual T
const&
get()
const = 0;
3950 template<
typename T>
3956 T
const&
get()
const override {
3964 template<
typename T>
3967 "FixedValuesGenerator does not support bools because of std::vector<bool>"
3968 "specialization, use SingleValue Generator instead.");
3974 T
const&
get()
const override {
3975 return m_values[m_idx];
3979 return m_idx < m_values.size();
3983 template <
typename T>
3988 m_generator(
std::move(generator))
3991 return m_generator->get();
3994 return m_generator->next();
3998 template <
typename T>
4002 template <
typename T>
4007 template<
typename T>
4010 size_t m_current = 0;
4013 m_generators.emplace_back(std::move(generator));
4016 m_generators.emplace_back(
value(std::forward<T>(val)));
4018 template<
typename U>
4020 populate(T(std::forward<U>(val)));
4022 template<
typename U,
typename... Gs>
4023 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4024 populate(std::forward<U>(valueOrGenerator));
4025 populate(std::forward<Gs>(moreGenerators)...);
4029 template <
typename... Gs>
4031 m_generators.reserve(
sizeof...(Gs));
4032 populate(std::forward<Gs>(moreGenerators)...);
4035 T
const&
get()
const override {
4036 return m_generators[m_current].get();
4040 if (m_current >= m_generators.size()) {
4043 const bool current_status = m_generators[m_current].next();
4044 if (!current_status) {
4047 return m_current < m_generators.size();
4051 template<
typename... Ts>
4052 GeneratorWrapper<std::tuple<Ts...>>
table( std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples ) {
4053 return values<std::tuple<Ts...>>( tuples );
4057 template <
typename T>
4060 template<
typename T,
typename... Gs>
4062 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4064 template<
typename T>
4068 template<
typename T,
typename... Gs>
4070 return makeGenerators(
value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4072 template<
typename T,
typename U,
typename... Gs>
4074 return makeGenerators(
value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4079 template<
typename L>
4084 using UnderlyingType =
typename decltype(generatorExpression())::type;
4092 return generator.
get();
4098 #define GENERATE( ... ) \
4099 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4100 CATCH_INTERNAL_LINEINFO, \
4101 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4102 #define GENERATE_COPY( ... ) \
4103 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4104 CATCH_INTERNAL_LINEINFO, \
4105 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4106 #define GENERATE_REF( ... ) \
4107 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4108 CATCH_INTERNAL_LINEINFO, \
4109 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4115 namespace Generators {
4117 template <
typename T>
4120 size_t m_returned = 0;
4124 m_generator(
std::move(generator)),
4127 assert(target != 0 &&
"Empty generators are not allowed");
4129 T
const&
get()
const override {
4130 return m_generator.
get();
4134 if (m_returned >= m_target) {
4138 const auto success = m_generator.
next();
4142 m_returned = m_target;
4148 template <
typename T>
4153 template <
typename T,
typename Predicate>
4158 template <
typename P = Predicate>
4160 m_generator(
std::move(generator)),
4161 m_predicate(
std::forward<P>(pred))
4163 if (!m_predicate(m_generator.
get())) {
4166 auto has_initial_value = next();
4167 if (!has_initial_value) {
4173 T
const&
get()
const override {
4174 return m_generator.
get();
4178 bool success = m_generator.
next();
4182 while (!m_predicate(m_generator.
get()) && (success = m_generator.
next()) ==
true);
4187 template <
typename T,
typename Predicate>
4192 template <
typename T>
4195 "RepeatGenerator currently does not support bools"
4196 "because of std::vector<bool> specialization");
4200 size_t m_current_repeat = 0;
4201 size_t m_repeat_index = 0;
4204 m_generator(
std::move(generator)),
4205 m_target_repeats(repeats)
4207 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4210 T
const&
get()
const override {
4211 if (m_current_repeat == 0) {
4212 m_returned.push_back(m_generator.
get());
4213 return m_returned.back();
4215 return m_returned[m_repeat_index];
4225 if (m_current_repeat == 0) {
4226 const auto success = m_generator.
next();
4230 return m_current_repeat < m_target_repeats;
4235 if (m_repeat_index == m_returned.size()) {
4239 return m_current_repeat < m_target_repeats;
4243 template <
typename T>
4248 template <
typename T,
typename U,
typename Func>
4256 template <
typename F2 = Func>
4258 m_generator(
std::move(generator)),
4259 m_function(
std::forward<F2>(function)),
4260 m_cache(m_function(m_generator.
get()))
4263 T
const&
get()
const override {
4267 const auto success = m_generator.
next();
4269 m_cache = m_function(m_generator.
get());
4275 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4282 template <
typename T,
typename U,
typename Func>
4283 GeneratorWrapper<T>
map(Func&&
function, GeneratorWrapper<U>&& generator) {
4284 return GeneratorWrapper<T>(
4285 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(
function), std::move(generator))
4289 template <
typename T>
4294 bool m_used_up =
false;
4297 m_chunk_size(size), m_generator(
std::move(generator))
4299 m_chunk.reserve(m_chunk_size);
4300 if (m_chunk_size != 0) {
4301 m_chunk.push_back(m_generator.
get());
4302 for (
size_t i = 1; i < m_chunk_size; ++i) {
4303 if (!m_generator.
next()) {
4306 m_chunk.push_back(m_generator.
get());
4310 std::vector<T>
const&
get()
const override {
4315 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4316 if (!m_generator.
next()) {
4319 m_chunk.push_back(m_generator.
get());
4325 template <
typename T>
4328 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4344 struct IResultCapture;
4347 struct IMutableContext;
4356 virtual IRunner* getRunner() = 0;
4357 virtual IConfigPtr const& getConfig()
const = 0;
4363 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4364 virtual void setRunner(
IRunner* runner ) = 0;
4365 virtual void setConfig(
IConfigPtr const& config ) = 0;
4371 static void createContext();
4401 template<
typename T>
4406 : nullableValue( new( storage ) T( _value ) )
4409 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4417 if( &_other !=
this ) {
4420 nullableValue =
new( storage ) T( *_other );
4426 nullableValue =
new( storage ) T( _value );
4432 nullableValue->~T();
4433 nullableValue =
nullptr;
4442 return nullableValue ? *nullableValue : defaultValue;
4445 bool some()
const {
return nullableValue !=
nullptr; }
4446 bool none()
const {
return nullableValue ==
nullptr; }
4448 bool operator !()
const {
return nullableValue ==
nullptr; }
4449 explicit operator bool()
const {
4455 alignas(
alignof(T))
char storage[
sizeof(T)];
4477 NoAssertions = 0x01,
4500 BeforeStartAndExit = BeforeStart | BeforeExit
4510 virtual std::ostream& stream()
const = 0;
4511 virtual std::string name()
const = 0;
4512 virtual bool includeSuccessfulResults()
const = 0;
4513 virtual bool shouldDebugBreak()
const = 0;
4514 virtual bool warnAboutMissingAssertions()
const = 0;
4515 virtual bool warnAboutNoTests()
const = 0;
4516 virtual int abortAfter()
const = 0;
4517 virtual bool showInvisibles()
const = 0;
4519 virtual double minDuration()
const = 0;
4520 virtual TestSpec
const& testSpec()
const = 0;
4521 virtual bool hasTestFilters()
const = 0;
4522 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4524 virtual unsigned int rngSeed()
const = 0;
4526 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4527 virtual Verbosity verbosity()
const = 0;
4529 virtual bool benchmarkNoAnalysis()
const = 0;
4530 virtual int benchmarkSamples()
const = 0;
4531 virtual double benchmarkConfidenceInterval()
const = 0;
4532 virtual unsigned int benchmarkResamples()
const = 0;
4533 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4536 using IConfigPtr = std::shared_ptr<IConfig const>;
4568 void discard(uint64_t skip);
4584 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4593 namespace Generators {
4595 template <
typename Float>
4598 std::uniform_real_distribution<Float>
m_dist;
4605 static_cast<void>(next());
4608 Float
const&
get()
const override {
4609 return m_current_number;
4612 m_current_number = m_dist(m_rng);
4617 template <
typename Integer>
4620 std::uniform_int_distribution<Integer>
m_dist;
4627 static_cast<void>(next());
4630 Integer
const&
get()
const override {
4631 return m_current_number;
4634 m_current_number = m_dist(m_rng);
4641 template <
typename T>
4643 GeneratorWrapper<T>>::type
4650 template <
typename T>
4652 GeneratorWrapper<T>>::type
4659 template <
typename T>
4671 m_positive(m_step > T(0))
4673 assert(m_current != m_end &&
"Range start and end cannot be equal");
4674 assert(m_step != T(0) &&
"Step size cannot be zero");
4675 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4682 T
const&
get()
const override {
4687 m_current += m_step;
4688 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4692 template <
typename T>
4698 template <
typename T>
4704 template <
typename T>
4707 "IteratorGenerator currently does not support bools"
4708 "because of std::vector<bool> specialization");
4711 size_t m_current = 0;
4713 template <
typename InputIterator,
typename InputSentinel>
4715 if (m_elems.empty()) {
4720 T
const&
get()
const override {
4721 return m_elems[m_current];
4726 return m_current != m_elems.size();
4730 template <
typename InputIterator,
4731 typename InputSentinel,
4732 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4737 template <
typename Container,
4738 typename ResultType =
typename Container::value_type>
4757 #pragma clang diagnostic push
4758 #pragma clang diagnostic ignored "-Wpadded"
4763 struct ITestInvoker;
4769 ShouldFail = 1 << 2,
4772 NonPortable = 1 << 5,
4777 std::string
const& _className,
4778 std::string
const& _description,
4779 std::vector<std::string>
const& _tags,
4782 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4784 bool isHidden()
const;
4785 bool throws()
const;
4786 bool okToFail()
const;
4787 bool expectedToFail()
const;
4789 std::string tagsAsString()
const;
4805 TestCase withName( std::string
const& _newName )
const;
4807 void invoke()
const;
4812 bool operator < (
TestCase const& other )
const;
4815 std::shared_ptr<ITestInvoker>
test;
4819 std::string
const& className,
4825 #pragma clang diagnostic pop
4835 virtual bool aborting()
const = 0;
4844 #import <objc/runtime.h>
4866 class OcMethod :
public ITestInvoker {
4869 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4871 virtual void invoke()
const {
4872 id obj = [[m_cls alloc] init];
4874 performOptionalSelector( obj,
@selector(setUp) );
4875 performOptionalSelector( obj, m_sel );
4876 performOptionalSelector( obj,
@selector(tearDown) );
4878 arcSafeRelease( obj );
4881 virtual ~OcMethod() {}
4889 inline std::string getAnnotation( Class cls,
4890 std::string
const& annotationName,
4891 std::string
const& testCaseName ) {
4892 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4893 SEL sel = NSSelectorFromString( selStr );
4894 arcSafeRelease( selStr );
4895 id value = performOptionalSelector( cls, sel );
4897 return [(NSString*)value UTF8String];
4902 inline std::size_t registerTestMethods() {
4903 std::size_t noTestMethods = 0;
4904 int noClasses = objc_getClassList(
nullptr, 0 );
4906 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4907 objc_getClassList( classes, noClasses );
4909 for(
int c = 0; c < noClasses; c++ ) {
4910 Class cls = classes[c];
4913 Method* methods = class_copyMethodList( cls, &count );
4914 for( u_int m = 0; m < count ; m++ ) {
4915 SEL selector = method_getName(methods[m]);
4916 std::string methodName = sel_getName(selector);
4917 if(
startsWith( methodName,
"Catch_TestCase_" ) ) {
4918 std::string testCaseName = methodName.substr( 15 );
4919 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4920 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4921 const char* className = class_getName( cls );
4930 return noTestMethods;
4933 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4935 namespace Matchers {
4937 namespace NSStringMatchers {
4939 struct StringHolder : MatcherBase<NSString*>{
4940 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4941 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4943 arcSafeRelease( m_substr );
4946 bool match( NSString* str )
const override {
4950 NSString* CATCH_ARC_STRONG m_substr;
4953 struct Equals : StringHolder {
4954 Equals( NSString* substr ) : StringHolder( substr ){}
4956 bool match( NSString* str )
const override {
4957 return (str != nil || m_substr == nil ) &&
4958 [str isEqualToString:m_substr];
4961 std::string describe()
const override {
4962 return "equals string: " +
Catch::Detail::stringify( m_substr );
4967 Contains( NSString* substr ) : StringHolder( substr ){}
4969 bool match( NSString* str )
const override {
4970 return (str != nil || m_substr == nil ) &&
4971 [str rangeOfString:m_substr].location != NSNotFound;
4974 std::string describe()
const override {
4975 return "contains string: " +
Catch::Detail::stringify( m_substr );
4980 StartsWith( NSString* substr ) : StringHolder( substr ){}
4982 bool match( NSString* str )
const override {
4983 return (str != nil || m_substr == nil ) &&
4984 [str rangeOfString:m_substr].location == 0;
4987 std::string describe()
const override {
4988 return "starts with: " +
Catch::Detail::stringify( m_substr );
4992 EndsWith( NSString* substr ) : StringHolder( substr ){}
4994 bool match( NSString* str )
const override {
4995 return (str != nil || m_substr == nil ) &&
4996 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4999 std::string describe()
const override {
5000 return "ends with: " +
Catch::Detail::stringify( m_substr );
5021 using namespace Matchers;
5023 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5028 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5029 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5030 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5034 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5038 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5040 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5046 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5058 #pragma clang diagnostic push
5059 #pragma clang diagnostic ignored "-Wpadded"
5065 #pragma clang diagnostic push
5066 #pragma clang diagnostic ignored "-Wpadded"
5073 class WildcardPattern {
5074 enum WildcardPosition {
5076 WildcardAtStart = 1,
5078 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5084 virtual ~WildcardPattern() =
default;
5085 virtual bool matches( std::string
const& str )
const;
5088 std::string normaliseString( std::string
const& str )
const;
5090 WildcardPosition m_wildcard = NoWildcard;
5091 std::string m_pattern;
5107 explicit Pattern( std::string
const& name );
5109 virtual bool matches( TestCaseInfo
const& testCase )
const = 0;
5110 std::string
const& name()
const;
5112 std::string
const m_name;
5114 using PatternPtr = std::shared_ptr<Pattern>;
5116 class NamePattern :
public Pattern {
5118 explicit NamePattern( std::string
const& name, std::string
const& filterString );
5119 bool matches( TestCaseInfo
const& testCase )
const override;
5121 WildcardPattern m_wildcardPattern;
5124 class TagPattern :
public Pattern {
5126 explicit TagPattern( std::string
const& tag, std::string
const& filterString );
5127 bool matches( TestCaseInfo
const& testCase )
const override;
5132 class ExcludedPattern :
public Pattern {
5134 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5135 bool matches( TestCaseInfo
const& testCase )
const override;
5137 PatternPtr m_underlyingPattern;
5141 std::vector<PatternPtr> m_patterns;
5143 bool matches( TestCaseInfo
const& testCase )
const;
5144 std::string name()
const;
5148 struct FilterMatch {
5150 std::vector<TestCase const*> tests;
5152 using Matches = std::vector<FilterMatch>;
5153 using vectorStrings = std::vector<std::string>;
5155 bool hasFilters()
const;
5156 bool matches( TestCaseInfo
const& testCase )
const;
5157 Matches matchesByFilter( std::vector<TestCase>
const& testCases, IConfig
const& config )
const;
5158 const vectorStrings & getInvalidArgs()
const;
5161 std::vector<Filter> m_filters;
5162 std::vector<std::string> m_invalidArgs;
5163 friend class TestSpecParser;
5168 #pragma clang diagnostic pop
5180 struct ITagAliasRegistry {
5181 virtual ~ITagAliasRegistry();
5183 virtual TagAlias
const*
find( std::string
const& alias )
const = 0;
5184 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
5186 static ITagAliasRegistry
const&
get();
5194 class TestSpecParser {
5195 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5197 Mode lastMode = None;
5198 bool m_exclusion =
false;
5199 std::size_t m_pos = 0;
5200 std::size_t m_realPatternPos = 0;
5202 std::string m_substring;
5203 std::string m_patternName;
5204 std::vector<std::size_t> m_escapeChars;
5205 TestSpec::Filter m_currentFilter;
5206 TestSpec m_testSpec;
5207 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5210 TestSpecParser( ITagAliasRegistry
const& tagAliases );
5212 TestSpecParser& parse( std::string
const& arg );
5213 TestSpec testSpec();
5216 bool visitChar(
char c );
5217 void startNewMode( Mode mode );
5218 bool processNoneChar(
char c );
5219 void processNameChar(
char c );
5220 bool processOtherChar(
char c );
5223 bool isControlChar(
char c )
const;
5224 void saveLastMode();
5225 void revertBackToLastMode();
5230 std::string preprocessPattern();
5232 void addNamePattern();
5234 void addTagPattern();
5236 inline void addCharToPattern(
char c) {
5243 TestSpec parseTestSpec( std::string
const& arg );
5248 #pragma clang diagnostic pop
5258 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5259 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5267 bool listTests =
false;
5268 bool listTags =
false;
5269 bool listReporters =
false;
5270 bool listTestNamesOnly =
false;
5272 bool showSuccessfulTests =
false;
5273 bool shouldDebugBreak =
false;
5274 bool noThrow =
false;
5275 bool showHelp =
false;
5276 bool showInvisibles =
false;
5277 bool filenamesAsTags =
false;
5278 bool libIdentify =
false;
5280 int abortAfter = -1;
5283 bool benchmarkNoAnalysis =
false;
5284 unsigned int benchmarkSamples = 100;
5285 double benchmarkConfidenceInterval = 0.95;
5286 unsigned int benchmarkResamples = 100000;
5287 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5292 double minDuration = -1;
5297 std::string outputFilename;
5299 std::string processName;
5300 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5301 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5303 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5304 #undef CATCH_CONFIG_DEFAULT_REPORTER
5306 std::vector<std::string> testsOrTags;
5307 std::vector<std::string> sectionsToRun;
5310 class Config :
public IConfig {
5314 Config( ConfigData
const& data );
5315 virtual ~Config() =
default;
5317 std::string
const& getFilename()
const;
5319 bool listTests()
const;
5320 bool listTestNamesOnly()
const;
5321 bool listTags()
const;
5322 bool listReporters()
const;
5324 std::string getProcessName()
const;
5325 std::string
const& getReporterName()
const;
5327 std::vector<std::string>
const& getTestsOrTags()
const override;
5328 std::vector<std::string>
const& getSectionsToRun()
const override;
5330 TestSpec
const& testSpec()
const override;
5331 bool hasTestFilters()
const override;
5333 bool showHelp()
const;
5337 std::ostream& stream()
const override;
5338 std::string name()
const override;
5339 bool includeSuccessfulResults()
const override;
5340 bool warnAboutMissingAssertions()
const override;
5341 bool warnAboutNoTests()
const override;
5343 double minDuration()
const override;
5345 unsigned int rngSeed()
const override;
5347 bool shouldDebugBreak()
const override;
5348 int abortAfter()
const override;
5349 bool showInvisibles()
const override;
5351 bool benchmarkNoAnalysis()
const override;
5352 int benchmarkSamples()
const override;
5353 double benchmarkConfidenceInterval()
const override;
5354 unsigned int benchmarkResamples()
const override;
5355 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5359 IStream
const* openStream();
5362 std::unique_ptr<IStream const> m_stream;
5363 TestSpec m_testSpec;
5364 bool m_hasTestFilters =
false;
5376 struct AssertionResultData
5378 AssertionResultData() =
delete;
5380 AssertionResultData(
ResultWas::OfType _resultType, LazyExpression
const& _lazyExpression );
5382 std::string message;
5383 mutable std::string reconstructedExpression;
5384 LazyExpression lazyExpression;
5387 std::string reconstructExpression()
const;
5390 class AssertionResult {
5392 AssertionResult() =
delete;
5393 AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data );
5396 bool succeeded()
const;
5398 bool hasExpression()
const;
5399 bool hasMessage()
const;
5400 std::string getExpression()
const;
5401 std::string getExpressionInMacro()
const;
5402 bool hasExpandedExpression()
const;
5403 std::string getExpandedExpression()
const;
5404 std::string getMessage()
const;
5405 SourceLineInfo getSourceInfo()
const;
5406 StringRef getTestMacroName()
const;
5409 AssertionInfo m_info;
5410 AssertionResultData m_resultData;
5416 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5423 namespace Benchmark {
5424 template <
typename Duration>
5428 Duration upper_bound;
5429 double confidence_interval;
5431 template <
typename Duration2>
5432 operator Estimate<Duration2>()
const {
5433 return { point,
lower_bound, upper_bound, confidence_interval };
5445 namespace Benchmark {
5446 struct OutlierClassification {
5447 int samples_seen = 0;
5451 int high_severe = 0;
5454 return low_severe + low_mild + high_mild + high_severe;
5461 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5468 #include <algorithm>
5472 struct ReporterConfig {
5473 explicit ReporterConfig(
IConfigPtr const& _fullConfig );
5475 ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream );
5477 std::ostream& stream()
const;
5481 std::ostream* m_stream;
5485 struct ReporterPreferences {
5486 bool shouldRedirectStdOut =
false;
5487 bool shouldReportAllAssertions =
false;
5490 template<
typename T>
5491 struct LazyStat : Option<T> {
5492 LazyStat& operator=( T
const& _value ) {
5504 struct TestRunInfo {
5505 TestRunInfo( std::string
const& _name );
5509 GroupInfo( std::string
const& _name,
5510 std::size_t _groupIndex,
5511 std::size_t _groupsCount );
5514 std::size_t groupIndex;
5515 std::size_t groupsCounts;
5518 struct AssertionStats {
5519 AssertionStats( AssertionResult
const& _assertionResult,
5520 std::vector<MessageInfo>
const& _infoMessages,
5521 Totals
const& _totals );
5523 AssertionStats( AssertionStats
const& ) =
default;
5524 AssertionStats( AssertionStats && ) =
default;
5525 AssertionStats& operator = ( AssertionStats
const& ) =
delete;
5526 AssertionStats& operator = ( AssertionStats && ) =
delete;
5527 virtual ~AssertionStats();
5529 AssertionResult assertionResult;
5530 std::vector<MessageInfo> infoMessages;
5534 struct SectionStats {
5535 SectionStats( SectionInfo
const& _sectionInfo,
5536 Counts
const& _assertions,
5537 double _durationInSeconds,
5538 bool _missingAssertions );
5539 SectionStats( SectionStats
const& ) =
default;
5540 SectionStats( SectionStats && ) =
default;
5541 SectionStats& operator = ( SectionStats
const& ) =
default;
5542 SectionStats& operator = ( SectionStats && ) =
default;
5543 virtual ~SectionStats();
5545 SectionInfo sectionInfo;
5547 double durationInSeconds;
5548 bool missingAssertions;
5551 struct TestCaseStats {
5552 TestCaseStats( TestCaseInfo
const& _testInfo,
5553 Totals
const& _totals,
5554 std::string
const& _stdOut,
5555 std::string
const& _stdErr,
5558 TestCaseStats( TestCaseStats
const& ) =
default;
5559 TestCaseStats( TestCaseStats && ) =
default;
5560 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5561 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5562 virtual ~TestCaseStats();
5564 TestCaseInfo testInfo;
5571 struct TestGroupStats {
5572 TestGroupStats( GroupInfo
const& _groupInfo,
5573 Totals
const& _totals,
5575 TestGroupStats( GroupInfo
const& _groupInfo );
5577 TestGroupStats( TestGroupStats
const& ) =
default;
5578 TestGroupStats( TestGroupStats && ) =
default;
5579 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5580 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5581 virtual ~TestGroupStats();
5583 GroupInfo groupInfo;
5588 struct TestRunStats {
5589 TestRunStats( TestRunInfo
const& _runInfo,
5590 Totals
const& _totals,
5593 TestRunStats( TestRunStats
const& ) =
default;
5594 TestRunStats( TestRunStats && ) =
default;
5595 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5596 TestRunStats& operator = ( TestRunStats && ) =
default;
5597 virtual ~TestRunStats();
5599 TestRunInfo runInfo;
5604 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5605 struct BenchmarkInfo {
5607 double estimatedDuration;
5610 unsigned int resamples;
5611 double clockResolution;
5615 template <
class Duration>
5616 struct BenchmarkStats {
5619 std::vector<Duration> samples;
5620 Benchmark::Estimate<Duration> mean;
5621 Benchmark::Estimate<Duration> standardDeviation;
5622 Benchmark::OutlierClassification outliers;
5623 double outlierVariance;
5625 template <
typename Duration2>
5626 operator BenchmarkStats<Duration2>()
const {
5627 std::vector<Duration2> samples2;
5628 samples2.reserve(samples.size());
5629 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5632 std::move(samples2),
5640 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5642 struct IStreamingReporter {
5643 virtual ~IStreamingReporter() =
default;
5649 virtual ReporterPreferences getPreferences()
const = 0;
5651 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5653 virtual void reportInvalidArguments(std::string
const&) {}
5655 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5656 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5658 virtual void testCaseStarting( TestCaseInfo
const& testInfo ) = 0;
5659 virtual void sectionStarting( SectionInfo
const& sectionInfo ) = 0;
5661 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5662 virtual void benchmarkPreparing( std::string
const& ) {}
5663 virtual void benchmarkStarting( BenchmarkInfo
const& ) {}
5664 virtual void benchmarkEnded( BenchmarkStats<>
const& ) {}
5665 virtual void benchmarkFailed( std::string
const& ) {}
5666 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5668 virtual void assertionStarting( AssertionInfo
const& assertionInfo ) = 0;
5671 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5673 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5674 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5675 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5676 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5678 virtual void skipTest( TestCaseInfo
const& testInfo ) = 0;
5681 virtual void fatalErrorEncountered( StringRef name );
5683 virtual bool isMulti()
const;
5685 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5687 struct IReporterFactory {
5688 virtual ~IReporterFactory();
5689 virtual IStreamingReporterPtr create( ReporterConfig
const& config )
const = 0;
5690 virtual std::string getDescription()
const = 0;
5694 struct IReporterRegistry {
5695 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5696 using Listeners = std::vector<IReporterFactoryPtr>;
5698 virtual ~IReporterRegistry();
5699 virtual IStreamingReporterPtr create( std::string
const& name,
IConfigPtr const& config )
const = 0;
5700 virtual FactoryMap
const& getFactories()
const = 0;
5701 virtual Listeners
const& getListeners()
const = 0;
5707 #include <algorithm>
5716 void prepareExpandedExpression(AssertionResult& result);
5719 std::string getFormattedDuration(
double duration );
5722 bool shouldShowDuration( IConfig
const& config,
double duration );
5724 std::string serializeFilters( std::vector<std::string>
const& container );
5726 template<
typename DerivedT>
5727 struct StreamingReporterBase : IStreamingReporter {
5729 StreamingReporterBase( ReporterConfig
const& _config )
5730 : m_config( _config.fullConfig() ),
5731 stream( _config.stream() )
5733 m_reporterPrefs.shouldRedirectStdOut =
false;
5734 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5735 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5738 ReporterPreferences getPreferences()
const override {
5739 return m_reporterPrefs;
5742 static std::set<Verbosity> getSupportedVerbosities() {
5746 ~StreamingReporterBase()
override =
default;
5748 void noMatchingTestCases(std::string
const&)
override {}
5750 void reportInvalidArguments(std::string
const&)
override {}
5752 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5753 currentTestRunInfo = _testRunInfo;
5756 void testGroupStarting(GroupInfo
const& _groupInfo)
override {
5757 currentGroupInfo = _groupInfo;
5760 void testCaseStarting(TestCaseInfo
const& _testInfo)
override {
5761 currentTestCaseInfo = _testInfo;
5763 void sectionStarting(SectionInfo
const& _sectionInfo)
override {
5764 m_sectionStack.push_back(_sectionInfo);
5767 void sectionEnded(SectionStats
const& )
override {
5768 m_sectionStack.pop_back();
5770 void testCaseEnded(TestCaseStats
const& )
override {
5771 currentTestCaseInfo.reset();
5773 void testGroupEnded(TestGroupStats
const& )
override {
5774 currentGroupInfo.reset();
5776 void testRunEnded(TestRunStats
const& )
override {
5777 currentTestCaseInfo.reset();
5778 currentGroupInfo.reset();
5779 currentTestRunInfo.reset();
5782 void skipTest(TestCaseInfo
const&)
override {
5788 std::ostream& stream;
5790 LazyStat<TestRunInfo> currentTestRunInfo;
5791 LazyStat<GroupInfo> currentGroupInfo;
5792 LazyStat<TestCaseInfo> currentTestCaseInfo;
5794 std::vector<SectionInfo> m_sectionStack;
5795 ReporterPreferences m_reporterPrefs;
5798 template<
typename DerivedT>
5799 struct CumulativeReporterBase : IStreamingReporter {
5800 template<
typename T,
typename ChildNodeT>
5802 explicit Node( T
const& _value ) :
value( _value ) {}
5805 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5807 ChildNodes children;
5809 struct SectionNode {
5810 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5811 virtual ~SectionNode() =
default;
5813 bool operator == (SectionNode
const& other)
const {
5814 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5816 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5821 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5822 using Assertions = std::vector<AssertionStats>;
5823 ChildSections childSections;
5824 Assertions assertions;
5829 struct BySectionInfo {
5830 BySectionInfo( SectionInfo
const& other ) : m_other( other ) {}
5831 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
5832 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5833 return ((node->stats.sectionInfo.name == m_other.name) &&
5834 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5836 void operator=(BySectionInfo
const&) =
delete;
5839 SectionInfo
const& m_other;
5842 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5843 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5844 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5846 CumulativeReporterBase( ReporterConfig
const& _config )
5847 : m_config( _config.fullConfig() ),
5848 stream( _config.stream() )
5850 m_reporterPrefs.shouldRedirectStdOut =
false;
5851 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5852 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5854 ~CumulativeReporterBase()
override =
default;
5856 ReporterPreferences getPreferences()
const override {
5857 return m_reporterPrefs;
5860 static std::set<Verbosity> getSupportedVerbosities() {
5864 void testRunStarting( TestRunInfo
const& )
override {}
5865 void testGroupStarting( GroupInfo
const& )
override {}
5867 void testCaseStarting( TestCaseInfo
const& )
override {}
5869 void sectionStarting( SectionInfo
const& sectionInfo )
override {
5870 SectionStats incompleteStats( sectionInfo, Counts(), 0,
false );
5871 std::shared_ptr<SectionNode> node;
5872 if( m_sectionStack.empty() ) {
5873 if( !m_rootSection )
5874 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5875 node = m_rootSection;
5878 SectionNode& parentNode = *m_sectionStack.back();
5880 std::find_if( parentNode.childSections.begin(),
5881 parentNode.childSections.end(),
5882 BySectionInfo( sectionInfo ) );
5883 if( it == parentNode.childSections.end() ) {
5884 node = std::make_shared<SectionNode>( incompleteStats );
5885 parentNode.childSections.push_back( node );
5890 m_sectionStack.push_back( node );
5891 m_deepestSection = std::move(node);
5894 void assertionStarting(AssertionInfo
const&)
override {}
5896 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5897 assert(!m_sectionStack.empty());
5903 prepareExpandedExpression(
const_cast<AssertionResult&
>( assertionStats.assertionResult ) );
5904 SectionNode& sectionNode = *m_sectionStack.back();
5905 sectionNode.assertions.push_back(assertionStats);
5908 void sectionEnded(SectionStats
const& sectionStats)
override {
5909 assert(!m_sectionStack.empty());
5910 SectionNode& node = *m_sectionStack.back();
5911 node.stats = sectionStats;
5912 m_sectionStack.pop_back();
5914 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5915 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5916 assert(m_sectionStack.size() == 0);
5917 node->children.push_back(m_rootSection);
5918 m_testCases.push_back(node);
5919 m_rootSection.reset();
5921 assert(m_deepestSection);
5922 m_deepestSection->stdOut = testCaseStats.stdOut;
5923 m_deepestSection->stdErr = testCaseStats.stdErr;
5925 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5926 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5927 node->children.swap(m_testCases);
5928 m_testGroups.push_back(node);
5930 void testRunEnded(TestRunStats
const& testRunStats)
override {
5931 auto node = std::make_shared<TestRunNode>(testRunStats);
5932 node->children.swap(m_testGroups);
5933 m_testRuns.push_back(node);
5934 testRunEndedCumulative();
5936 virtual void testRunEndedCumulative() = 0;
5938 void skipTest(TestCaseInfo
const&)
override {}
5941 std::ostream& stream;
5942 std::vector<AssertionStats> m_assertions;
5943 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5944 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5945 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5947 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5949 std::shared_ptr<SectionNode> m_rootSection;
5950 std::shared_ptr<SectionNode> m_deepestSection;
5951 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5952 ReporterPreferences m_reporterPrefs;
5956 char const* getLineOfChars() {
5957 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5959 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5960 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5965 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5966 TestEventListenerBase( ReporterConfig
const& _config );
5968 static std::set<Verbosity> getSupportedVerbosities();
5970 void assertionStarting(AssertionInfo
const&)
override;
5971 bool assertionEnded(AssertionStats
const&)
override;
5995 BrightRed = Bright | Red,
5996 BrightGreen = Bright | Green,
5997 LightGrey = Bright | Grey,
5998 BrightWhite = Bright | White,
5999 BrightYellow = Bright | Yellow,
6002 FileName = LightGrey,
6003 Warning = BrightYellow,
6004 ResultError = BrightRed,
6005 ResultSuccess = BrightGreen,
6006 ResultExpectedFailure = Warning,
6011 OriginalExpression = Cyan,
6012 ReconstructedExpression = BrightYellow,
6014 SecondaryText = LightGrey,
6019 Colour( Code _colourCode );
6020 Colour( Colour&& other ) noexcept;
6021 Colour& operator=( Colour&& other ) noexcept;
6025 static void use( Code _colourCode );
6028 bool m_moved =
false;
6031 std::ostream&
operator << ( std::ostream& os, Colour
const& );
6041 template<
typename T>
6042 class ReporterRegistrar {
6044 class ReporterFactory :
public IReporterFactory {
6046 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6047 return std::unique_ptr<T>(
new T( config ) );
6050 std::string getDescription()
const override {
6051 return T::getDescription();
6057 explicit ReporterRegistrar( std::string
const& name ) {
6062 template<
typename T>
6063 class ListenerRegistrar {
6065 class ListenerFactory :
public IReporterFactory {
6067 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6068 return std::unique_ptr<T>(
new T( config ) );
6070 std::string getDescription()
const override {
6071 return std::string();
6077 ListenerRegistrar() {
6083 #if !defined(CATCH_CONFIG_DISABLE)
6085 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
6086 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6087 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6088 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6089 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6091 #define CATCH_REGISTER_LISTENER( listenerType ) \
6092 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6093 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6094 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6095 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6096 #else // CATCH_CONFIG_DISABLE
6098 #define CATCH_REGISTER_REPORTER(name, reporterType)
6099 #define CATCH_REGISTER_LISTENER(listenerType)
6101 #endif // CATCH_CONFIG_DISABLE
6109 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6111 using StreamingReporterBase::StreamingReporterBase;
6113 ~CompactReporter()
override;
6115 static std::string getDescription();
6117 void noMatchingTestCases(std::string
const& spec)
override;
6119 void assertionStarting(AssertionInfo
const&)
override;
6121 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6123 void sectionEnded(SectionStats
const& _sectionStats)
override;
6125 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6134 #if defined(_MSC_VER)
6135 #pragma warning(push)
6136 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
6143 struct SummaryColumn;
6146 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6147 std::unique_ptr<TablePrinter> m_tablePrinter;
6149 ConsoleReporter(ReporterConfig
const& config);
6150 ~ConsoleReporter()
override;
6151 static std::string getDescription();
6153 void noMatchingTestCases(std::string
const& spec)
override;
6155 void reportInvalidArguments(std::string
const&arg)
override;
6157 void assertionStarting(AssertionInfo
const&)
override;
6159 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6161 void sectionStarting(SectionInfo
const& _sectionInfo)
override;
6162 void sectionEnded(SectionStats
const& _sectionStats)
override;
6164 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6165 void benchmarkPreparing(std::string
const& name)
override;
6166 void benchmarkStarting(BenchmarkInfo
const& info)
override;
6167 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6168 void benchmarkFailed(std::string
const& error)
override;
6169 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6171 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6172 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6173 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6174 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6179 void lazyPrintWithoutClosingBenchmarkTable();
6180 void lazyPrintRunInfo();
6181 void lazyPrintGroupInfo();
6182 void printTestCaseAndSectionHeader();
6184 void printClosedHeader(std::string
const& _name);
6185 void printOpenHeader(std::string
const& _name);
6189 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6191 void printTotals(Totals
const& totals);
6192 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row);
6194 void printTotalsDivider(Totals
const& totals);
6195 void printSummaryDivider();
6196 void printTestFilters();
6199 bool m_headerPrinted =
false;
6204 #if defined(_MSC_VER)
6205 #pragma warning(pop)
6216 enum class XmlFormatting {
6222 XmlFormatting
operator | (XmlFormatting lhs, XmlFormatting rhs);
6223 XmlFormatting
operator & (XmlFormatting lhs, XmlFormatting rhs);
6227 enum ForWhat { ForTextNodes, ForAttributes };
6229 XmlEncode( std::string
const& str, ForWhat forWhat = ForTextNodes );
6231 void encodeTo( std::ostream& os )
const;
6233 friend std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode );
6243 class ScopedElement {
6245 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6247 ScopedElement( ScopedElement&& other ) noexcept;
6248 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6252 ScopedElement& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6254 template<
typename T>
6255 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
6256 m_writer->writeAttribute( name, attribute );
6261 mutable XmlWriter* m_writer =
nullptr;
6262 XmlFormatting m_fmt;
6268 XmlWriter( XmlWriter
const& ) =
delete;
6269 XmlWriter& operator=( XmlWriter
const& ) =
delete;
6271 XmlWriter& startElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6273 ScopedElement scopedElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6275 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6277 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute );
6279 XmlWriter& writeAttribute( std::string
const& name,
bool attribute );
6281 template<
typename T>
6282 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
6283 ReusableStringStream rss;
6285 return writeAttribute( name, rss.str() );
6288 XmlWriter& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6290 XmlWriter& writeComment(std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6292 void writeStylesheetRef( std::string
const& url );
6294 XmlWriter& writeBlankLine();
6296 void ensureTagClosed();
6300 void applyFormatting(XmlFormatting fmt);
6302 void writeDeclaration();
6304 void newlineIfNecessary();
6306 bool m_tagIsOpen =
false;
6307 bool m_needsNewline =
false;
6308 std::vector<std::string> m_tags;
6309 std::string m_indent;
6318 class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6320 JunitReporter(ReporterConfig
const& _config);
6322 ~JunitReporter()
override;
6324 static std::string getDescription();
6326 void noMatchingTestCases(std::string
const& )
override;
6328 void testRunStarting(TestRunInfo
const& runInfo)
override;
6330 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6332 void testCaseStarting(TestCaseInfo
const& testCaseInfo)
override;
6333 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6335 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6337 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6339 void testRunEndedCumulative()
override;
6341 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6343 void writeTestCase(TestCaseNode
const& testCaseNode);
6345 void writeSection(std::string
const& className,
6346 std::string
const& rootName,
6347 SectionNode
const& sectionNode);
6349 void writeAssertions(SectionNode
const& sectionNode);
6350 void writeAssertion(AssertionStats
const& stats);
6354 std::string stdOutForSuite;
6355 std::string stdErrForSuite;
6356 unsigned int unexpectedExceptions = 0;
6357 bool m_okToFail =
false;
6366 class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6368 XmlReporter(ReporterConfig
const& _config);
6370 ~XmlReporter()
override;
6372 static std::string getDescription();
6374 virtual std::string getStylesheetRef()
const;
6376 void writeSourceInfo(SourceLineInfo
const& sourceInfo);
6380 void noMatchingTestCases(std::string
const& s)
override;
6382 void testRunStarting(TestRunInfo
const& testInfo)
override;
6384 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6386 void testCaseStarting(TestCaseInfo
const& testInfo)
override;
6388 void sectionStarting(SectionInfo
const& sectionInfo)
override;
6390 void assertionStarting(AssertionInfo
const&)
override;
6392 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6394 void sectionEnded(SectionStats
const& sectionStats)
override;
6396 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6398 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6400 void testRunEnded(TestRunStats
const& testRunStats)
override;
6402 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6403 void benchmarkPreparing(std::string
const& name)
override;
6404 void benchmarkStarting(BenchmarkInfo
const&)
override;
6405 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6406 void benchmarkFailed(std::string
const&)
override;
6407 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6410 Timer m_testCaseTimer;
6412 int m_sectionDepth = 0;
6422 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6447 namespace Benchmark {
6448 template <
typename Clock>
6449 using ClockDuration =
typename Clock::duration;
6450 template <
typename Clock>
6451 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6453 template <
typename Clock>
6454 using TimePoint =
typename Clock::time_point;
6456 using default_clock = std::chrono::steady_clock;
6458 template <
typename Clock>
6460 TimePoint<Clock> operator()()
const {
6461 return Clock::now();
6465 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6475 #if defined(_MSC_VER)
6480 namespace Benchmark {
6481 #if defined(__GNUC__) || defined(__clang__)
6482 template <
typename T>
6483 inline void keep_memory(T* p) {
6484 asm volatile(
"" : :
"g"(p) :
"memory");
6486 inline void keep_memory() {
6487 asm volatile(
"" : : :
"memory");
6491 inline void optimizer_barrier() { keep_memory(); }
6493 #elif defined(_MSC_VER)
6495 #pragma optimize("", off)
6496 template <
typename T>
6497 inline void keep_memory(T* p) {
6499 *
reinterpret_cast<char volatile*
>(p) = *
reinterpret_cast<char const volatile*
>(p);
6502 #pragma optimize("", on)
6505 inline void optimizer_barrier() {
6506 std::atomic_thread_fence(std::memory_order_seq_cst);
6512 template <
typename T>
6513 inline void deoptimize_value(T&& x) {
6517 template <
typename Fn,
typename... Args>
6518 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<!std::is_same<void, decltype(fn(args...))>
::value>::type {
6519 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6522 template <
typename Fn,
typename... Args>
6523 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<std::is_same<void, decltype(fn(args...))>
::value>::type {
6524 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6535 #include <type_traits>
6539 namespace Benchmark {
6541 template <
typename T>
6542 struct CompleteType {
using type = T; };
6544 struct CompleteType<void> {
struct type {}; };
6546 template <
typename T>
6547 using CompleteType_t =
typename CompleteType<T>::type;
6549 template <
typename Result>
6550 struct CompleteInvoker {
6551 template <
typename Fun,
typename... Args>
6552 static Result invoke(Fun&& fun, Args&&... args) {
6553 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6557 struct CompleteInvoker<void> {
6558 template <
typename Fun,
typename... Args>
6559 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6560 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6566 template <
typename Fun,
typename... Args>
6567 CompleteType_t<
FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6568 return CompleteInvoker<
FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6571 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6574 template <
typename Fun>
6575 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6577 return Detail::complete_invoke(std::forward<Fun>(fun));
6588 namespace Benchmark {
6590 struct ChronometerConcept {
6591 virtual void start() = 0;
6592 virtual void finish() = 0;
6593 virtual ~ChronometerConcept() =
default;
6595 template <
typename Clock>
6596 struct ChronometerModel final :
public ChronometerConcept {
6597 void start()
override { started = Clock::now(); }
6598 void finish()
override { finished = Clock::now(); }
6600 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6602 TimePoint<Clock> started;
6603 TimePoint<Clock> finished;
6607 struct Chronometer {
6609 template <
typename Fun>
6610 void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(
int)>()); }
6612 int runs()
const {
return k; }
6614 Chronometer(Detail::ChronometerConcept& meter,
int k)
6619 template <
typename Fun>
6620 void measure(Fun&& fun, std::false_type) {
6621 measure([&fun](
int) {
return fun(); }, std::true_type());
6624 template <
typename Fun>
6625 void measure(Fun&& fun, std::true_type) {
6626 Detail::optimizer_barrier();
6628 for (
int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6630 Detail::optimizer_barrier();
6633 Detail::ChronometerConcept* impl;
6646 namespace Benchmark {
6647 template <
typename Duration>
6648 struct EnvironmentEstimate {
6650 OutlierClassification outliers;
6652 template <
typename Duration2>
6653 operator EnvironmentEstimate<Duration2>()
const {
6654 return { mean, outliers };
6657 template <
typename Clock>
6658 struct Environment {
6659 using clock_type = Clock;
6660 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6661 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6678 #include <type_traits>
6683 namespace Benchmark {
6685 template <
typename T>
6686 using Decay =
typename std::decay<T>::type;
6687 template <
typename T,
typename U>
6689 : std::is_same<Decay<T>, Decay<U>> {};
6698 struct BenchmarkFunction {
6701 virtual void call(Chronometer meter)
const = 0;
6702 virtual callable* clone()
const = 0;
6703 virtual ~callable() =
default;
6705 template <
typename Fun>
6706 struct model :
public callable {
6707 model(Fun&& fun) : fun(
std::move(fun)) {}
6708 model(Fun
const& fun) : fun(fun) {}
6710 model<Fun>* clone()
const override {
return new model<Fun>(*
this); }
6712 void call(Chronometer meter)
const override {
6713 call(meter, is_callable<Fun(Chronometer)>());
6715 void call(Chronometer meter, std::true_type)
const {
6718 void call(Chronometer meter, std::false_type)
const {
6725 struct do_nothing {
void operator()()
const {} };
6727 template <
typename T>
6728 BenchmarkFunction(model<T>* c) : f(c) {}
6732 : f(new model<do_nothing>{ {} }) {}
6734 template <
typename Fun,
6736 BenchmarkFunction(Fun&& fun)
6737 : f(new model<typename
std::decay<Fun>::type>(
std::forward<Fun>(fun))) {}
6739 BenchmarkFunction(BenchmarkFunction&& that)
6740 : f(
std::move(that.f)) {}
6742 BenchmarkFunction(BenchmarkFunction
const& that)
6743 : f(that.f->clone()) {}
6745 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6746 f = std::move(that.f);
6750 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6751 f.reset(that.f->clone());
6755 void operator()(Chronometer meter)
const { f->call(meter); }
6758 std::unique_ptr<callable> f;
6770 #include <type_traits>
6774 namespace Benchmark {
6776 template <
typename Fun>
6778 void operator()(
int k)
const {
6779 for (
int i = 0; i < k; ++i) {
6785 template <
typename Fun>
6786 repeater<typename std::decay<Fun>::type>
repeat(Fun&& fun) {
6787 return { std::forward<Fun>(fun) };
6810 #include <type_traits>
6813 namespace Benchmark {
6814 template <
typename Duration,
typename Result>
6820 template <
typename Clock,
typename Func,
typename... Args>
6821 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<
FunctionReturnType<Func, Args...>>>;
6829 namespace Benchmark {
6831 template <
typename Clock,
typename Fun,
typename... Args>
6832 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6833 auto start = Clock::now();
6834 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6835 auto end = Clock::now();
6836 auto delta = end - start;
6837 return { delta, std::forward<decltype(r)>(r), 1 };
6845 #include <type_traits>
6848 namespace Benchmark {
6850 template <
typename Clock,
typename Fun>
6851 TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6852 return Detail::measure<Clock>(fun, iters);
6854 template <
typename Clock,
typename Fun>
6855 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6856 Detail::ChronometerModel<Clock> meter;
6857 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6859 return { meter.elapsed(), std::move(result), iters };
6862 template <
typename Clock,
typename Fun>
6863 using run_for_at_least_argument_t =
typename std::conditional<is_callable<Fun(Chronometer)>
::value, Chronometer,
int>::type;
6865 struct optimized_away_error : std::exception {
6866 const char* what() const noexcept
override {
6867 return "could not measure benchmark, maybe it was optimized away";
6871 template <
typename Clock,
typename Fun>
6872 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6874 while (iters < (1 << 30)) {
6875 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6877 if (Timing.elapsed >= how_long) {
6878 return { Timing.elapsed, std::move(Timing.result), iters };
6882 throw optimized_away_error{};
6889 #include <algorithm>
6892 namespace Benchmark {
6893 template <
typename Duration>
6894 struct ExecutionPlan {
6895 int iterations_per_sample;
6896 Duration estimated_duration;
6897 Detail::BenchmarkFunction benchmark;
6898 Duration warmup_time;
6899 int warmup_iterations;
6901 template <
typename Duration2>
6902 operator ExecutionPlan<Duration2>()
const {
6903 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6906 template <
typename Clock>
6907 std::vector<FloatDuration<Clock>> run(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
6909 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
Detail::repeat(now<Clock>{}));
6911 std::vector<FloatDuration<Clock>> times;
6912 times.reserve(cfg.benchmarkSamples());
6913 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [
this, env] {
6914 Detail::ChronometerModel<Clock> model;
6915 this->benchmark(Chronometer(model, iterations_per_sample));
6916 auto sample_time = model.elapsed() - env.clock_cost.mean;
6917 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6918 return sample_time / iterations_per_sample;
6937 #include <algorithm>
6938 #include <functional>
6949 namespace Benchmark {
6951 using sample = std::vector<double>;
6953 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6955 template <
typename Iterator>
6956 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6957 std::vector<double> copy(first, last);
6959 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6960 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6962 auto los = q1 - (iqr * 3.);
6963 auto lom = q1 - (iqr * 1.5);
6964 auto him = q3 + (iqr * 1.5);
6965 auto his = q3 + (iqr * 3.);
6967 OutlierClassification o;
6968 for (; first != last; ++first) {
6970 if (t < los) ++o.low_severe;
6971 else if (t < lom) ++o.low_mild;
6972 else if (t > his) ++o.high_severe;
6973 else if (t > him) ++o.high_mild;
6979 template <
typename Iterator>
6980 double mean(Iterator first, Iterator last) {
6981 auto count = last - first;
6982 double sum = std::accumulate(first, last, 0.);
6986 template <
typename URng,
typename Iterator,
typename Estimator>
6987 sample resample(URng&
rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
6988 auto n = last - first;
6989 std::uniform_int_distribution<decltype(
n)> dist(0,
n - 1);
6992 out.reserve(resamples);
6993 std::generate_n(std::back_inserter(out), resamples, [
n, first, &estimator, &dist, &
rng] {
6994 std::vector<double> resampled;
6995 resampled.reserve(
n);
6996 std::generate_n(std::back_inserter(resampled),
n, [first, &dist, &
rng] {
return first[dist(rng)]; });
6997 return estimator(resampled.begin(), resampled.end());
6999 std::sort(out.begin(), out.end());
7003 template <
typename Estimator,
typename Iterator>
7004 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7005 auto n = last - first;
7006 auto second = std::next(first);
7010 for (
auto it = first; it != last; ++it) {
7011 std::iter_swap(it, first);
7012 results.push_back(estimator(second, last));
7018 inline double normal_cdf(
double x) {
7019 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7022 double erfc_inv(
double x);
7024 double normal_quantile(
double p);
7026 template <
typename Iterator,
typename Estimator>
7027 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last, sample
const& resample, Estimator&& estimator) {
7028 auto n_samples = last - first;
7030 double point = estimator(first, last);
7032 if (n_samples == 1)
return { point, point, point, confidence_level };
7034 sample jack = jackknife(estimator, first, last);
7035 double jack_mean = mean(jack.begin(), jack.end());
7036 double sum_squares, sum_cubes;
7037 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> {
7038 auto d = jack_mean - x;
7041 return { sqcb.first + d2, sqcb.second + d3 };
7044 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7045 int n =
static_cast<int>(resample.size());
7046 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) { return x < point; }) / (double)
n;
7048 if (prob_n == 0)
return { point, point, point, confidence_level };
7050 double bias = normal_quantile(prob_n);
7051 double z1 = normal_quantile((1. - confidence_level) / 2.);
7053 auto cumn = [n](
double x) ->
int {
7054 return std::lround(normal_cdf(x) *
n); };
7055 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7056 double b1 = bias + z1;
7057 double b2 = bias - z1;
7060 auto lo = (std::max)(cumn(a1), 0);
7061 auto hi = (std::min)(cumn(a2),
n - 1);
7063 return { point, resample[lo], resample[hi], confidence_level };
7066 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7068 struct bootstrap_analysis {
7069 Estimate<double> mean;
7070 Estimate<double> standard_deviation;
7071 double outlier_variance;
7074 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7080 #include <algorithm>
7087 namespace Benchmark {
7089 template <
typename Clock>
7090 std::vector<double> resolution(
int k) {
7091 std::vector<TimePoint<Clock>> times;
7092 times.reserve(k + 1);
7093 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7095 std::vector<double> deltas;
7097 std::transform(std::next(times.begin()), times.end(), times.begin(),
7098 std::back_inserter(deltas),
7099 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7104 const auto warmup_iterations = 10000;
7105 const auto warmup_time = std::chrono::milliseconds(100);
7106 const auto minimum_ticks = 1000;
7107 const auto warmup_seed = 10000;
7108 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7109 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7110 const auto clock_cost_estimation_tick_limit = 100000;
7111 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7112 const auto clock_cost_estimation_iterations = 10000;
7114 template <
typename Clock>
7116 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7119 template <
typename Clock>
7120 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7121 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7124 FloatDuration<Clock>(mean(r.begin(), r.end())),
7125 classify_outliers(r.begin(), r.end()),
7128 template <
typename Clock>
7129 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7130 auto time_limit = (std::min)(
7131 resolution * clock_cost_estimation_tick_limit,
7132 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7133 auto time_clock = [](
int k) {
7134 return Detail::measure<Clock>([k] {
7135 for (
int i = 0; i < k; ++i) {
7136 volatile auto ignored = Clock::now();
7142 int iters = clock_cost_estimation_iterations;
7143 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7144 std::vector<double> times;
7145 int nsamples =
static_cast<int>(std::ceil(time_limit / r.elapsed));
7146 times.reserve(nsamples);
7147 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7148 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7151 FloatDuration<Clock>(mean(times.begin(), times.end())),
7152 classify_outliers(times.begin(), times.end()),
7156 template <
typename Clock>
7157 Environment<FloatDuration<Clock>> measure_environment() {
7158 static Environment<FloatDuration<Clock>>* env =
nullptr;
7163 auto iters = Detail::warmup<Clock>();
7164 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7165 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7167 env =
new Environment<FloatDuration<Clock>>{ resolution, cost };
7185 #include <algorithm>
7191 namespace Benchmark {
7192 template <
typename Duration>
7193 struct SampleAnalysis {
7194 std::vector<Duration> samples;
7195 Estimate<Duration> mean;
7196 Estimate<Duration> standard_deviation;
7197 OutlierClassification outliers;
7198 double outlier_variance;
7200 template <
typename Duration2>
7201 operator SampleAnalysis<Duration2>()
const {
7202 std::vector<Duration2> samples2;
7203 samples2.reserve(samples.size());
7204 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7206 std::move(samples2),
7218 #include <algorithm>
7223 namespace Benchmark {
7225 template <
typename Duration,
typename Iterator>
7226 SampleAnalysis<Duration> analyse(
const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7227 if (!cfg.benchmarkNoAnalysis()) {
7228 std::vector<double> samples;
7229 samples.reserve(last - first);
7230 std::transform(first, last, std::back_inserter(samples), [](Duration d) {
return d.count(); });
7232 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7233 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7235 auto wrap_estimate = [](Estimate<double> e) {
7236 return Estimate<Duration> {
7238 Duration(e.lower_bound),
7239 Duration(e.upper_bound),
7240 e.confidence_interval,
7243 std::vector<Duration> samples2;
7244 samples2.reserve(samples.size());
7245 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
double d) { return Duration(d); });
7247 std::move(samples2),
7248 wrap_estimate(analysis.mean),
7249 wrap_estimate(analysis.standard_deviation),
7251 analysis.outlier_variance,
7254 std::vector<Duration> samples;
7255 samples.reserve(last - first);
7257 Duration mean = Duration(0);
7259 for (
auto it = first; it < last; ++it, ++i) {
7260 samples.push_back(Duration(*it));
7261 mean += Duration(*it);
7267 Estimate<Duration>{mean, mean, mean, 0.0},
7268 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7269 OutlierClassification{},
7279 #include <algorithm>
7280 #include <functional>
7286 namespace Benchmark {
7288 Benchmark(std::string &&name)
7289 : name(
std::move(name)) {}
7291 template <
class FUN>
7292 Benchmark(std::string &&name, FUN &&func)
7293 : fun(
std::move(func)), name(
std::move(name)) {}
7295 template <
typename Clock>
7296 ExecutionPlan<FloatDuration<Clock>> prepare(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
7297 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7298 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7299 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7300 int new_iters =
static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7301 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7304 template <
typename Clock = default_clock>
7308 auto env = Detail::measure_environment<Clock>();
7312 auto plan = user_code([&] {
7313 return prepare<Clock>(*cfg, env);
7316 BenchmarkInfo info {
7318 plan.estimated_duration.count(),
7319 plan.iterations_per_sample,
7320 cfg->benchmarkSamples(),
7321 cfg->benchmarkResamples(),
7322 env.clock_resolution.mean.count(),
7323 env.clock_cost.mean.count()
7328 auto samples = user_code([&] {
7329 return plan.template run<Clock>(*cfg, env);
7332 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7333 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7338 std::rethrow_exception(std::current_exception());
7343 template <
typename Fun,
7345 Benchmark & operator=(Fun func) {
7346 fun = Detail::BenchmarkFunction(func);
7351 explicit operator bool() {
7356 Detail::BenchmarkFunction fun;
7362 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7363 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7365 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7366 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7367 BenchmarkName = [&](int benchmarkIndex)
7369 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7370 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7379 #include <type_traits>
7382 namespace Benchmark {
7384 template <
typename T,
bool Destruct>
7385 struct ObjectStorage
7389 ObjectStorage() : data() {}
7391 ObjectStorage(
const ObjectStorage& other)
7393 new(&data) T(other.stored_object());
7396 ObjectStorage(ObjectStorage&& other)
7398 new(&data) T(std::move(other.stored_object()));
7401 ~ObjectStorage() { destruct_on_exit<T>(); }
7403 template <
typename... Args>
7404 void construct(Args&&... args)
7406 new (&data) T(std::forward<Args>(args)...);
7409 template <
bool AllowManualDestruction = !Destruct>
7410 typename std::enable_if<AllowManualDestruction>::type destruct()
7412 stored_object().~T();
7417 template <
typename U>
7418 void destruct_on_exit(
typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7420 template <
typename U>
7421 void destruct_on_exit(
typename std::enable_if<!Destruct, U>::type* = 0) { }
7423 T& stored_object() {
7424 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7427 T
const& stored_object()
const {
7428 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7435 template <
typename T>
7436 using storage_for = Detail::ObjectStorage<T, true>;
7438 template <
typename T>
7439 using destructable_object = Detail::ObjectStorage<T, false>;
7447 #endif // ! CATCH_CONFIG_IMPL_ONLY
7453 #pragma clang diagnostic push
7454 #pragma clang diagnostic ignored "-Wweak-vtables"
7465 namespace TestCaseTracking {
7467 struct NameAndLocation {
7469 SourceLineInfo location;
7471 NameAndLocation( std::string
const& _name, SourceLineInfo
const& _location );
7472 friend bool operator==(NameAndLocation
const& lhs, NameAndLocation
const& rhs) {
7473 return lhs.name == rhs.name
7474 && lhs.location == rhs.location;
7480 using ITrackerPtr = std::shared_ptr<ITracker>;
7483 NameAndLocation m_nameAndLocation;
7486 ITracker(NameAndLocation
const& nameAndLoc) :
7487 m_nameAndLocation(nameAndLoc)
7491 NameAndLocation
const& nameAndLocation()
const {
7492 return m_nameAndLocation;
7495 virtual ~ITracker();
7498 virtual bool isComplete()
const = 0;
7499 virtual bool isSuccessfullyCompleted()
const = 0;
7500 virtual bool isOpen()
const = 0;
7501 virtual bool hasChildren()
const = 0;
7502 virtual bool hasStarted()
const = 0;
7504 virtual ITracker& parent() = 0;
7507 virtual void close() = 0;
7508 virtual void fail() = 0;
7509 virtual void markAsNeedingAnotherRun() = 0;
7511 virtual void addChild( ITrackerPtr
const& child ) = 0;
7512 virtual ITrackerPtr findChild( NameAndLocation
const& nameAndLocation ) = 0;
7513 virtual void openChild() = 0;
7516 virtual bool isSectionTracker()
const = 0;
7517 virtual bool isGeneratorTracker()
const = 0;
7520 class TrackerContext {
7528 ITrackerPtr m_rootTracker;
7529 ITracker* m_currentTracker =
nullptr;
7530 RunState m_runState = NotStarted;
7534 ITracker& startRun();
7538 void completeCycle();
7540 bool completedCycle()
const;
7541 ITracker& currentTracker();
7542 void setCurrentTracker( ITracker* tracker );
7545 class TrackerBase :
public ITracker {
7552 CompletedSuccessfully,
7556 using Children = std::vector<ITrackerPtr>;
7557 TrackerContext& m_ctx;
7559 Children m_children;
7560 CycleState m_runState = NotStarted;
7563 TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7565 bool isComplete()
const override;
7566 bool isSuccessfullyCompleted()
const override;
7567 bool isOpen()
const override;
7568 bool hasChildren()
const override;
7569 bool hasStarted()
const override {
7570 return m_runState != NotStarted;
7573 void addChild( ITrackerPtr
const& child )
override;
7575 ITrackerPtr findChild( NameAndLocation
const& nameAndLocation )
override;
7576 ITracker& parent()
override;
7578 void openChild()
override;
7580 bool isSectionTracker()
const override;
7581 bool isGeneratorTracker()
const override;
7585 void close()
override;
7586 void fail()
override;
7587 void markAsNeedingAnotherRun()
override;
7590 void moveToParent();
7594 class SectionTracker :
public TrackerBase {
7595 std::vector<std::string> m_filters;
7596 std::string m_trimmed_name;
7598 SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7600 bool isSectionTracker()
const override;
7602 bool isComplete()
const override;
7604 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation );
7608 void addInitialFilters( std::vector<std::string>
const& filters );
7609 void addNextFilters( std::vector<std::string>
const& filters );
7611 std::vector<std::string>
const& getFilters()
const;
7613 std::string
const& trimmedName()
const;
7618 using TestCaseTracking::ITracker;
7619 using TestCaseTracking::TrackerContext;
7620 using TestCaseTracking::SectionTracker;
7630 struct LeakDetector {
7642 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7647 #if defined(CATCH_CONFIG_USE_ASYNC)
7652 double erf_inv(
double x) {
7656 w = -log((1.0 - x) * (1.0 + x));
7660 p = -3.6444120640178196996e-21;
7661 p = -1.685059138182016589e-19 + p * w;
7662 p = 1.2858480715256400167e-18 + p * w;
7663 p = 1.115787767802518096e-17 + p * w;
7664 p = -1.333171662854620906e-16 + p * w;
7665 p = 2.0972767875968561637e-17 + p * w;
7666 p = 6.6376381343583238325e-15 + p * w;
7667 p = -4.0545662729752068639e-14 + p * w;
7668 p = -8.1519341976054721522e-14 + p * w;
7669 p = 2.6335093153082322977e-12 + p * w;
7670 p = -1.2975133253453532498e-11 + p * w;
7671 p = -5.4154120542946279317e-11 + p * w;
7672 p = 1.051212273321532285e-09 + p * w;
7673 p = -4.1126339803469836976e-09 + p * w;
7674 p = -2.9070369957882005086e-08 + p * w;
7675 p = 4.2347877827932403518e-07 + p * w;
7676 p = -1.3654692000834678645e-06 + p * w;
7677 p = -1.3882523362786468719e-05 + p * w;
7678 p = 0.0001867342080340571352 + p * w;
7679 p = -0.00074070253416626697512 + p * w;
7680 p = -0.0060336708714301490533 + p * w;
7681 p = 0.24015818242558961693 + p * w;
7682 p = 1.6536545626831027356 + p * w;
7683 }
else if (w < 16.000000) {
7684 w = sqrt(w) - 3.250000;
7685 p = 2.2137376921775787049e-09;
7686 p = 9.0756561938885390979e-08 + p * w;
7687 p = -2.7517406297064545428e-07 + p * w;
7688 p = 1.8239629214389227755e-08 + p * w;
7689 p = 1.5027403968909827627e-06 + p * w;
7690 p = -4.013867526981545969e-06 + p * w;
7691 p = 2.9234449089955446044e-06 + p * w;
7692 p = 1.2475304481671778723e-05 + p * w;
7693 p = -4.7318229009055733981e-05 + p * w;
7694 p = 6.8284851459573175448e-05 + p * w;
7695 p = 2.4031110387097893999e-05 + p * w;
7696 p = -0.0003550375203628474796 + p * w;
7697 p = 0.00095328937973738049703 + p * w;
7698 p = -0.0016882755560235047313 + p * w;
7699 p = 0.0024914420961078508066 + p * w;
7700 p = -0.0037512085075692412107 + p * w;
7701 p = 0.005370914553590063617 + p * w;
7702 p = 1.0052589676941592334 + p * w;
7703 p = 3.0838856104922207635 + p * w;
7705 w = sqrt(w) - 5.000000;
7706 p = -2.7109920616438573243e-11;
7707 p = -2.5556418169965252055e-10 + p * w;
7708 p = 1.5076572693500548083e-09 + p * w;
7709 p = -3.7894654401267369937e-09 + p * w;
7710 p = 7.6157012080783393804e-09 + p * w;
7711 p = -1.4960026627149240478e-08 + p * w;
7712 p = 2.9147953450901080826e-08 + p * w;
7713 p = -6.7711997758452339498e-08 + p * w;
7714 p = 2.2900482228026654717e-07 + p * w;
7715 p = -9.9298272942317002539e-07 + p * w;
7716 p = 4.5260625972231537039e-06 + p * w;
7717 p = -1.9681778105531670567e-05 + p * w;
7718 p = 7.5995277030017761139e-05 + p * w;
7719 p = -0.00021503011930044477347 + p * w;
7720 p = -0.00013871931833623122026 + p * w;
7721 p = 1.0103004648645343977 + p * w;
7722 p = 4.8499064014085844221 + p * w;
7727 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7728 auto m = Catch::Benchmark::Detail::mean(first, last);
7729 double variance = std::accumulate(first, last, 0., [m](
double a,
double b) {
7730 double diff = b - m;
7731 return a + diff * diff;
7732 }) / (last - first);
7733 return std::sqrt(variance);
7739 namespace Benchmark {
7742 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7743 auto count = last - first;
7744 double idx = (count - 1) * k / static_cast<double>(q);
7745 int j =
static_cast<int>(idx);
7747 std::nth_element(first, first + j, last);
7749 if (g == 0)
return xj;
7751 auto xj1 = *std::min_element(first + (j + 1), last);
7752 return xj + g * (xj1 - xj);
7755 double erfc_inv(
double x) {
7756 return erf_inv(1.0 - x);
7759 double normal_quantile(
double p) {
7760 static const double ROOT_TWO = std::sqrt(2.0);
7762 double result = 0.0;
7763 assert(p >= 0 && p <= 1);
7764 if (p < 0 || p > 1) {
7768 result = -erfc_inv(2.0 * p);
7775 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7776 double sb = stddev.point;
7777 double mn = mean.point /
n;
7778 double mg_min = mn / 2.;
7779 double sg = (std::min)(mg_min / 4., sb / std::sqrt(
n));
7780 double sg2 = sg * sg;
7781 double sb2 = sb * sb;
7783 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7787 double k0 = -
n * nd;
7788 double k1 = sb2 -
n * sg2 + nd;
7789 double det = k1 * k1 - 4 * sg2 * k0;
7790 return (
int)(-2. * k0 / (k1 +
std::sqrt(det)));
7793 auto var_out = [n, sb2, sg2](
double c) {
7795 return (nc /
n) * (sb2 - nc * sg2);
7798 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7801 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7804 static std::random_device entropy;
7807 auto n =
static_cast<int>(last - first);
7809 auto mean = &Detail::mean<std::vector<double>::iterator>;
7810 auto stddev = &standard_deviation;
7812 #if defined(CATCH_CONFIG_USE_ASYNC)
7813 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7814 auto seed = entropy();
7815 return std::async(std::launch::async, [=] {
7816 std::mt19937
rng(seed);
7817 auto resampled = resample(
rng, n_resamples, first, last, f);
7818 return bootstrap(confidence_level, first, last, resampled, f);
7822 auto mean_future = Estimate(mean);
7823 auto stddev_future = Estimate(stddev);
7825 auto mean_estimate = mean_future.get();
7826 auto stddev_estimate = stddev_future.get();
7828 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7829 auto seed = entropy();
7830 std::mt19937
rng(seed);
7831 auto resampled = resample(
rng, n_resamples, first, last, f);
7832 return bootstrap(confidence_level, first, last, resampled, f);
7835 auto mean_estimate = Estimate(mean);
7836 auto stddev_estimate = Estimate(stddev);
7837 #endif // CATCH_USE_ASYNC
7839 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate,
n);
7841 return { mean_estimate, stddev_estimate, outlier_variance };
7847 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7858 bool marginComparison(
double lhs,
double rhs,
double margin) {
7859 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7868 : m_epsilon(
std::numeric_limits<float>::epsilon()*100 ),
7874 Approx Approx::custom() {
7878 Approx Approx::operator-()
const {
7880 temp.m_value = -temp.m_value;
7884 std::string Approx::toString()
const {
7885 ReusableStringStream rss;
7890 bool Approx::equalityComparisonImpl(
const double other)
const {
7893 return marginComparison(m_value, other, m_margin)
7894 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7897 void Approx::setMargin(
double newMargin) {
7899 "Invalid Approx::margin: " << newMargin <<
'.'
7900 <<
" Approx::Margin has to be non-negative.");
7901 m_margin = newMargin;
7904 void Approx::setEpsilon(
double newEpsilon) {
7906 "Invalid Approx::epsilon: " << newEpsilon <<
'.'
7907 <<
" Approx::epsilon has to be in [0, 1]");
7908 m_epsilon = newEpsilon;
7913 namespace literals {
7923 return value.toString();
7933 bool isDebuggerActive();
7936 #ifdef CATCH_PLATFORM_MAC
7938 #if defined(__i386__) || defined(__x86_64__)
7939 #define CATCH_TRAP() __asm__("int $3\n" : : )
7940 #elif defined(__aarch64__)
7941 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7944 #elif defined(CATCH_PLATFORM_IPHONE)
7947 #if defined(__i386__) || defined(__x86_64__)
7948 #define CATCH_TRAP() __asm__("int $3")
7949 #elif defined(__aarch64__)
7950 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7951 #elif defined(__arm__) && !defined(__thumb__)
7952 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7953 #elif defined(__arm__) && defined(__thumb__)
7954 #define CATCH_TRAP() __asm__(".inst 0xde01")
7957 #elif defined(CATCH_PLATFORM_LINUX)
7961 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7962 #define CATCH_TRAP() asm volatile ("int $3")
7963 #else // Fall back to the generic way.
7966 #define CATCH_TRAP() raise(SIGTRAP)
7968 #elif defined(_MSC_VER)
7969 #define CATCH_TRAP() __debugbreak()
7970 #elif defined(__MINGW32__)
7971 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7972 #define CATCH_TRAP() DebugBreak()
7975 #ifndef CATCH_BREAK_INTO_DEBUGGER
7977 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7979 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
8000 class FatalConditionHandler {
8001 bool m_started =
false;
8006 void engage_platform();
8007 void disengage_platform();
8010 FatalConditionHandler();
8011 ~FatalConditionHandler();
8014 assert(!m_started &&
"Handler cannot be installed twice.");
8020 assert(m_started &&
"Handler cannot be uninstalled without being installed first");
8022 disengage_platform();
8027 class FatalConditionHandlerGuard {
8028 FatalConditionHandler* m_handler;
8030 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8031 m_handler(handler) {
8032 m_handler->engage();
8034 ~FatalConditionHandlerGuard() {
8035 m_handler->disengage();
8046 struct IMutableContext;
8050 class RunContext :
public IResultCapture,
public IRunner {
8053 RunContext( RunContext
const& ) =
delete;
8054 RunContext& operator =( RunContext
const& ) =
delete;
8056 explicit RunContext(
IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8058 ~RunContext()
override;
8060 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8061 void testGroupEnded( std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex, std::size_t groupsCount );
8063 Totals runTest(TestCase
const& testCase);
8066 IStreamingReporter& reporter()
const;
8072 ( AssertionInfo
const& info,
8073 ITransientExpression
const& expr,
8074 AssertionReaction& reaction )
override;
8076 ( AssertionInfo
const& info,
8078 StringRef
const& message,
8079 AssertionReaction& reaction )
override;
8080 void handleUnexpectedExceptionNotThrown
8081 ( AssertionInfo
const& info,
8082 AssertionReaction& reaction )
override;
8083 void handleUnexpectedInflightException
8084 ( AssertionInfo
const& info,
8085 std::string
const& message,
8086 AssertionReaction& reaction )
override;
8087 void handleIncomplete
8088 ( AssertionInfo
const& info )
override;
8090 ( AssertionInfo
const &info,
8092 AssertionReaction &reaction )
override;
8094 bool sectionStarted( SectionInfo
const& sectionInfo, Counts& assertions )
override;
8096 void sectionEnded( SectionEndInfo
const& endInfo )
override;
8097 void sectionEndedEarly( SectionEndInfo
const& endInfo )
override;
8099 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker&
override;
8101 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8102 void benchmarkPreparing( std::string
const& name )
override;
8103 void benchmarkStarting( BenchmarkInfo
const& info )
override;
8104 void benchmarkEnded( BenchmarkStats<>
const& stats )
override;
8105 void benchmarkFailed( std::string
const& error )
override;
8106 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8108 void pushScopedMessage( MessageInfo
const& message )
override;
8109 void popScopedMessage( MessageInfo
const& message )
override;
8111 void emplaceUnscopedMessage( MessageBuilder
const& builder )
override;
8113 std::string getCurrentTestName()
const override;
8115 const AssertionResult* getLastResult()
const override;
8117 void exceptionEarlyReported()
override;
8119 void handleFatalErrorCondition( StringRef message )
override;
8121 bool lastAssertionPassed()
override;
8123 void assertionPassed()
override;
8127 bool aborting() const final;
8131 void runCurrentTest(
std::
string& redirectedCout,
std::
string& redirectedCerr );
8132 void invokeActiveTestCase();
8134 void resetAssertionInfo();
8135 bool testForMissingAssertions( Counts& assertions );
8137 void assertionEnded( AssertionResult const& result );
8139 ( AssertionInfo const &info,
8140 ResultWas::OfType resultType,
8141 ITransientExpression const *expr,
8144 void populateReaction( AssertionReaction& reaction );
8148 void handleUnfinishedSections();
8150 TestRunInfo m_runInfo;
8151 IMutableContext& m_context;
8152 TestCase const* m_activeTestCase =
nullptr;
8153 ITracker* m_testCaseTracker =
nullptr;
8154 Option<AssertionResult> m_lastResult;
8158 IStreamingReporterPtr m_reporter;
8159 std::vector<MessageInfo> m_messages;
8160 std::vector<ScopedMessage> m_messageScopes;
8161 AssertionInfo m_lastAssertionInfo;
8162 std::vector<SectionEndInfo> m_unfinishedSections;
8163 std::vector<ITracker*> m_activeSections;
8164 TrackerContext m_trackerContext;
8165 FatalConditionHandler m_fatalConditionhandler;
8166 bool m_lastAssertionPassed = false;
8167 bool m_shouldReportUnexpected = true;
8168 bool m_includeSuccessfulResults;
8171 void seedRng(IConfig const& config);
8179 auto operator <<( std::ostream& os, ITransientExpression
const& expr ) -> std::ostream& {
8180 expr.streamReconstructedExpression( os );
8186 : m_isNegated( isNegated )
8191 LazyExpression::operator bool()
const {
8192 return m_transientExpression !=
nullptr;
8195 auto operator << ( std::ostream& os, LazyExpression
const& lazyExpr ) -> std::ostream& {
8196 if( lazyExpr.m_isNegated )
8200 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8201 os <<
"(" << *lazyExpr.m_transientExpression <<
")";
8203 os << *lazyExpr.m_transientExpression;
8206 os <<
"{** error - unchecked empty expression requested **}";
8212 ( StringRef
const& macroName,
8213 SourceLineInfo
const& lineInfo,
8214 StringRef capturedExpression,
8216 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8239 CATCH_BREAK_INTO_DEBUGGER();
8242 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8245 CATCH_ERROR(
"Test failure requires aborting test!" );
8274 void handleExceptionMatchExpr( AssertionHandler& handler, std::string
const& str, StringRef
const& matcherString ) {
8283 AssertionResultData::AssertionResultData(
ResultWas::OfType _resultType, LazyExpression
const & _lazyExpression):
8284 lazyExpression(_lazyExpression),
8285 resultType(_resultType) {}
8287 std::string AssertionResultData::reconstructExpression()
const {
8289 if( reconstructedExpression.empty() ) {
8290 if( lazyExpression ) {
8291 ReusableStringStream rss;
8292 rss << lazyExpression;
8293 reconstructedExpression = rss.str();
8296 return reconstructedExpression;
8299 AssertionResult::AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data )
8301 m_resultData( data )
8305 bool AssertionResult::succeeded()
const {
8315 return m_resultData.resultType;
8318 bool AssertionResult::hasExpression()
const {
8319 return !m_info.capturedExpression.empty();
8322 bool AssertionResult::hasMessage()
const {
8323 return !m_resultData.message.empty();
8326 std::string AssertionResult::getExpression()
const {
8328 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8332 expr += m_info.capturedExpression;
8339 std::string AssertionResult::getExpressionInMacro()
const {
8341 if( m_info.macroName.empty() )
8342 expr =
static_cast<std::string
>(m_info.capturedExpression);
8344 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8345 expr += m_info.macroName;
8347 expr += m_info.capturedExpression;
8353 bool AssertionResult::hasExpandedExpression()
const {
8354 return hasExpression() && getExpandedExpression() != getExpression();
8357 std::string AssertionResult::getExpandedExpression()
const {
8358 std::string expr = m_resultData.reconstructExpression();
8364 std::string AssertionResult::getMessage()
const {
8365 return m_resultData.message;
8367 SourceLineInfo AssertionResult::getSourceInfo()
const {
8368 return m_info.lineInfo;
8371 StringRef AssertionResult::getTestMacroName()
const {
8372 return m_info.macroName;
8381 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8388 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8389 handler.handleExpr( expr );
8401 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8402 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8403 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8405 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8408 #pragma clang diagnostic push
8409 #pragma clang diagnostic ignored "-Wweak-vtables"
8410 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8411 #pragma clang diagnostic ignored "-Wshadow"
8425 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8426 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8429 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8430 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8433 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8434 #ifdef __has_include
8435 #if __has_include(<optional>) && __cplusplus >= 201703L
8437 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8459 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8460 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8465 namespace TextFlow {
8467 inline auto isWhitespace(
char c) ->
bool {
8468 static std::string chars =
" \t\n\r";
8469 return chars.find(c) != std::string::npos;
8471 inline auto isBreakableBefore(
char c) ->
bool {
8472 static std::string chars =
"[({<|";
8473 return chars.find(c) != std::string::npos;
8475 inline auto isBreakableAfter(
char c) ->
bool {
8476 static std::string chars =
"])}>.,:;*+-=&/\\";
8477 return chars.find(c) != std::string::npos;
8483 std::vector<std::string> m_strings;
8484 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8485 size_t m_indent = 0;
8486 size_t m_initialIndent = std::string::npos;
8492 Column
const& m_column;
8493 size_t m_stringIndex = 0;
8498 bool m_suffix =
false;
8500 iterator(Column
const& column,
size_t stringIndex)
8502 m_stringIndex(stringIndex) {}
8504 auto line() const ->
std::
string const& {
return m_column.m_strings[m_stringIndex]; }
8506 auto isBoundary(
size_t at)
const ->
bool {
8508 assert(at <= line().size());
8510 return at == line().size() ||
8511 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8512 isBreakableBefore(line()[at]) ||
8513 isBreakableAfter(line()[at - 1]);
8517 assert(m_stringIndex < m_column.m_strings.size());
8520 auto width = m_column.m_width - indent();
8522 if (line()[m_pos] ==
'\n') {
8525 while (m_end < line().size() && line()[m_end] !=
'\n')
8528 if (m_end < m_pos + width) {
8529 m_len = m_end - m_pos;
8532 while (len > 0 && !isBoundary(m_pos + len))
8534 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8546 auto indent() const ->
size_t {
8547 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8548 return initial == std::string::npos ? m_column.m_indent : initial;
8551 auto addIndentAndSuffix(std::string
const &plain)
const -> std::string {
8552 return std::string(indent(),
' ') + (m_suffix ? plain + "-" : plain);
8556 using difference_type = std::ptrdiff_t;
8557 using value_type = std::string;
8558 using pointer = value_type * ;
8559 using reference = value_type & ;
8560 using iterator_category = std::forward_iterator_tag;
8562 explicit iterator(Column
const& column) : m_column(column) {
8563 assert(m_column.m_width > m_column.m_indent);
8564 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8570 auto operator *() const ->
std::
string {
8571 assert(m_stringIndex < m_column.m_strings.size());
8572 assert(m_pos <= m_end);
8573 return addIndentAndSuffix(line().substr(m_pos, m_len));
8576 auto operator ++() -> iterator& {
8578 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8581 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8584 if (m_pos == line().size()) {
8588 if (m_stringIndex < m_column.m_strings.size())
8592 auto operator ++(
int) -> iterator {
8593 iterator prev(*
this);
8598 auto operator ==(iterator
const& other)
const ->
bool {
8600 m_pos == other.m_pos &&
8601 m_stringIndex == other.m_stringIndex &&
8602 &m_column == &other.m_column;
8604 auto operator !=(iterator
const& other)
const ->
bool {
8608 using const_iterator = iterator;
8610 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8612 auto width(
size_t newWidth) -> Column& {
8613 assert(newWidth > 0);
8617 auto indent(
size_t newIndent) -> Column& {
8618 m_indent = newIndent;
8621 auto initialIndent(
size_t newIndent) -> Column& {
8622 m_initialIndent = newIndent;
8626 auto width() const ->
size_t {
return m_width; }
8627 auto begin() const -> iterator {
return iterator(*
this); }
8628 auto end() const -> iterator {
return { *
this, m_strings.size() }; }
8630 inline friend std::ostream&
operator << (std::ostream& os, Column
const& col) {
8632 for (
auto line : col) {
8642 auto operator + (Column
const& other)->Columns;
8644 auto toString() const ->
std::
string {
8645 std::ostringstream oss;
8651 class Spacer :
public Column {
8654 explicit Spacer(
size_t spaceWidth) : Column(
"") {
8660 std::vector<Column> m_columns;
8668 std::vector<Column>
const& m_columns;
8669 std::vector<Column::iterator> m_iterators;
8670 size_t m_activeIterators;
8672 iterator(Columns
const& columns, EndTag)
8673 : m_columns(columns.m_columns),
8674 m_activeIterators(0) {
8675 m_iterators.reserve(m_columns.size());
8677 for (
auto const& col : m_columns)
8678 m_iterators.push_back(col.end());
8682 using difference_type = std::ptrdiff_t;
8683 using value_type = std::string;
8684 using pointer = value_type * ;
8685 using reference = value_type & ;
8686 using iterator_category = std::forward_iterator_tag;
8688 explicit iterator(Columns
const& columns)
8689 : m_columns(columns.m_columns),
8690 m_activeIterators(m_columns.size()) {
8691 m_iterators.reserve(m_columns.size());
8693 for (
auto const& col : m_columns)
8694 m_iterators.push_back(col.begin());
8697 auto operator ==(iterator
const& other)
const ->
bool {
8698 return m_iterators == other.m_iterators;
8700 auto operator !=(iterator
const& other)
const ->
bool {
8701 return m_iterators != other.m_iterators;
8703 auto operator *() const ->
std::
string {
8704 std::string row, padding;
8706 for (
size_t i = 0; i < m_columns.size(); ++i) {
8707 auto width = m_columns[i].width();
8708 if (m_iterators[i] != m_columns[i].end()) {
8709 std::string col = *m_iterators[i];
8710 row += padding + col;
8711 if (col.size() < width)
8712 padding = std::string(width - col.size(),
' ');
8716 padding +=
std::string(width, ' ');
8721 auto operator ++() -> iterator& {
8722 for (
size_t i = 0; i < m_columns.size(); ++i) {
8723 if (m_iterators[i] != m_columns[i].end())
8728 auto operator ++(
int) -> iterator {
8729 iterator prev(*
this);
8734 using const_iterator = iterator;
8736 auto begin() const -> iterator {
return iterator(*
this); }
8737 auto end() const -> iterator {
return { *
this, iterator::EndTag() }; }
8739 auto operator += (Column
const& col) -> Columns& {
8740 m_columns.push_back(col);
8743 auto operator + (Column
const& col) -> Columns {
8744 Columns combined = *
this;
8749 inline friend std::ostream&
operator << (std::ostream& os, Columns
const& cols) {
8752 for (
auto line : cols) {
8762 auto toString() const ->
std::
string {
8763 std::ostringstream oss;
8787 #include <algorithm>
8789 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8790 #define CATCH_PLATFORM_WINDOWS
8793 namespace Catch {
namespace clara {
8797 template<
typename L>
8798 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8800 template<
typename ClassT,
typename ReturnT,
typename... Args>
8801 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8802 static const bool isValid =
false;
8805 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8806 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8807 static const bool isValid =
true;
8808 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8809 using ReturnType = ReturnT;
8817 std::string m_exeName;
8818 std::vector<std::string> m_args;
8821 Args(
int argc,
char const*
const* argv )
8822 : m_exeName(argv[0]),
8823 m_args(argv + 1, argv + argc) {}
8825 Args( std::initializer_list<std::string> args )
8826 : m_exeName( *args.begin() ),
8827 m_args( args.begin()+1, args.end() )
8830 auto exeName() const ->
std::
string {
8837 enum class TokenType {
8845 inline auto isOptPrefix(
char c ) ->
bool {
8847 #ifdef CATCH_PLATFORM_WINDOWS
8855 using Iterator = std::vector<std::string>::const_iterator;
8858 std::vector<Token> m_tokenBuffer;
8861 m_tokenBuffer.resize( 0 );
8864 while( it != itEnd && it->empty() )
8868 auto const &next = *it;
8869 if( isOptPrefix( next[0] ) ) {
8870 auto delimiterPos = next.find_first_of(
" :=" );
8871 if( delimiterPos != std::string::npos ) {
8872 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8873 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8875 if( next[1] !=
'-' && next.size() > 2 ) {
8876 std::string opt =
"- ";
8877 for(
size_t i = 1; i < next.size(); ++i ) {
8879 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8882 m_tokenBuffer.push_back( { TokenType::Option, next } );
8886 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8892 explicit TokenStream( Args
const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8894 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8898 explicit operator bool()
const {
8899 return !m_tokenBuffer.empty() || it != itEnd;
8902 auto count() const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8904 auto operator*() const -> Token {
8905 assert( !m_tokenBuffer.empty() );
8906 return m_tokenBuffer.front();
8909 auto operator->() const -> Token const * {
8910 assert( !m_tokenBuffer.empty() );
8911 return &m_tokenBuffer.front();
8914 auto operator++() -> TokenStream & {
8915 if( m_tokenBuffer.size() >= 2 ) {
8916 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8929 Ok, LogicError, RuntimeError
8933 ResultBase( Type type ) : m_type( type ) {}
8934 virtual ~ResultBase() =
default;
8936 virtual void enforceOk()
const = 0;
8941 template<
typename T>
8942 class ResultValueBase :
public ResultBase {
8944 auto value() const -> T const & {
8950 ResultValueBase( Type type ) : ResultBase( type ) {}
8952 ResultValueBase( ResultValueBase
const &other ) : ResultBase( other ) {
8953 if( m_type == ResultBase::Ok )
8954 new( &m_value ) T( other.m_value );
8957 ResultValueBase( Type, T
const &
value ) : ResultBase( Ok ) {
8958 new( &m_value ) T(
value );
8961 auto operator=( ResultValueBase
const &other ) -> ResultValueBase & {
8962 if( m_type == ResultBase::Ok )
8964 ResultBase::operator=(other);
8965 if( m_type == ResultBase::Ok )
8966 new( &m_value ) T( other.m_value );
8970 ~ResultValueBase()
override {
8981 class ResultValueBase<void> :
public ResultBase {
8983 using ResultBase::ResultBase;
8986 template<
typename T =
void>
8987 class BasicResult :
public ResultValueBase<T> {
8989 template<
typename U>
8990 explicit BasicResult( BasicResult<U>
const &other )
8991 : ResultValueBase<T>( other.type() ),
8992 m_errorMessage( other.errorMessage() )
8994 assert( type() != ResultBase::Ok );
8997 template<
typename U>
8998 static auto ok( U
const &
value ) -> BasicResult {
return { ResultBase::Ok,
value }; }
8999 static auto ok() -> BasicResult {
return { ResultBase::Ok }; }
9000 static auto logicError( std::string
const &message ) -> BasicResult {
return { ResultBase::LogicError, message }; }
9001 static auto runtimeError( std::string
const &message ) -> BasicResult {
return { ResultBase::RuntimeError, message }; }
9003 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9004 auto type() const -> ResultBase::Type {
return m_type; }
9005 auto errorMessage() const ->
std::
string {
return m_errorMessage; }
9008 void enforceOk()
const override {
9012 assert( m_type != ResultBase::LogicError );
9013 assert( m_type != ResultBase::RuntimeError );
9014 if( m_type != ResultBase::Ok )
9018 std::string m_errorMessage;
9020 BasicResult( ResultBase::Type type, std::string
const &message )
9021 : ResultValueBase<T>(type),
9022 m_errorMessage(message)
9024 assert( m_type != ResultBase::Ok );
9027 using ResultValueBase<T>::ResultValueBase;
9028 using ResultBase::m_type;
9031 enum class ParseResultType {
9032 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9038 ParseState( ParseResultType type, TokenStream
const &remainingTokens )
9040 m_remainingTokens( remainingTokens )
9043 auto type() const -> ParseResultType {
return m_type; }
9044 auto remainingTokens() const -> TokenStream {
return m_remainingTokens; }
9047 ParseResultType m_type;
9048 TokenStream m_remainingTokens;
9051 using Result = BasicResult<void>;
9052 using ParserResult = BasicResult<ParseResultType>;
9053 using InternalParseResult = BasicResult<ParseState>;
9055 struct HelpColumns {
9060 template<
typename T>
9061 inline auto convertInto( std::string
const &source, T& target ) -> ParserResult {
9062 std::stringstream ss;
9066 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9068 return ParserResult::ok( ParseResultType::Matched );
9070 inline auto convertInto( std::string
const &source, std::string& target ) -> ParserResult {
9072 return ParserResult::ok( ParseResultType::Matched );
9074 inline auto convertInto( std::string
const &source,
bool &target ) -> ParserResult {
9075 std::string srcLC = source;
9076 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9077 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9079 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9082 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9083 return ParserResult::ok( ParseResultType::Matched );
9085 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9086 template<
typename T>
9087 inline auto convertInto( std::string
const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9089 auto result = convertInto( source, temp );
9091 target = std::move(temp);
9094 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9096 struct NonCopyable {
9097 NonCopyable() =
default;
9098 NonCopyable( NonCopyable
const & ) =
delete;
9099 NonCopyable( NonCopyable && ) =
delete;
9100 NonCopyable &operator=( NonCopyable
const & ) =
delete;
9101 NonCopyable &operator=( NonCopyable && ) =
delete;
9104 struct BoundRef : NonCopyable {
9105 virtual ~BoundRef() =
default;
9106 virtual auto isContainer() const ->
bool {
return false; }
9107 virtual auto isFlag() const ->
bool {
return false; }
9109 struct BoundValueRefBase : BoundRef {
9110 virtual auto setValue( std::string
const &arg ) -> ParserResult = 0;
9112 struct BoundFlagRefBase : BoundRef {
9113 virtual auto setFlag(
bool flag ) -> ParserResult = 0;
9114 virtual auto isFlag() const ->
bool {
return true; }
9117 template<
typename T>
9118 struct BoundValueRef : BoundValueRefBase {
9121 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9123 auto setValue( std::string
const &arg ) -> ParserResult
override {
9124 return convertInto( arg, m_ref );
9128 template<
typename T>
9129 struct BoundValueRef<
std::vector<T>> : BoundValueRefBase {
9130 std::vector<T> &m_ref;
9132 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9134 auto isContainer() const ->
bool override {
return true; }
9136 auto setValue( std::string
const &arg ) -> ParserResult
override {
9138 auto result = convertInto( arg, temp );
9140 m_ref.push_back( temp );
9145 struct BoundFlagRef : BoundFlagRefBase {
9148 explicit BoundFlagRef(
bool &ref ) : m_ref( ref ) {}
9150 auto setFlag(
bool flag ) -> ParserResult
override {
9152 return ParserResult::ok( ParseResultType::Matched );
9156 template<
typename ReturnType>
9157 struct LambdaInvoker {
9160 template<
typename L,
typename ArgType>
9161 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9162 return lambda( arg );
9167 struct LambdaInvoker<void> {
9168 template<
typename L,
typename ArgType>
9169 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9171 return ParserResult::ok( ParseResultType::Matched );
9175 template<
typename ArgType,
typename L>
9176 inline auto invokeLambda( L
const &lambda, std::string
const &arg ) -> ParserResult {
9178 auto result = convertInto( arg, temp );
9181 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9184 template<
typename L>
9185 struct BoundLambda : BoundValueRefBase {
9188 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9189 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9191 auto setValue( std::string
const &arg ) -> ParserResult
override {
9192 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9196 template<
typename L>
9197 struct BoundFlagLambda : BoundFlagRefBase {
9200 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9201 static_assert( std::is_same<
typename UnaryLambdaTraits<L>::ArgType,
bool>::
value,
"flags must be boolean" );
9203 explicit BoundFlagLambda( L
const &lambda ) : m_lambda( lambda ) {}
9205 auto setFlag(
bool flag ) -> ParserResult
override {
9206 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9210 enum class Optionality { Optional, Required };
9216 virtual ~ParserBase() =
default;
9217 virtual auto validate() const -> Result {
return Result::ok(); }
9218 virtual auto parse( std::string
const& exeName, TokenStream
const &tokens)
const -> InternalParseResult = 0;
9219 virtual auto cardinality() const ->
size_t {
return 1; }
9221 auto parse( Args
const &args )
const -> InternalParseResult {
9222 return parse( args.exeName(), TokenStream( args ) );
9226 template<
typename DerivedT>
9227 class ComposableParserImpl :
public ParserBase {
9229 template<
typename T>
9230 auto operator|( T
const &other )
const -> Parser;
9232 template<
typename T>
9233 auto operator+( T
const &other )
const -> Parser;
9237 template<
typename DerivedT>
9238 class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9240 Optionality m_optionality = Optionality::Optional;
9241 std::shared_ptr<BoundRef> m_ref;
9243 std::string m_description;
9245 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &ref ) : m_ref( ref ) {}
9248 template<
typename T>
9249 ParserRefImpl( T &ref, std::string
const &hint )
9250 : m_ref(
std::make_shared<BoundValueRef<T>>( ref ) ),
9254 template<
typename LambdaT>
9255 ParserRefImpl( LambdaT
const &ref, std::string
const &hint )
9256 : m_ref(
std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9260 auto operator()( std::string
const &description ) -> DerivedT & {
9261 m_description = description;
9262 return static_cast<DerivedT &
>( *this );
9265 auto optional() -> DerivedT & {
9266 m_optionality = Optionality::Optional;
9267 return static_cast<DerivedT &
>( *this );
9270 auto required() -> DerivedT & {
9271 m_optionality = Optionality::Required;
9272 return static_cast<DerivedT &
>( *this );
9275 auto isOptional() const ->
bool {
9276 return m_optionality == Optionality::Optional;
9279 auto cardinality() const ->
size_t override {
9280 if( m_ref->isContainer() )
9286 auto hint() const ->
std::
string {
return m_hint; }
9289 class ExeName :
public ComposableParserImpl<ExeName> {
9290 std::shared_ptr<std::string> m_name;
9291 std::shared_ptr<BoundValueRefBase> m_ref;
9293 template<
typename LambdaT>
9294 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9295 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9299 ExeName() : m_name(
std::make_shared<
std::string>(
"<executable>" ) ) {}
9301 explicit ExeName( std::string &ref ) : ExeName() {
9302 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9305 template<
typename LambdaT>
9306 explicit ExeName( LambdaT
const& lambda ) : ExeName() {
9307 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9311 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9312 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9315 auto name() const ->
std::
string {
return *m_name; }
9316 auto set( std::string
const& newName ) -> ParserResult {
9318 auto lastSlash = newName.find_last_of(
"\\/" );
9319 auto filename = ( lastSlash == std::string::npos )
9321 : newName.substr( lastSlash+1 );
9325 return m_ref->setValue( filename );
9327 return ParserResult::ok( ParseResultType::Matched );
9331 class Arg :
public ParserRefImpl<Arg> {
9333 using ParserRefImpl::ParserRefImpl;
9335 auto parse( std::string
const &, TokenStream
const &tokens )
const -> InternalParseResult
override {
9336 auto validationResult = validate();
9337 if( !validationResult )
9338 return InternalParseResult( validationResult );
9340 auto remainingTokens = tokens;
9341 auto const &token = *remainingTokens;
9342 if( token.type != TokenType::Argument )
9343 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9345 assert( !m_ref->isFlag() );
9346 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9348 auto result = valueRef->setValue( remainingTokens->token );
9350 return InternalParseResult( result );
9352 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9356 inline auto normaliseOpt( std::string
const &optName ) -> std::string {
9357 #ifdef CATCH_PLATFORM_WINDOWS
9358 if( optName[0] ==
'/' )
9359 return "-" + optName.substr( 1 );
9365 class Opt :
public ParserRefImpl<Opt> {
9367 std::vector<std::string> m_optNames;
9370 template<
typename LambdaT>
9371 explicit Opt( LambdaT
const &ref ) : ParserRefImpl(
std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9373 explicit Opt(
bool &ref ) : ParserRefImpl(
std::make_shared<BoundFlagRef>( ref ) ) {}
9375 template<
typename LambdaT>
9376 Opt( LambdaT
const &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9378 template<
typename T>
9379 Opt( T &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9381 auto operator[]( std::string
const &optName ) -> Opt & {
9382 m_optNames.push_back( optName );
9386 auto getHelpColumns() const ->
std::vector<HelpColumns> {
9387 std::ostringstream oss;
9389 for(
auto const &opt : m_optNames ) {
9396 if( !m_hint.empty() )
9397 oss <<
" <" << m_hint <<
">";
9398 return { { oss.str(), m_description } };
9401 auto isMatch( std::string
const &optToken )
const ->
bool {
9402 auto normalisedToken = normaliseOpt( optToken );
9403 for(
auto const &name : m_optNames ) {
9404 if( normaliseOpt( name ) == normalisedToken )
9410 using ParserBase::parse;
9412 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9413 auto validationResult = validate();
9414 if( !validationResult )
9415 return InternalParseResult( validationResult );
9417 auto remainingTokens = tokens;
9418 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9419 auto const &token = *remainingTokens;
9420 if( isMatch(token.token ) ) {
9421 if( m_ref->isFlag() ) {
9422 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>( m_ref.get() );
9423 auto result = flagRef->setFlag(
true );
9425 return InternalParseResult( result );
9426 if( result.value() == ParseResultType::ShortCircuitAll )
9427 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9429 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9431 if( !remainingTokens )
9432 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9433 auto const &argToken = *remainingTokens;
9434 if( argToken.type != TokenType::Argument )
9435 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9436 auto result = valueRef->setValue( argToken.token );
9438 return InternalParseResult( result );
9439 if( result.value() == ParseResultType::ShortCircuitAll )
9440 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9442 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9445 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9448 auto validate() const -> Result
override {
9449 if( m_optNames.empty() )
9450 return Result::logicError(
"No options supplied to Opt" );
9451 for(
auto const &name : m_optNames ) {
9453 return Result::logicError(
"Option name cannot be empty" );
9454 #ifdef CATCH_PLATFORM_WINDOWS
9455 if( name[0] !=
'-' && name[0] !=
'/' )
9456 return Result::logicError(
"Option name must begin with '-' or '/'" );
9458 if( name[0] !=
'-' )
9459 return Result::logicError(
"Option name must begin with '-'" );
9462 return ParserRefImpl::validate();
9467 Help(
bool &showHelpFlag )
9468 : Opt([&]( bool flag ) {
9469 showHelpFlag = flag;
9470 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9473 static_cast<Opt &
>( *this )
9474 (
"display usage information")
9475 [
"-?"][
"-h"][
"--help"]
9480 struct Parser : ParserBase {
9482 mutable ExeName m_exeName;
9483 std::vector<Opt> m_options;
9484 std::vector<Arg> m_args;
9486 auto operator|=( ExeName
const &exeName ) -> Parser & {
9487 m_exeName = exeName;
9491 auto operator|=( Arg
const &arg ) -> Parser & {
9492 m_args.push_back(arg);
9496 auto operator|=( Opt
const &opt ) -> Parser & {
9497 m_options.push_back(opt);
9501 auto operator|=( Parser
const &other ) -> Parser & {
9502 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9503 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9507 template<
typename T>
9508 auto operator|( T
const &other )
const -> Parser {
9509 return Parser( *
this ) |= other;
9513 template<
typename T>
9515 template<
typename T>
9518 auto getHelpColumns() const ->
std::vector<HelpColumns> {
9519 std::vector<HelpColumns> cols;
9520 for (
auto const &o : m_options) {
9521 auto childCols = o.getHelpColumns();
9522 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9527 void writeToStream( std::ostream &os )
const {
9528 if (!m_exeName.name().empty()) {
9529 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9530 bool required =
true, first =
true;
9531 for(
auto const &arg : m_args ) {
9536 if( arg.isOptional() && required ) {
9540 os <<
"<" << arg.hint() <<
">";
9541 if( arg.cardinality() == 0 )
9546 if( !m_options.empty() )
9548 os <<
"\n\nwhere options are:" << std::endl;
9551 auto rows = getHelpColumns();
9552 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9553 size_t optWidth = 0;
9554 for(
auto const &cols : rows )
9555 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9557 optWidth = (std::min)(optWidth, consoleWidth/2);
9559 for(
auto const &cols : rows ) {
9561 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9562 TextFlow::Spacer(4) +
9563 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9564 os << row << std::endl;
9568 friend auto operator<<( std::ostream &os, Parser
const &parser ) -> std::ostream& {
9569 parser.writeToStream( os );
9573 auto validate() const -> Result
override {
9574 for(
auto const &opt : m_options ) {
9575 auto result = opt.validate();
9579 for(
auto const &arg : m_args ) {
9580 auto result = arg.validate();
9584 return Result::ok();
9587 using ParserBase::parse;
9589 auto parse( std::string
const& exeName, TokenStream
const &tokens )
const -> InternalParseResult
override {
9592 ParserBase
const* parser =
nullptr;
9595 const size_t totalParsers = m_options.size() + m_args.size();
9596 assert( totalParsers < 512 );
9598 ParserInfo parseInfos[512];
9602 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9603 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9606 m_exeName.set( exeName );
9608 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9609 while( result.value().remainingTokens() ) {
9610 bool tokenParsed =
false;
9612 for(
size_t i = 0; i < totalParsers; ++i ) {
9613 auto& parseInfo = parseInfos[i];
9614 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9615 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9618 if (result.value().type() != ParseResultType::NoMatch) {
9626 if( result.value().type() == ParseResultType::ShortCircuitAll )
9629 return InternalParseResult::runtimeError(
"Unrecognised token: " + result.value().remainingTokens()->token );
9636 template<
typename DerivedT>
9637 template<
typename T>
9639 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9644 using detail::Parser;
9656 using detail::ExeName;
9662 using detail::ParseResultType;
9665 using detail::ParserResult;
9671 #pragma clang diagnostic pop
9675 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9676 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9677 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9683 clara::Parser makeCommandLineParser( ConfigData& config );
9693 clara::Parser makeCommandLineParser( ConfigData& config ) {
9695 using namespace clara;
9697 auto const setWarning = [&]( std::string
const& warning ) {
9698 auto warningSet = [&]() {
9699 if( warning ==
"NoAssertions" )
9702 if ( warning ==
"NoTests" )
9709 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9710 config.warnings =
static_cast<WarnAbout::What>( config.warnings | warningSet );
9711 return ParserResult::ok( ParseResultType::Matched );
9713 auto const loadTestNamesFromFile = [&]( std::string
const& filename ) {
9714 std::ifstream f( filename.c_str() );
9716 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'" );
9719 while( std::getline( f, line ) ) {
9721 if( !line.empty() && !
startsWith( line,
'#' ) ) {
9723 line =
'"' + line + '"';
9724 config.testsOrTags.push_back( line );
9725 config.testsOrTags.emplace_back(
"," );
9729 if(!config.testsOrTags.empty())
9730 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9732 return ParserResult::ok( ParseResultType::Matched );
9734 auto const setTestOrder = [&]( std::string
const& order ) {
9742 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'" );
9743 return ParserResult::ok( ParseResultType::Matched );
9745 auto const setRngSeed = [&]( std::string
const& seed ) {
9746 if( seed !=
"time" )
9747 return clara::detail::convertInto( seed, config.rngSeed );
9748 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9749 return ParserResult::ok( ParseResultType::Matched );
9751 auto const setColourUsage = [&]( std::string
const& useColour ) {
9752 auto mode =
toLower( useColour );
9756 else if( mode ==
"no" )
9758 else if( mode ==
"auto" )
9761 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9762 return ParserResult::ok( ParseResultType::Matched );
9764 auto const setWaitForKeypress = [&]( std::string
const& keypress ) {
9765 auto keypressLc =
toLower( keypress );
9766 if (keypressLc ==
"never")
9768 else if( keypressLc ==
"start" )
9770 else if( keypressLc ==
"exit" )
9772 else if( keypressLc ==
"both" )
9775 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9776 return ParserResult::ok( ParseResultType::Matched );
9778 auto const setVerbosity = [&]( std::string
const& verbosity ) {
9779 auto lcVerbosity =
toLower( verbosity );
9780 if( lcVerbosity ==
"quiet" )
9782 else if( lcVerbosity ==
"normal" )
9784 else if( lcVerbosity ==
"high" )
9787 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9788 return ParserResult::ok( ParseResultType::Matched );
9790 auto const setReporter = [&]( std::string
const& reporter ) {
9793 auto lcReporter =
toLower( reporter );
9794 auto result = factories.find( lcReporter );
9796 if( factories.end() != result )
9797 config.reporterName = lcReporter;
9799 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9800 return ParserResult::ok( ParseResultType::Matched );
9804 = ExeName( config.processName )
9805 | Help( config.showHelp )
9806 | Opt( config.listTests )
9807 ["-l"]["--list-tests"]
9808 (
"list all/matching test cases" )
9809 | Opt( config.listTags )
9810 ["-t"]["--list-tags"]
9811 (
"list all/matching tags" )
9812 | Opt( config.showSuccessfulTests )
9814 (
"include successful tests in output" )
9815 | Opt( config.shouldDebugBreak )
9817 (
"break into debugger on failure" )
9818 | Opt( config.noThrow )
9820 (
"skip exception tests" )
9821 | Opt( config.showInvisibles )
9822 ["-i"]["--invisibles"]
9823 (
"show invisibles (tabs, newlines)" )
9824 | Opt( config.outputFilename,
"filename" )
9826 (
"output filename" )
9827 | Opt( setReporter,
"name" )
9828 ["-r"]["--reporter"]
9829 (
"reporter to use (defaults to console)" )
9830 | Opt( config.name,
"name" )
9833 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9835 (
"abort at first failure" )
9836 | Opt( [&](
int x ){ config.abortAfter = x; },
"no. failures" )
9838 (
"abort after x failures" )
9839 | Opt( setWarning,
"warning name" )
9841 (
"enable warnings" )
9843 [
"-d"][
"--durations"]
9844 (
"show test durations" )
9845 | Opt( config.minDuration,
"seconds" )
9846 ["-D"]["--min-duration"]
9847 (
"show test durations for tests taking at least the given number of seconds" )
9848 | Opt( loadTestNamesFromFile,
"filename" )
9849 ["-f"]["--input-file"]
9850 (
"load test names to run from a file" )
9851 | Opt( config.filenamesAsTags )
9852 ["-#"]["--filenames-as-tags"]
9853 (
"adds a tag for the filename" )
9854 | Opt( config.sectionsToRun,
"section name" )
9856 (
"specify section to run" )
9857 | Opt( setVerbosity,
"quiet|normal|high" )
9858 ["-v"]["--verbosity"]
9859 (
"set output verbosity" )
9860 | Opt( config.listTestNamesOnly )
9861 ["--list-test-names-only"]
9862 (
"list all/matching test cases names only" )
9863 | Opt( config.listReporters )
9864 ["--list-reporters"]
9865 (
"list all reporters" )
9866 | Opt( setTestOrder,
"decl|lex|rand" )
9868 (
"test case order (defaults to decl)" )
9869 | Opt( setRngSeed,
"'time'|number" )
9871 (
"set a specific seed for random numbers" )
9872 | Opt( setColourUsage,
"yes|no" )
9874 (
"should output be colourised" )
9875 | Opt( config.libIdentify )
9877 (
"report name and version according to libidentify standard" )
9878 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9879 ["--wait-for-keypress"]
9880 (
"waits for a keypress before exiting" )
9881 | Opt( config.benchmarkSamples,
"samples" )
9882 ["--benchmark-samples"]
9883 (
"number of samples to collect (default: 100)" )
9884 | Opt( config.benchmarkResamples,
"resamples" )
9885 ["--benchmark-resamples"]
9886 (
"number of resamples for the bootstrap (default: 100000)" )
9887 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9888 ["--benchmark-confidence-interval"]
9889 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9890 | Opt( config.benchmarkNoAnalysis )
9891 ["--benchmark-no-analysis"]
9892 (
"perform only measurements; do not perform any analysis" )
9893 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9894 ["--benchmark-warmup-time"]
9895 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9896 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9897 (
"which test or tests to use" );
9912 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9917 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9920 std::ostream&
operator << ( std::ostream& os, SourceLineInfo
const& info ) {
9922 os << info.file <<
'(' << info.line <<
')';
9924 os << info.file <<
':' << info.line;
9930 return std::string();
9942 Config::Config( ConfigData
const& data )
9944 m_stream( openStream() )
9950 for (
auto& elem : m_data.testsOrTags) {
9953 for (
auto& elem : m_data.sectionsToRun) {
9958 if (!m_data.testsOrTags.empty()) {
9959 m_hasTestFilters =
true;
9960 for (
auto const& testOrTags : m_data.testsOrTags) {
9961 parser.parse(testOrTags);
9964 m_testSpec = parser.testSpec();
9967 std::string
const& Config::getFilename()
const {
9968 return m_data.outputFilename ;
9971 bool Config::listTests()
const {
return m_data.listTests; }
9972 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
9973 bool Config::listTags()
const {
return m_data.listTags; }
9974 bool Config::listReporters()
const {
return m_data.listReporters; }
9976 std::string Config::getProcessName()
const {
return m_data.processName; }
9977 std::string
const& Config::getReporterName()
const {
return m_data.reporterName; }
9979 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
9980 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
9982 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
9983 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
9985 bool Config::showHelp()
const {
return m_data.showHelp; }
9988 bool Config::allowThrows()
const {
return !m_data.noThrow; }
9989 std::ostream& Config::stream()
const {
return m_stream->stream(); }
9990 std::string Config::name()
const {
return m_data.name.empty() ? m_data.processName : m_data.name; }
9991 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
9993 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings &
WarnAbout::NoTests); }
9995 double Config::minDuration()
const {
return m_data.minDuration; }
9999 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
10000 int Config::abortAfter()
const {
return m_data.abortAfter; }
10001 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
10002 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
10004 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
10005 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
10006 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
10007 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
10008 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10010 IStream
const* Config::openStream() {
10018 #if defined(__clang__)
10019 # pragma clang diagnostic push
10020 # pragma clang diagnostic ignored "-Wexit-time-destructors"
10041 #if defined(CATCH_PLATFORM_WINDOWS)
10043 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10044 # define CATCH_DEFINED_NOMINMAX
10047 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10048 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10049 # define WIN32_LEAN_AND_MEAN
10053 #include <AfxWin.h>
10055 #include <windows.h>
10058 #ifdef CATCH_DEFINED_NOMINMAX
10061 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10062 # undef WIN32_LEAN_AND_MEAN
10065 #endif // defined(CATCH_PLATFORM_WINDOWS)
10073 struct IColourImpl {
10074 virtual ~IColourImpl() =
default;
10075 virtual void use( Colour::Code _colourCode ) = 0;
10078 struct NoColourImpl : IColourImpl {
10079 void use( Colour::Code )
override {}
10081 static IColourImpl* instance() {
10082 static NoColourImpl s_instance;
10083 return &s_instance;
10090 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10091 # ifdef CATCH_PLATFORM_WINDOWS
10092 # define CATCH_CONFIG_COLOUR_WINDOWS
10094 # define CATCH_CONFIG_COLOUR_ANSI
10098 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS )
10103 class Win32ColourImpl :
public IColourImpl {
10105 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10107 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10108 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10109 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10110 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10113 void use( Colour::Code _colourCode )
override {
10114 switch( _colourCode ) {
10115 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
10116 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10117 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
10118 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
10119 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
10120 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10121 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10122 case Colour::Grey:
return setTextAttribute( 0 );
10124 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
10125 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10126 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10127 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10128 case Colour::BrightYellow:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10138 void setTextAttribute( WORD _textAttribute ) {
10139 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10141 HANDLE stdoutHandle;
10142 WORD originalForegroundAttributes;
10143 WORD originalBackgroundAttributes;
10146 IColourImpl* platformColourInstance() {
10147 static Win32ColourImpl s_instance;
10151 ? config->useColour()
10157 : NoColourImpl::instance();
10163 #elif defined( CATCH_CONFIG_COLOUR_ANSI )
10165 #include <unistd.h>
10174 class PosixColourImpl :
public IColourImpl {
10176 void use( Colour::Code _colourCode )
override {
10177 switch( _colourCode ) {
10179 case Colour::White:
return setColour(
"[0m" );
10180 case Colour::Red:
return setColour(
"[0;31m" );
10181 case Colour::Green:
return setColour(
"[0;32m" );
10182 case Colour::Blue:
return setColour(
"[0;34m" );
10183 case Colour::Cyan:
return setColour(
"[0;36m" );
10184 case Colour::Yellow:
return setColour(
"[0;33m" );
10185 case Colour::Grey:
return setColour(
"[1;30m" );
10187 case Colour::LightGrey:
return setColour(
"[0;37m" );
10188 case Colour::BrightRed:
return setColour(
"[1;31m" );
10189 case Colour::BrightGreen:
return setColour(
"[1;32m" );
10190 case Colour::BrightWhite:
return setColour(
"[1;37m" );
10191 case Colour::BrightYellow:
return setColour(
"[1;33m" );
10197 static IColourImpl* instance() {
10198 static PosixColourImpl s_instance;
10199 return &s_instance;
10203 void setColour(
const char* _escapeCode ) {
10205 <<
'\033' << _escapeCode;
10209 bool useColourOnPlatform() {
10211 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10212 !isDebuggerActive() &&
10214 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10215 isatty(STDOUT_FILENO)
10221 IColourImpl* platformColourInstance() {
10225 ? config->useColour()
10228 colourMode = useColourOnPlatform()
10232 ? PosixColourImpl::instance()
10233 : NoColourImpl::instance();
10239 #else // not Windows or ANSI
10243 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
10247 #endif // Windows/ ANSI/ None
10251 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10252 Colour::Colour( Colour&& other ) noexcept {
10253 m_moved = other.m_moved;
10254 other.m_moved =
true;
10256 Colour& Colour::operator=( Colour&& other ) noexcept {
10257 m_moved = other.m_moved;
10258 other.m_moved =
true;
10262 Colour::~Colour(){
if( !m_moved ) use( None ); }
10264 void Colour::use( Code _colourCode ) {
10265 static IColourImpl* impl = platformColourInstance();
10270 if (impl !=
nullptr) {
10271 impl->use( _colourCode );
10275 std::ostream&
operator << ( std::ostream& os, Colour
const& ) {
10281 #if defined(__clang__)
10282 # pragma clang diagnostic pop
10290 class Context :
public IMutableContext, NonCopyable {
10294 return m_resultCapture;
10296 IRunner* getRunner()
override {
10300 IConfigPtr const& getConfig()
const override {
10304 ~Context()
override;
10307 void setResultCapture( IResultCapture* resultCapture )
override {
10308 m_resultCapture = resultCapture;
10310 void setRunner( IRunner* runner )
override {
10313 void setConfig(
IConfigPtr const& config )
override {
10321 IRunner* m_runner =
nullptr;
10322 IResultCapture* m_resultCapture =
nullptr;
10338 Context::~Context() =
default;
10340 SimplePcg32&
rng() {
10341 static SimplePcg32 s_rng;
10354 void writeToDebugConsole( std::string
const& text );
10358 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10359 #include <android/log.h>
10362 void writeToDebugConsole( std::string
const& text ) {
10363 __android_log_write( ANDROID_LOG_DEBUG,
"Catch", text.c_str() );
10367 #elif defined(CATCH_PLATFORM_WINDOWS)
10370 void writeToDebugConsole( std::string
const& text ) {
10371 ::OutputDebugStringA( text.c_str() );
10378 void writeToDebugConsole( std::string
const& text ) {
10388 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10390 # include <cassert>
10391 # include <sys/types.h>
10392 # include <unistd.h>
10393 # include <cstddef>
10394 # include <ostream>
10396 #ifdef __apple_build_version__
10399 # include <sys/sysctl.h>
10403 #ifdef __apple_build_version__
10409 bool isDebuggerActive(){
10411 struct kinfo_proc info;
10417 info.kp_proc.p_flag = 0;
10423 mib[1] = KERN_PROC;
10424 mib[2] = KERN_PROC_PID;
10429 size =
sizeof(info);
10430 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0 ) {
10431 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10437 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10440 bool isDebuggerActive() {
10447 #elif defined(CATCH_PLATFORM_LINUX)
10459 bool isDebuggerActive(){
10463 std::ifstream in(
"/proc/self/status");
10464 for( std::string line; std::getline(in, line); ) {
10465 static const int PREFIX_LEN = 11;
10466 if( line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
10470 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
10477 #elif defined(_MSC_VER)
10478 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10480 bool isDebuggerActive() {
10481 return IsDebuggerPresent() != 0;
10484 #elif defined(__MINGW32__)
10485 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10487 bool isDebuggerActive() {
10488 return IsDebuggerPresent() != 0;
10493 bool isDebuggerActive() {
return false; }
10504 if( lhs.size() + rhs.size() < 40 &&
10505 lhs.find(
'\n') == std::string::npos &&
10506 rhs.find(
'\n') == std::string::npos )
10507 os << lhs <<
" " << op <<
" " << rhs;
10509 os << lhs <<
"\n" << op <<
"\n" << rhs;
10515 #include <stdexcept>
10518 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10521 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n"
10522 <<
"The message was: " << e.what() <<
'\n';
10554 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int>
const&
values );
10556 class EnumValuesRegistry :
public IMutableEnumValuesRegistry {
10558 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10560 EnumInfo
const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int>
const&
values)
override;
10563 std::vector<StringRef> parseEnums( StringRef enums );
10583 StringRef extractInstanceName(StringRef enumInstance) {
10585 size_t name_start = enumInstance.size();
10586 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10589 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10593 std::vector<StringRef> parseEnums( StringRef enums ) {
10595 std::vector<StringRef> parsed;
10596 parsed.reserve( enumValues.size() );
10597 for(
auto const& enumValue : enumValues ) {
10598 parsed.push_back(
trim(extractInstanceName(enumValue)));
10606 for(
auto const& valueToName :
m_values ) {
10607 if( valueToName.first ==
value )
10608 return valueToName.second;
10610 return "{** unexpected enum value **}"_sr;
10613 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int>
const&
values ) {
10614 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo );
10615 enumInfo->m_name = enumName;
10616 enumInfo->m_values.reserve(
values.size() );
10618 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10619 assert( valueNames.size() ==
values.size() );
10622 enumInfo->m_values.emplace_back(
value, valueNames[i++]);
10627 EnumInfo
const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int>
const&
values ) {
10628 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames,
values));
10629 return *m_enumInfos.back();
10641 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10642 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10655 class ExceptionTranslatorRegistry :
public IExceptionTranslatorRegistry {
10657 ~ExceptionTranslatorRegistry();
10658 virtual void registerTranslator(
const IExceptionTranslator* translator );
10660 std::string tryTranslators()
const;
10663 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10669 #import "Foundation/Foundation.h"
10674 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10677 void ExceptionTranslatorRegistry::registerTranslator(
const IExceptionTranslator* translator ) {
10678 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10681 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10687 return tryTranslators();
10689 @catch (NSException *exception) {
10701 if (std::current_exception() ==
nullptr) {
10702 return "Non C++ exception. Possibly a CLR exception.";
10704 return tryTranslators();
10707 catch( TestFailureException& ) {
10708 std::rethrow_exception(std::current_exception());
10710 catch( std::exception& ex ) {
10713 catch( std::string& msg ) {
10716 catch(
const char* msg ) {
10720 return "Unknown exception";
10724 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10725 if (m_translators.empty()) {
10726 std::rethrow_exception(std::current_exception());
10728 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10732 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
10734 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10737 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10738 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10746 #include <algorithm>
10748 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
10754 FatalConditionHandler::engage_platform() {}
10755 FatalConditionHandler::disengage_platform() {}
10756 FatalConditionHandler::FatalConditionHandler() =
default;
10757 FatalConditionHandler::~FatalConditionHandler() =
default;
10761 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
10763 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
10764 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10765 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
10767 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10771 void reportFatal(
char const *
const message ) {
10778 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10781 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
10783 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10787 struct SignalDefs { DWORD id;
const char* name; };
10792 static SignalDefs signalDefs[] = {
10793 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10794 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10795 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10796 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10799 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10800 for (
auto const& def : signalDefs) {
10801 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10802 reportFatal(def.name);
10807 return EXCEPTION_CONTINUE_SEARCH;
10813 static PVOID exceptionHandlerHandle =
nullptr;
10817 FatalConditionHandler::FatalConditionHandler() {
10818 ULONG guaranteeSize =
static_cast<ULONG
>(minStackSizeForErrors);
10819 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10823 <<
"Failed to reserve piece of stack."
10824 <<
" Stack overflows will not be reported successfully.";
10830 FatalConditionHandler::~FatalConditionHandler() =
default;
10832 void FatalConditionHandler::engage_platform() {
10834 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10835 if (!exceptionHandlerHandle) {
10840 void FatalConditionHandler::disengage_platform() {
10841 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10844 exceptionHandlerHandle =
nullptr;
10849 #endif // CATCH_CONFIG_WINDOWS_SEH
10851 #if defined( CATCH_CONFIG_POSIX_SIGNALS )
10853 #include <signal.h>
10857 struct SignalDefs {
10862 static SignalDefs signalDefs[] = {
10863 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10864 { SIGILL,
"SIGILL - Illegal instruction signal" },
10865 { SIGFPE,
"SIGFPE - Floating point error signal" },
10866 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10867 { SIGTERM,
"SIGTERM - Termination request signal" },
10868 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10874 #if defined(__GNUC__)
10875 # pragma GCC diagnostic push
10876 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10879 static char* altStackMem =
nullptr;
10880 static std::size_t altStackSize = 0;
10881 static stack_t oldSigStack{};
10882 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10884 static void restorePreviousSignalHandlers() {
10889 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
10890 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10893 sigaltstack(&oldSigStack,
nullptr);
10896 static void handleSignal(
int sig ) {
10897 char const * name =
"<unknown signal>";
10898 for (
auto const& def : signalDefs) {
10899 if (sig == def.id) {
10907 restorePreviousSignalHandlers();
10908 reportFatal( name );
10912 FatalConditionHandler::FatalConditionHandler() {
10913 assert(!altStackMem &&
"Cannot initialize POSIX signal handler when one already exists");
10914 if (altStackSize == 0) {
10915 altStackSize = std::max(
static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10917 altStackMem =
new char[altStackSize]();
10920 FatalConditionHandler::~FatalConditionHandler() {
10921 delete[] altStackMem;
10924 altStackMem =
nullptr;
10927 void FatalConditionHandler::engage_platform() {
10929 sigStack.ss_sp = altStackMem;
10930 sigStack.ss_size = altStackSize;
10931 sigStack.ss_flags = 0;
10932 sigaltstack(&sigStack, &oldSigStack);
10933 struct sigaction sa = { };
10935 sa.sa_handler = handleSignal;
10936 sa.sa_flags = SA_ONSTACK;
10937 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
10938 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
10942 #if defined(__GNUC__)
10943 # pragma GCC diagnostic pop
10946 void FatalConditionHandler::disengage_platform() {
10947 restorePreviousSignalHandlers();
10952 #endif // CATCH_CONFIG_POSIX_SIGNALS
10967 namespace Generators {
10971 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker& {
11010 class ListeningReporter :
public IStreamingReporter {
11011 using Reporters = std::vector<IStreamingReporterPtr>;
11012 Reporters m_listeners;
11013 IStreamingReporterPtr m_reporter =
nullptr;
11014 ReporterPreferences m_preferences;
11017 ListeningReporter();
11019 void addListener( IStreamingReporterPtr&& listener );
11020 void addReporter( IStreamingReporterPtr&& reporter );
11024 ReporterPreferences getPreferences()
const override;
11026 void noMatchingTestCases( std::string
const& spec )
override;
11028 void reportInvalidArguments(std::string
const&arg)
override;
11030 static std::set<Verbosity> getSupportedVerbosities();
11032 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11033 void benchmarkPreparing(std::string
const& name)
override;
11034 void benchmarkStarting( BenchmarkInfo
const& benchmarkInfo )
override;
11035 void benchmarkEnded( BenchmarkStats<>
const& benchmarkStats )
override;
11036 void benchmarkFailed(std::string
const&)
override;
11037 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11039 void testRunStarting( TestRunInfo
const& testRunInfo )
override;
11040 void testGroupStarting( GroupInfo
const& groupInfo )
override;
11041 void testCaseStarting( TestCaseInfo
const& testInfo )
override;
11042 void sectionStarting( SectionInfo
const& sectionInfo )
override;
11043 void assertionStarting( AssertionInfo
const& assertionInfo )
override;
11046 bool assertionEnded( AssertionStats
const& assertionStats )
override;
11047 void sectionEnded( SectionStats
const& sectionStats )
override;
11048 void testCaseEnded( TestCaseStats
const& testCaseStats )
override;
11049 void testGroupEnded( TestGroupStats
const& testGroupStats )
override;
11050 void testRunEnded( TestRunStats
const& testRunStats )
override;
11052 void skipTest( TestCaseInfo
const& testInfo )
override;
11053 bool isMulti()
const override;
11062 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig )
11063 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11065 ReporterConfig::ReporterConfig(
IConfigPtr const& _fullConfig, std::ostream& _stream )
11066 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11068 std::ostream& ReporterConfig::stream()
const {
return *m_stream; }
11069 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
11071 TestRunInfo::TestRunInfo( std::string
const& _name ) : name( _name ) {}
11073 GroupInfo::GroupInfo( std::string
const& _name,
11074 std::size_t _groupIndex,
11075 std::size_t _groupsCount )
11077 groupIndex( _groupIndex ),
11078 groupsCounts( _groupsCount )
11081 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
11082 std::vector<MessageInfo>
const& _infoMessages,
11083 Totals
const& _totals )
11084 : assertionResult( _assertionResult ),
11085 infoMessages( _infoMessages ),
11088 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11090 if( assertionResult.hasMessage() ) {
11093 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11094 builder << assertionResult.getMessage();
11095 builder.m_info.message = builder.m_stream.str();
11097 infoMessages.push_back( builder.m_info );
11101 AssertionStats::~AssertionStats() =
default;
11103 SectionStats::SectionStats( SectionInfo
const& _sectionInfo,
11104 Counts
const& _assertions,
11105 double _durationInSeconds,
11106 bool _missingAssertions )
11107 : sectionInfo( _sectionInfo ),
11108 assertions( _assertions ),
11109 durationInSeconds( _durationInSeconds ),
11110 missingAssertions( _missingAssertions )
11113 SectionStats::~SectionStats() =
default;
11115 TestCaseStats::TestCaseStats( TestCaseInfo
const& _testInfo,
11116 Totals
const& _totals,
11117 std::string
const& _stdOut,
11118 std::string
const& _stdErr,
11120 : testInfo( _testInfo ),
11124 aborting( _aborting )
11127 TestCaseStats::~TestCaseStats() =
default;
11129 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11130 Totals
const& _totals,
11132 : groupInfo( _groupInfo ),
11134 aborting( _aborting )
11137 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11138 : groupInfo( _groupInfo ),
11142 TestGroupStats::~TestGroupStats() =
default;
11144 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11145 Totals
const& _totals,
11147 : runInfo( _runInfo ),
11149 aborting( _aborting )
11152 TestRunStats::~TestRunStats() =
default;
11154 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
11155 bool IStreamingReporter::isMulti()
const {
return false; }
11157 IReporterFactory::~IReporterFactory() =
default;
11158 IReporterRegistry::~IReporterRegistry() =
default;
11177 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11178 #include <crtdbg.h>
11182 LeakDetector::LeakDetector() {
11183 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11184 flag |= _CRTDBG_LEAK_CHECK_DF;
11185 flag |= _CRTDBG_ALLOC_MEM_DF;
11186 _CrtSetDbgFlag(flag);
11187 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11188 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11190 _CrtSetBreakAlloc(-1);
11196 Catch::LeakDetector::LeakDetector() {}
11200 Catch::LeakDetector::~LeakDetector() {
11212 std::size_t listTests( Config
const& config );
11214 std::size_t listTestsNamesOnly( Config
const& config );
11217 void add( std::string
const& spelling );
11218 std::string all()
const;
11220 std::set<std::string> spellings;
11221 std::size_t count = 0;
11224 std::size_t listTags( Config
const& config );
11226 std::size_t listReporters();
11228 Option<std::size_t> list( std::shared_ptr<Config>
const& config );
11236 using namespace clara::TextFlow;
11241 #include <algorithm>
11246 std::size_t listTests( Config
const& config ) {
11247 TestSpec
const& testSpec = config.testSpec();
11248 if( config.hasTestFilters() )
11255 for(
auto const& testCaseInfo : matchedTestCases ) {
11256 Colour::Code colour = testCaseInfo.isHidden()
11257 ? Colour::SecondaryText
11259 Colour colourGuard( colour );
11261 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11264 std::string description = testCaseInfo.description;
11265 if( description.empty() )
11266 description =
"(NO DESCRIPTION)";
11267 Catch::cout() << Column( description ).indent(4) << std::endl;
11269 if( !testCaseInfo.tags.empty() )
11270 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) <<
"\n";
11273 if( !config.hasTestFilters() )
11274 Catch::cout() << pluralise( matchedTestCases.size(),
"test case" ) <<
'\n' << std::endl;
11276 Catch::cout() << pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11277 return matchedTestCases.size();
11280 std::size_t listTestsNamesOnly( Config
const& config ) {
11281 TestSpec
const& testSpec = config.testSpec();
11282 std::size_t matchedTests = 0;
11284 for(
auto const& testCaseInfo : matchedTestCases ) {
11287 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11294 return matchedTests;
11297 void TagInfo::add( std::string
const& spelling ) {
11299 spellings.insert( spelling );
11302 std::string TagInfo::all()
const {
11304 for (
auto const& spelling : spellings) {
11306 size += spelling.size() + 2;
11309 std::string out; out.reserve(size);
11310 for (
auto const& spelling : spellings) {
11318 std::size_t listTags( Config
const& config ) {
11319 TestSpec
const& testSpec = config.testSpec();
11320 if( config.hasTestFilters() )
11321 Catch::cout() <<
"Tags for matching test cases:\n";
11326 std::map<std::string, TagInfo> tagCounts;
11329 for(
auto const& testCase : matchedTestCases ) {
11330 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11331 std::string lcaseTagName =
toLower( tagName );
11332 auto countIt = tagCounts.find( lcaseTagName );
11333 if( countIt == tagCounts.end() )
11334 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11335 countIt->second.add( tagName );
11339 for(
auto const& tagCount : tagCounts ) {
11340 ReusableStringStream rss;
11341 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11342 auto str = rss.str();
11343 auto wrapper = Column( tagCount.second.all() )
11344 .initialIndent( 0 )
11345 .indent( str.size() )
11346 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11349 Catch::cout() << pluralise( tagCounts.size(),
"tag" ) <<
'\n' << std::endl;
11350 return tagCounts.size();
11353 std::size_t listReporters() {
11356 std::size_t maxNameLen = 0;
11357 for(
auto const& factoryKvp : factories )
11358 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11360 for(
auto const& factoryKvp : factories ) {
11362 << Column( factoryKvp.first +
":" )
11364 .width( 5+maxNameLen )
11365 + Column( factoryKvp.second->getDescription() )
11368 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11372 return factories.size();
11375 Option<std::size_t> list( std::shared_ptr<Config>
const& config ) {
11376 Option<std::size_t> listedCount;
11378 if( config->listTests() )
11379 listedCount = listedCount.valueOr(0) + listTests( *config );
11380 if( config->listTestNamesOnly() )
11381 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11382 if( config->listTags() )
11383 listedCount = listedCount.valueOr(0) + listTags( *config );
11384 if( config->listReporters() )
11385 listedCount = listedCount.valueOr(0) + listReporters();
11386 return listedCount;
11394 namespace Matchers {
11408 using namespace Matchers;
11409 using Matchers::Impl::MatcherBase;
11416 namespace Matchers {
11417 namespace Exception {
11424 return "exception message matches \"" +
m_message + "\"";
11428 Exception::ExceptionMessageMatcher
Message(std::string
const& message) {
11429 return Exception::ExceptionMessageMatcher(message);
11441 bool isnan(
float f);
11442 bool isnan(
double d);
11451 template <
typename T>
11452 std::string to_string(T
const& t) {
11453 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11454 return std::to_string(t);
11456 ReusableStringStream rss;
11464 #include <algorithm>
11470 #include <type_traits>
11477 int32_t convert(
float f) {
11478 static_assert(
sizeof(
float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11480 std::memcpy(&i, &f,
sizeof(f));
11484 int64_t convert(
double d) {
11485 static_assert(
sizeof(
double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11487 std::memcpy(&i, &d,
sizeof(d));
11491 template <
typename FP>
11492 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11495 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11499 auto lc = convert(lhs);
11500 auto rc = convert(rhs);
11502 if ((lc < 0) != (rc < 0)) {
11508 auto ulpDiff = std::abs(
static_cast<FP
>(lc - rc));
11509 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11512 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11514 float nextafter(
float x,
float y) {
11515 return ::nextafterf(x, y);
11518 double nextafter(
double x,
double y) {
11519 return ::nextafter(x, y);
11522 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11524 template <
typename FP>
11525 FP step(FP start, FP direction, uint64_t steps) {
11526 for (uint64_t i = 0; i < steps; ++i) {
11527 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11528 start = Catch::nextafter(start, direction);
11530 start = std::nextafter(start, direction);
11538 bool marginComparison(
double lhs,
double rhs,
double margin) {
11539 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11542 template <
typename FloatingPo
int>
11543 void write(std::ostream& out, FloatingPoint num) {
11544 out << std::scientific
11545 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11551 namespace Matchers {
11552 namespace Floating {
11554 enum class FloatingPointKind : uint8_t {
11559 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11560 :m_target{ target }, m_margin{ margin } {
11561 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.'
11562 <<
" Margin has to be non-negative.");
11567 bool WithinAbsMatcher::match(
double const& matchee)
const {
11568 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11571 std::string WithinAbsMatcher::describe()
const {
11572 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11575 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11576 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11578 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11579 "Provided ULP is impossibly large for a float comparison.");
11582 #if defined(__clang__)
11583 #pragma clang diagnostic push
11585 #pragma clang diagnostic ignored "-Wunreachable-code"
11588 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11590 case FloatingPointKind::Float:
11591 return almostEqualUlps<float>(
static_cast<float>(matchee),
static_cast<float>(m_target), m_ulps);
11592 case FloatingPointKind::Double:
11593 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11599 #if defined(__clang__)
11600 #pragma clang diagnostic pop
11603 std::string WithinUlpsMatcher::describe()
const {
11604 std::stringstream ret;
11606 ret <<
"is within " << m_ulps <<
" ULPs of ";
11608 if (m_type == FloatingPointKind::Float) {
11609 write(ret,
static_cast<float>(m_target));
11612 write(ret, m_target);
11616 if (m_type == FloatingPointKind::Double) {
11617 write(ret, step(m_target,
static_cast<double>(-INFINITY), m_ulps));
11619 write(ret, step(m_target,
static_cast<double>( INFINITY), m_ulps));
11622 write(ret, step(
static_cast<float>(m_target),
static_cast<float>(-INFINITY), m_ulps));
11624 write(ret, step(
static_cast<float>(m_target),
static_cast<float>( INFINITY), m_ulps));
11631 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11633 m_epsilon(epsilon){
11634 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11635 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
");
11638 bool WithinRelMatcher::match(double const& matchee) const {
11639 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11640 return marginComparison(matchee, m_target,
11641 std::isinf(relMargin)? 0 : relMargin);
11644 std::string WithinRelMatcher::describe() const {
11645 Catch::ReusableStringStream sstr;
11646 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
";
11650 }// namespace Floating
11652 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11653 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11656 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11657 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11660 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11661 return Floating::WithinAbsMatcher(target, margin);
11664 Floating::WithinRelMatcher WithinRel(double target, double eps) {
11665 return Floating::WithinRelMatcher(target, eps);
11668 Floating::WithinRelMatcher WithinRel(double target) {
11669 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11672 Floating::WithinRelMatcher WithinRel(float target, float eps) {
11673 return Floating::WithinRelMatcher(target, eps);
11676 Floating::WithinRelMatcher WithinRel(float target) {
11677 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11680 } // namespace Matchers
11681 } // namespace Catch
11682 // end catch_matchers_floating.cpp
11683 // start catch_matchers_generic.cpp
11685 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11686 if (desc.empty()) {
11687 return "matches undescribed predicate
";
11689 return "matches predicate: \
"" + desc +
'"';
11698 namespace Matchers {
11700 namespace StdString {
11703 : m_caseSensitivity( caseSensitivity ),
11704 m_str( adjustString( str ) )
11706 std::string CasedString::adjustString( std::string
const& str )
const {
11711 std::string CasedString::caseSensitivitySuffix()
const {
11713 ?
" (case insensitive)"
11717 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
11718 : m_comparator( comparator ),
11719 m_operation( operation ) {
11722 std::string StringMatcherBase::describe()
const {
11723 std::string description;
11724 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11725 m_comparator.caseSensitivitySuffix().size());
11726 description += m_operation;
11727 description += ": \"";
11728 description += m_comparator.m_str;
11729 description += "\"";
11730 description += m_comparator.caseSensitivitySuffix();
11731 return description;
11734 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11736 bool EqualsMatcher::match( std::string
const& source )
const {
11737 return m_comparator.adjustString( source ) == m_comparator.m_str;
11740 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11742 bool ContainsMatcher::match( std::string
const& source )
const {
11743 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11746 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11748 bool StartsWithMatcher::match( std::string
const& source )
const {
11749 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11752 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11754 bool EndsWithMatcher::match( std::string
const& source )
const {
11755 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11758 RegexMatcher::RegexMatcher(std::string regex,
CaseSensitive::Choice caseSensitivity): m_regex(
std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11760 bool RegexMatcher::match(std::string
const& matchee)
const {
11761 auto flags = std::regex::ECMAScript;
11762 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11763 flags |= std::regex::icase;
11765 auto reg = std::regex(m_regex, flags);
11766 return std::regex_match(matchee, reg);
11769 std::string RegexMatcher::describe()
const {
11770 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11775 StdString::EqualsMatcher
Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11776 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11778 StdString::ContainsMatcher
Contains( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11779 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11781 StdString::EndsWithMatcher
EndsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11782 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11784 StdString::StartsWithMatcher
StartsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11785 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11788 StdString::RegexMatcher
Matches(std::string
const& regex, CaseSensitive::Choice caseSensitivity) {
11789 return StdString::RegexMatcher(regex, caseSensitivity);
11800 bool uncaught_exceptions();
11810 SourceLineInfo
const& _lineInfo,
11812 : macroName( _macroName ),
11813 lineInfo( _lineInfo ),
11815 sequence( ++globalCount )
11819 return sequence == other.sequence;
11832 SourceLineInfo
const& lineInfo,
11834 :m_info(macroName, lineInfo, type) {}
11839 : m_info( builder.m_info ), m_moved()
11841 m_info.message = builder.m_stream.str();
11846 : m_info( old.m_info ), m_moved()
11848 old.m_moved =
true;
11852 if ( !uncaught_exceptions() && !
m_moved ){
11858 auto trimmed = [&] (
size_t start,
size_t end) {
11859 while (
names[start] ==
',' || isspace(
static_cast<unsigned char>(
names[start]))) {
11862 while (
names[end] ==
',' || isspace(
static_cast<unsigned char>(
names[end]))) {
11865 return names.substr(start, end - start + 1);
11867 auto skipq = [&] (
size_t start,
char quote) {
11868 for (
auto i = start + 1; i <
names.size() ; ++i) {
11869 if (
names[i] == quote)
11871 if (
names[i] ==
'\\')
11878 std::stack<char> openings;
11879 for (
size_t pos = 0; pos <
names.size(); ++pos) {
11880 char c =
names[pos];
11898 pos = skipq(pos, c);
11901 if (start != pos && openings.empty()) {
11902 m_messages.emplace_back(macroName, lineInfo, resultType);
11903 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11904 m_messages.back().message += " := ";
11909 assert(openings.empty() &&
"Mismatched openings");
11910 m_messages.emplace_back(macroName, lineInfo, resultType);
11911 m_messages.back().message =
static_cast<std::string
>(trimmed(start,
names.size() - 1));
11912 m_messages.back().message += " := ";
11914 Capturer::~Capturer() {
11915 if ( !uncaught_exceptions() ){
11916 assert( m_captured == m_messages.size() );
11917 for(
size_t i = 0; i < m_captured; ++i )
11918 m_resultCapture.popScopedMessage( m_messages[i] );
11922 void Capturer::captureValue(
size_t index, std::string
const&
value ) {
11923 assert( index < m_messages.size() );
11924 m_messages[index].message +=
value;
11934 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11935 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11943 class RedirectedStream {
11944 std::ostream& m_originalStream;
11945 std::ostream& m_redirectionStream;
11946 std::streambuf* m_prevBuf;
11949 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11950 ~RedirectedStream();
11953 class RedirectedStdOut {
11954 ReusableStringStream m_rss;
11955 RedirectedStream m_cout;
11957 RedirectedStdOut();
11958 auto str() const ->
std::
string;
11964 class RedirectedStdErr {
11965 ReusableStringStream m_rss;
11966 RedirectedStream m_cerr;
11967 RedirectedStream m_clog;
11969 RedirectedStdErr();
11970 auto str() const ->
std::
string;
11973 class RedirectedStreams {
11975 RedirectedStreams(RedirectedStreams
const&) =
delete;
11976 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
11977 RedirectedStreams(RedirectedStreams&&) =
delete;
11978 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
11980 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11981 ~RedirectedStreams();
11983 std::string& m_redirectedCout;
11984 std::string& m_redirectedCerr;
11985 RedirectedStdOut m_redirectedStdOut;
11986 RedirectedStdErr m_redirectedStdErr;
11989 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11997 TempFile(TempFile
const&) =
delete;
11998 TempFile& operator=(TempFile
const&) =
delete;
11999 TempFile(TempFile&&) =
delete;
12000 TempFile& operator=(TempFile&&) =
delete;
12005 std::FILE* getFile();
12006 std::string getContents();
12009 std::FILE* m_file =
nullptr;
12010 #if defined(_MSC_VER)
12011 char m_buffer[L_tmpnam] = { 0 };
12015 class OutputRedirect {
12017 OutputRedirect(OutputRedirect
const&) =
delete;
12018 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
12019 OutputRedirect(OutputRedirect&&) =
delete;
12020 OutputRedirect& operator=(OutputRedirect&&) =
delete;
12022 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12026 int m_originalStdout = -1;
12027 int m_originalStderr = -1;
12028 TempFile m_stdoutFile;
12029 TempFile m_stderrFile;
12030 std::string& m_stdoutDest;
12031 std::string& m_stderrDest;
12038 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12044 #include <stdexcept>
12046 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12047 #if defined(_MSC_VER)
12051 #define fileno _fileno
12053 #include <unistd.h>
12059 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12060 : m_originalStream( originalStream ),
12061 m_redirectionStream( redirectionStream ),
12062 m_prevBuf( m_originalStream.rdbuf() )
12064 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12067 RedirectedStream::~RedirectedStream() {
12068 m_originalStream.rdbuf( m_prevBuf );
12071 RedirectedStdOut::RedirectedStdOut() : m_cout(
Catch::
cout(), m_rss.
get() ) {}
12072 auto RedirectedStdOut::str() const ->
std::
string {
return m_rss.str(); }
12074 RedirectedStdErr::RedirectedStdErr()
12078 auto RedirectedStdErr::str() const ->
std::
string {
return m_rss.str(); }
12080 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12081 : m_redirectedCout(redirectedCout),
12082 m_redirectedCerr(redirectedCerr)
12085 RedirectedStreams::~RedirectedStreams() {
12086 m_redirectedCout += m_redirectedStdOut.str();
12087 m_redirectedCerr += m_redirectedStdErr.str();
12090 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12092 #if defined(_MSC_VER)
12093 TempFile::TempFile() {
12094 if (tmpnam_s(m_buffer)) {
12097 if (fopen_s(&m_file, m_buffer,
"w+")) {
12099 if (strerror_s(buffer, errno)) {
12102 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12106 TempFile::TempFile() {
12107 m_file = std::tmpfile();
12115 TempFile::~TempFile() {
12117 std::fclose(m_file);
12120 #if defined(_MSC_VER)
12121 std::remove(m_buffer);
12125 FILE* TempFile::getFile() {
12129 std::string TempFile::getContents() {
12130 std::stringstream sstr;
12131 char buffer[100] = {};
12132 std::rewind(m_file);
12133 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12139 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12140 m_originalStdout(dup(1)),
12141 m_originalStderr(dup(2)),
12142 m_stdoutDest(stdout_dest),
12143 m_stderrDest(stderr_dest) {
12144 dup2(fileno(m_stdoutFile.getFile()), 1);
12145 dup2(fileno(m_stderrFile.getFile()), 2);
12148 OutputRedirect::~OutputRedirect() {
12157 dup2(m_originalStdout, 1);
12158 dup2(m_originalStderr, 2);
12160 m_stdoutDest += m_stdoutFile.getContents();
12161 m_stderrDest += m_stderrFile.getContents();
12164 #endif // CATCH_CONFIG_NEW_CAPTURE
12168 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12169 #if defined(_MSC_VER)
12182 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12183 bool isnan(
float f) {
12184 return std::isnan(f);
12186 bool isnan(
double d) {
12187 return std::isnan(d);
12191 bool isnan(
float f) {
12192 return std::_isnan(f);
12194 bool isnan(
double d) {
12195 return std::_isnan(d);
12207 #if defined(_MSC_VER)
12208 #pragma warning(push)
12209 #pragma warning(disable:4146) // we negate uint32 during the rotate
12212 uint32_t rotate_right(uint32_t val, uint32_t count) {
12213 const uint32_t mask = 31;
12215 return (val >> count) | (val << (-count & mask));
12218 #if defined(_MSC_VER)
12219 #pragma warning(pop)
12238 for (uint64_t s = 0; s < skip; ++s) {
12239 static_cast<void>((*this)());
12245 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12246 const auto output = rotate_right(xorshifted, m_state >> 59u);
12249 m_state = m_state * 6364136223846793005ULL + s_inc;
12254 bool operator==(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12255 return lhs.m_state == rhs.m_state;
12258 bool operator!=(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12259 return lhs.m_state != rhs.m_state;
12269 #include <algorithm>
12277 std::vector<TestCase> sortTests( IConfig
const& config, std::vector<TestCase>
const& unsortedTestCases );
12279 bool isThrowSafe( TestCase
const& testCase, IConfig
const& config );
12280 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config );
12282 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12284 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config );
12287 class TestRegistry :
public ITestCaseRegistry {
12289 virtual ~TestRegistry() =
default;
12291 virtual void registerTest( TestCase
const& testCase );
12293 std::vector<TestCase>
const& getAllTests()
const override;
12294 std::vector<TestCase>
const& getAllTestsSorted( IConfig
const& config )
const override;
12297 std::vector<TestCase> m_functions;
12299 mutable std::vector<TestCase> m_sortedFunctions;
12300 std::size_t m_unnamedCount = 0;
12301 std::ios_base::Init m_ostreamInit;
12306 class TestInvokerAsFunction :
public ITestInvoker {
12307 void(*m_testAsFunction)();
12309 TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept;
12311 void invoke() const override;
12314 std::
string extractClassName( StringRef const& classOrQualifiedMethodName );
12327 class ReporterRegistry :
public IReporterRegistry {
12331 ~ReporterRegistry()
override;
12333 IStreamingReporterPtr create( std::string
const& name,
IConfigPtr const& config )
const override;
12338 FactoryMap
const& getFactories()
const override;
12339 Listeners
const& getListeners()
const override;
12342 FactoryMap m_factories;
12343 Listeners m_listeners;
12357 TagAlias(std::string
const& _tag, SourceLineInfo _lineInfo);
12360 SourceLineInfo lineInfo;
12370 class TagAliasRegistry :
public ITagAliasRegistry {
12372 ~TagAliasRegistry()
override;
12373 TagAlias
const*
find( std::string
const& alias )
const override;
12374 std::string expandAliases( std::string
const& unexpandedTestSpec )
const override;
12375 void add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo );
12378 std::map<std::string, TagAlias> m_registry;
12387 #include <exception>
12391 class StartupExceptionRegistry {
12392 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12394 void add(std::exception_ptr
const& exception) noexcept;
12395 std::vector<std::exception_ptr>
const& getExceptions() const noexcept;
12397 std::vector<
std::exception_ptr> m_exceptions;
12408 struct ISingleton {
12409 virtual ~ISingleton();
12412 void addSingleton( ISingleton* singleton );
12413 void cleanupSingletons();
12415 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12416 class Singleton : SingletonImplT,
public ISingleton {
12418 static auto getInternal() -> Singleton* {
12419 static Singleton* s_instance =
nullptr;
12420 if( !s_instance ) {
12421 s_instance =
new Singleton;
12422 addSingleton( s_instance );
12428 static auto get() -> InterfaceT
const& {
12429 return *getInternal();
12431 static auto getMutable() -> MutableInterfaceT& {
12432 return *getInternal();
12443 class RegistryHub :
public IRegistryHub,
public IMutableRegistryHub,
12444 private NonCopyable {
12447 RegistryHub() =
default;
12448 IReporterRegistry
const& getReporterRegistry()
const override {
12449 return m_reporterRegistry;
12451 ITestCaseRegistry
const& getTestCaseRegistry()
const override {
12452 return m_testCaseRegistry;
12454 IExceptionTranslatorRegistry
const& getExceptionTranslatorRegistry()
const override {
12455 return m_exceptionTranslatorRegistry;
12457 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
12458 return m_tagAliasRegistry;
12460 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12461 return m_exceptionRegistry;
12465 void registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory )
override {
12466 m_reporterRegistry.registerReporter( name, factory );
12469 m_reporterRegistry.registerListener( factory );
12471 void registerTest( TestCase
const& testInfo )
override {
12472 m_testCaseRegistry.registerTest( testInfo );
12474 void registerTranslator(
const IExceptionTranslator* translator )
override {
12475 m_exceptionTranslatorRegistry.registerTranslator( translator );
12477 void registerTagAlias( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo )
override {
12478 m_tagAliasRegistry.add( alias, tag, lineInfo );
12480 void registerStartupException() noexcept
override {
12481 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12482 m_exceptionRegistry.add(std::current_exception());
12484 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12487 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry()
override {
12488 return m_enumValuesRegistry;
12492 TestRegistry m_testCaseRegistry;
12493 ReporterRegistry m_reporterRegistry;
12494 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12495 TagAliasRegistry m_tagAliasRegistry;
12496 StartupExceptionRegistry m_exceptionRegistry;
12497 Detail::EnumValuesRegistry m_enumValuesRegistry;
12501 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12507 return RegistryHubSingleton::getMutable();
12510 cleanupSingletons();
12523 ReporterRegistry::~ReporterRegistry() =
default;
12525 IStreamingReporterPtr ReporterRegistry::create( std::string
const& name,
IConfigPtr const& config )
const {
12526 auto it = m_factories.find( name );
12527 if( it == m_factories.end() )
12529 return it->second->create( ReporterConfig( config ) );
12532 void ReporterRegistry::registerReporter( std::string
const& name,
IReporterFactoryPtr const& factory ) {
12533 m_factories.emplace(name, factory);
12536 m_listeners.push_back( factory );
12539 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12540 return m_factories;
12542 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12543 return m_listeners;
12571 #include <algorithm>
12576 namespace Generators {
12577 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12580 GeneratorTracker( TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12581 : TrackerBase( nameAndLocation, ctx, parent )
12583 ~GeneratorTracker();
12585 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation
const& nameAndLocation ) {
12586 std::shared_ptr<GeneratorTracker> tracker;
12588 ITracker& currentTracker = ctx.currentTracker();
12600 if (currentTracker.nameAndLocation() == nameAndLocation) {
12601 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12602 assert(thisTracker);
12603 assert(thisTracker->isGeneratorTracker());
12604 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12605 }
else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12606 assert( childTracker );
12607 assert( childTracker->isGeneratorTracker() );
12608 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12610 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12611 currentTracker.addChild( tracker );
12614 if( !tracker->isComplete() ) {
12622 bool isGeneratorTracker()
const override {
return true; }
12623 auto hasGenerator() const ->
bool override {
12624 return !!m_generator;
12626 void close()
override {
12627 TrackerBase::close();
12635 const bool should_wait_for_child = [&]() {
12637 if ( m_children.empty() ) {
12642 m_children.begin(),
12644 []( TestCaseTracking::ITrackerPtr tracker ) {
12645 return tracker->hasStarted();
12646 } ) != m_children.end() ) {
12653 auto* parent = m_parent;
12656 while ( !parent->isSectionTracker() ) {
12657 parent = &( parent->parent() );
12660 "Missing root (test case) level section" );
12662 auto const& parentSection =
12663 static_cast<SectionTracker&
>( *parent );
12664 auto const& filters = parentSection.getFilters();
12666 if ( filters.empty() ) {
12670 for (
auto const& child : m_children ) {
12671 if ( child->isSectionTracker() &&
12674 static_cast<SectionTracker&
>( *child )
12675 .trimmedName() ) !=
12687 if ( should_wait_for_child ||
12688 ( m_runState == CompletedSuccessfully &&
12689 m_generator->next() ) ) {
12690 m_children.clear();
12691 m_runState = Executing;
12697 return m_generator;
12700 m_generator = std::move( generator );
12703 GeneratorTracker::~GeneratorTracker() {}
12706 RunContext::RunContext(
IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12707 : m_runInfo(_config->name()),
12710 m_reporter(
std::move(reporter)),
12712 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12714 m_context.setRunner(
this);
12715 m_context.setConfig(m_config);
12716 m_context.setResultCapture(
this);
12717 m_reporter->testRunStarting(m_runInfo);
12720 RunContext::~RunContext() {
12721 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12724 void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12725 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12728 void RunContext::testGroupEnded(std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12729 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12732 Totals RunContext::runTest(TestCase
const& testCase) {
12733 Totals prevTotals = m_totals;
12735 std::string redirectedCout;
12736 std::string redirectedCerr;
12738 auto const& testInfo = testCase.getTestCaseInfo();
12740 m_reporter->testCaseStarting(testInfo);
12742 m_activeTestCase = &testCase;
12744 ITracker& rootTracker = m_trackerContext.startRun();
12745 assert(rootTracker.isSectionTracker());
12746 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12748 m_trackerContext.startCycle();
12749 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12750 runCurrentTest(redirectedCout, redirectedCerr);
12751 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12753 Totals deltaTotals = m_totals.delta(prevTotals);
12754 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12755 deltaTotals.assertions.failed++;
12756 deltaTotals.testCases.passed--;
12757 deltaTotals.testCases.failed++;
12759 m_totals.testCases += deltaTotals.testCases;
12760 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12766 m_activeTestCase =
nullptr;
12767 m_testCaseTracker =
nullptr;
12769 return deltaTotals;
12776 IStreamingReporter& RunContext::reporter()
const {
12777 return *m_reporter;
12780 void RunContext::assertionEnded(AssertionResult
const & result) {
12782 m_totals.assertions.passed++;
12783 m_lastAssertionPassed =
true;
12784 }
else if (!result.isOk()) {
12785 m_lastAssertionPassed =
false;
12786 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12787 m_totals.assertions.failedButOk++;
12789 m_totals.assertions.failed++;
12792 m_lastAssertionPassed =
true;
12797 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12800 m_messageScopes.clear();
12803 resetAssertionInfo();
12804 m_lastResult = result;
12806 void RunContext::resetAssertionInfo() {
12807 m_lastAssertionInfo.macroName = StringRef();
12808 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12811 bool RunContext::sectionStarted(SectionInfo
const & sectionInfo, Counts & assertions) {
12812 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12813 if (!sectionTracker.isOpen())
12815 m_activeSections.push_back(§ionTracker);
12817 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12819 m_reporter->sectionStarting(sectionInfo);
12821 assertions = m_totals.assertions;
12826 using namespace Generators;
12827 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12828 TestCaseTracking::NameAndLocation(
static_cast<std::string
>(generatorName), lineInfo ) );
12829 m_lastAssertionInfo.lineInfo = lineInfo;
12833 bool RunContext::testForMissingAssertions(Counts& assertions) {
12834 if (assertions.total() != 0)
12836 if (!m_config->warnAboutMissingAssertions())
12838 if (m_trackerContext.currentTracker().hasChildren())
12840 m_totals.assertions.failed++;
12841 assertions.failed++;
12845 void RunContext::sectionEnded(SectionEndInfo
const & endInfo) {
12846 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12847 bool missingAssertions = testForMissingAssertions(assertions);
12849 if (!m_activeSections.empty()) {
12850 m_activeSections.back()->close();
12851 m_activeSections.pop_back();
12854 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12855 m_messages.clear();
12856 m_messageScopes.clear();
12859 void RunContext::sectionEndedEarly(SectionEndInfo
const & endInfo) {
12860 if (m_unfinishedSections.empty())
12861 m_activeSections.back()->fail();
12863 m_activeSections.back()->close();
12864 m_activeSections.pop_back();
12866 m_unfinishedSections.push_back(endInfo);
12869 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12870 void RunContext::benchmarkPreparing(std::string
const& name) {
12871 m_reporter->benchmarkPreparing(name);
12873 void RunContext::benchmarkStarting( BenchmarkInfo
const& info ) {
12874 m_reporter->benchmarkStarting( info );
12876 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12877 m_reporter->benchmarkEnded( stats );
12879 void RunContext::benchmarkFailed(std::string
const & error) {
12880 m_reporter->benchmarkFailed(error);
12882 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12884 void RunContext::pushScopedMessage(MessageInfo
const & message) {
12885 m_messages.push_back(message);
12888 void RunContext::popScopedMessage(MessageInfo
const & message) {
12889 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12892 void RunContext::emplaceUnscopedMessage( MessageBuilder
const& builder ) {
12893 m_messageScopes.emplace_back( builder );
12896 std::string RunContext::getCurrentTestName()
const {
12897 return m_activeTestCase
12898 ? m_activeTestCase->getTestCaseInfo().name
12902 const AssertionResult * RunContext::getLastResult()
const {
12903 return &(*m_lastResult);
12906 void RunContext::exceptionEarlyReported() {
12907 m_shouldReportUnexpected =
false;
12910 void RunContext::handleFatalErrorCondition( StringRef message ) {
12912 m_reporter->fatalErrorEncountered(message);
12917 tempResult.message =
static_cast<std::string
>(message);
12918 AssertionResult result(m_lastAssertionInfo, tempResult);
12920 assertionEnded(result);
12922 handleUnfinishedSections();
12925 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12926 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12929 assertions.failed = 1;
12930 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12931 m_reporter->sectionEnded(testCaseSectionStats);
12933 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12935 Totals deltaTotals;
12936 deltaTotals.testCases.failed = 1;
12937 deltaTotals.assertions.failed = 1;
12938 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12943 m_totals.testCases.failed++;
12944 testGroupEnded(std::string(), m_totals, 1, 1);
12945 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12948 bool RunContext::lastAssertionPassed() {
12949 return m_lastAssertionPassed;
12952 void RunContext::assertionPassed() {
12953 m_lastAssertionPassed =
true;
12954 ++m_totals.assertions.passed;
12955 resetAssertionInfo();
12956 m_messageScopes.clear();
12959 bool RunContext::aborting()
const {
12960 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12963 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12964 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12965 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12966 m_reporter->sectionStarting(testCaseSection);
12967 Counts prevAssertions = m_totals.assertions;
12968 double duration = 0;
12969 m_shouldReportUnexpected =
true;
12972 seedRng(*m_config);
12976 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12977 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12978 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12981 invokeActiveTestCase();
12983 OutputRedirect r(redirectedCout, redirectedCerr);
12985 invokeActiveTestCase();
12989 invokeActiveTestCase();
12991 duration = timer.getElapsedSeconds();
12997 if( m_shouldReportUnexpected ) {
12998 AssertionReaction dummyReaction;
13002 Counts assertions = m_totals.assertions - prevAssertions;
13003 bool missingAssertions = testForMissingAssertions(assertions);
13005 m_testCaseTracker->close();
13006 handleUnfinishedSections();
13007 m_messages.clear();
13008 m_messageScopes.clear();
13010 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13011 m_reporter->sectionEnded(testCaseSectionStats);
13014 void RunContext::invokeActiveTestCase() {
13015 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13016 m_activeTestCase->invoke();
13019 void RunContext::handleUnfinishedSections() {
13022 for (
auto it = m_unfinishedSections.rbegin(),
13023 itEnd = m_unfinishedSections.rend();
13027 m_unfinishedSections.clear();
13030 void RunContext::handleExpr(
13031 AssertionInfo
const& info,
13032 ITransientExpression
const& expr,
13033 AssertionReaction& reaction
13035 m_reporter->assertionStarting( info );
13037 bool negated =
isFalseTest( info.resultDisposition );
13038 bool result = expr.getResult() != negated;
13041 if (!m_includeSuccessfulResults) {
13050 populateReaction( reaction );
13053 void RunContext::reportExpr(
13054 AssertionInfo
const &info,
13056 ITransientExpression
const *expr,
13059 m_lastAssertionInfo = info;
13060 AssertionResultData data( resultType, LazyExpression( negated ) );
13062 AssertionResult assertionResult{ info, data };
13063 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13065 assertionEnded( assertionResult );
13068 void RunContext::handleMessage(
13069 AssertionInfo
const& info,
13071 StringRef
const& message,
13072 AssertionReaction& reaction
13074 m_reporter->assertionStarting( info );
13076 m_lastAssertionInfo = info;
13078 AssertionResultData data( resultType, LazyExpression(
false ) );
13079 data.message =
static_cast<std::string
>(message);
13080 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13081 assertionEnded( assertionResult );
13082 if( !assertionResult.isOk() )
13083 populateReaction( reaction );
13085 void RunContext::handleUnexpectedExceptionNotThrown(
13086 AssertionInfo
const& info,
13087 AssertionReaction& reaction
13092 void RunContext::handleUnexpectedInflightException(
13093 AssertionInfo
const& info,
13094 std::string
const& message,
13095 AssertionReaction& reaction
13097 m_lastAssertionInfo = info;
13100 data.message = message;
13101 AssertionResult assertionResult{ info, data };
13102 assertionEnded( assertionResult );
13103 populateReaction( reaction );
13106 void RunContext::populateReaction( AssertionReaction& reaction ) {
13107 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13111 void RunContext::handleIncomplete(
13112 AssertionInfo
const& info
13114 m_lastAssertionInfo = info;
13117 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13118 AssertionResult assertionResult{ info, data };
13119 assertionEnded( assertionResult );
13121 void RunContext::handleNonExpr(
13122 AssertionInfo
const &info,
13124 AssertionReaction &reaction
13126 m_lastAssertionInfo = info;
13128 AssertionResultData data( resultType, LazyExpression(
false ) );
13129 AssertionResult assertionResult{ info, data };
13130 assertionEnded( assertionResult );
13132 if( !assertionResult.isOk() )
13133 populateReaction( reaction );
13143 void seedRng(IConfig
const& config) {
13144 if (config.rngSeed() != 0) {
13145 std::srand(config.rngSeed());
13146 rng().
seed(config.rngSeed());
13162 m_sectionIncluded(
getResultCapture().sectionStarted( m_info, m_assertions ) )
13170 if( uncaught_exceptions() )
13178 Section::operator bool()
const {
13179 return m_sectionIncluded;
13189 ( SourceLineInfo
const& _lineInfo,
13190 std::string
const& _name )
13192 lineInfo( _lineInfo )
13205 class Session : NonCopyable {
13209 ~Session()
override;
13211 void showHelp()
const;
13212 void libIdentify();
13214 int applyCommandLine(
int argc,
char const *
const * argv );
13215 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13216 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13219 void useConfigData( ConfigData
const& configData );
13221 template<
typename CharT>
13222 int run(
int argc, CharT
const *
const argv[]) {
13223 if (m_startupExceptions)
13225 int returnCode = applyCommandLine(argc, argv);
13226 if (returnCode == 0)
13227 returnCode = run();
13233 clara::Parser
const& cli()
const;
13234 void cli( clara::Parser
const& newParser );
13235 ConfigData& configData();
13240 clara::Parser m_cli;
13241 ConfigData m_configData;
13242 std::shared_ptr<Config> m_config;
13243 bool m_startupExceptions =
false;
13257 Version( Version
const& ) =
delete;
13258 Version& operator=( Version
const& ) =
delete;
13259 Version(
unsigned int _majorVersion,
13260 unsigned int _minorVersion,
13261 unsigned int _patchNumber,
13262 char const *
const _branchName,
13263 unsigned int _buildNumber );
13265 unsigned int const majorVersion;
13266 unsigned int const minorVersion;
13267 unsigned int const patchNumber;
13270 char const *
const branchName;
13271 unsigned int const buildNumber;
13273 friend std::ostream&
operator << ( std::ostream& os, Version
const& version );
13276 Version
const& libraryVersion();
13283 #include <iterator>
13288 const int MaxExitCode = 255;
13290 IStreamingReporterPtr createReporter(std::string
const& reporterName,
IConfigPtr const& config) {
13292 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13297 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13299 return createReporter(config->getReporterName(), config);
13307 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13308 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13310 for (
auto const& listener : listeners) {
13311 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13313 multi.addReporter(createReporter(config->getReporterName(), config));
13319 explicit TestGroup(std::shared_ptr<Config>
const& config)
13321 , m_context{config, makeReporter(config)}
13324 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13325 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13327 if (m_matches.empty() && invalidArgs.empty()) {
13328 for (
auto const& test : allTestCases)
13329 if (!test.isHidden())
13330 m_tests.emplace(&test);
13332 for (
auto const& match : m_matches)
13333 m_tests.insert(match.tests.begin(), match.tests.end());
13338 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13340 m_context.testGroupStarting(m_config->name(), 1, 1);
13341 for (
auto const& testCase : m_tests) {
13342 if (!m_context.aborting())
13343 totals += m_context.runTest(*testCase);
13345 m_context.reporter().skipTest(*testCase);
13348 for (
auto const& match : m_matches) {
13349 if (match.tests.empty()) {
13350 m_context.reporter().noMatchingTestCases(match.name);
13355 if (!invalidArgs.empty()) {
13356 for (
auto const& invalidArg: invalidArgs)
13357 m_context.reporter().reportInvalidArguments(invalidArg);
13360 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13365 using Tests = std::set<TestCase const*>;
13367 std::shared_ptr<Config> m_config;
13368 RunContext m_context;
13375 for (
auto& testCase : tests) {
13376 auto tags = testCase.tags;
13378 std::string filename = testCase.lineInfo.file;
13379 auto lastSlash = filename.find_last_of(
"\\/");
13380 if (lastSlash != std::string::npos) {
13381 filename.erase(0, lastSlash);
13385 auto lastDot = filename.find_last_of(
'.');
13386 if (lastDot != std::string::npos) {
13387 filename.erase(lastDot);
13390 tags.push_back(std::move(filename));
13391 setTags(testCase, tags);
13397 Session::Session() {
13398 static bool alreadyInstantiated =
false;
13399 if( alreadyInstantiated ) {
13405 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13407 if ( !exceptions.empty() ) {
13411 m_startupExceptions =
true;
13412 Colour colourGuard( Colour::Red );
13413 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13415 for (
const auto& ex_ptr : exceptions ) {
13417 std::rethrow_exception(ex_ptr);
13418 }
catch ( std::exception
const& ex ) {
13419 Catch::cerr() << Column( ex.what() ).indent(2) <<
'\n';
13425 alreadyInstantiated =
true;
13426 m_cli = makeCommandLineParser( m_configData );
13428 Session::~Session() {
13432 void Session::showHelp()
const {
13434 <<
"\nCatch v" << libraryVersion() <<
"\n"
13435 << m_cli << std::endl
13436 <<
"For more detailed usage please see the project docs\n" << std::endl;
13438 void Session::libIdentify() {
13440 << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n"
13441 << std::left << std::setw(16) <<
"category: " <<
"testframework\n"
13442 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n"
13443 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13446 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13447 if( m_startupExceptions )
13450 auto result = m_cli.parse( clara::Args( argc, argv ) );
13455 << Colour( Colour::Red )
13456 <<
"\nError(s) in input:\n"
13457 << Column( result.errorMessage() ).indent( 2 )
13459 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13460 return MaxExitCode;
13463 if( m_configData.showHelp )
13465 if( m_configData.libIdentify )
13471 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13472 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13474 char **utf8Argv =
new char *[ argc ];
13476 for (
int i = 0; i < argc; ++i ) {
13477 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr );
13479 utf8Argv[ i ] =
new char[ bufSize ];
13481 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13484 int returnCode = applyCommandLine( argc, utf8Argv );
13486 for (
int i = 0; i < argc; ++i )
13487 delete [] utf8Argv[ i ];
13489 delete [] utf8Argv;
13495 void Session::useConfigData( ConfigData
const& configData ) {
13496 m_configData = configData;
13500 int Session::run() {
13501 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13502 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13503 static_cast<void>(std::getchar());
13505 int exitCode = runInternal();
13506 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13507 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13508 static_cast<void>(std::getchar());
13513 clara::Parser
const& Session::cli()
const {
13516 void Session::cli( clara::Parser
const& newParser ) {
13519 ConfigData& Session::configData() {
13520 return m_configData;
13522 Config& Session::config() {
13524 m_config = std::make_shared<Config>( m_configData );
13528 int Session::runInternal() {
13529 if( m_startupExceptions )
13532 if (m_configData.showHelp || m_configData.libIdentify) {
13539 seedRng( *m_config );
13541 if( m_configData.filenamesAsTags )
13542 applyFilenamesAsTags( *m_config );
13545 if( Option<std::size_t> listed = list( m_config ) )
13546 return static_cast<int>( *listed );
13548 TestGroup tests { m_config };
13549 auto const totals = tests.execute();
13551 if( m_config->warnAboutNoTests() && totals.error == -1 )
13557 return (std::min) (MaxExitCode, (std::max) (totals.error,
static_cast<int>(totals.assertions.failed)));
13559 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13560 catch( std::exception& ex ) {
13562 return MaxExitCode;
13576 static auto getSingletons() -> std::vector<ISingleton*>*& {
13577 static std::vector<ISingleton*>* g_singletons =
nullptr;
13578 if( !g_singletons )
13579 g_singletons =
new std::vector<ISingleton*>();
13580 return g_singletons;
13584 ISingleton::~ISingleton() {}
13586 void addSingleton(ISingleton* singleton ) {
13587 getSingletons()->push_back( singleton );
13589 void cleanupSingletons() {
13590 auto& singletons = getSingletons();
13591 for(
auto singleton : *singletons )
13594 singletons =
nullptr;
13601 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13603 void StartupExceptionRegistry::add( std::exception_ptr
const& exception ) noexcept {
13605 m_exceptions.push_back(exception);
13612 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions() const noexcept {
13613 return m_exceptions;
13622 #include <iostream>
13632 namespace Detail {
namespace {
13633 template<
typename WriterF, std::
size_t bufferSize=256>
13634 class StreamBufImpl :
public std::streambuf {
13635 char data[bufferSize];
13640 setp( data, data +
sizeof(data) );
13643 ~StreamBufImpl() noexcept {
13644 StreamBufImpl::sync();
13648 int overflow(
int c )
override {
13652 if( pbase() == epptr() )
13653 m_writer( std::string( 1,
static_cast<char>( c ) ) );
13655 sputc(
static_cast<char>( c ) );
13660 int sync()
override {
13661 if( pbase() != pptr() ) {
13662 m_writer( std::string( pbase(),
static_cast<std::string::size_type
>( pptr() - pbase() ) ) );
13663 setp( pbase(), epptr() );
13671 struct OutputDebugWriter {
13673 void operator()( std::string
const&str ) {
13674 writeToDebugConsole( str );
13680 class FileStream :
public IStream {
13681 mutable std::ofstream m_ofs;
13683 FileStream( StringRef filename ) {
13684 m_ofs.open( filename.c_str() );
13685 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13687 ~FileStream()
override =
default;
13689 std::ostream& stream()
const override {
13696 class CoutStream :
public IStream {
13697 mutable std::ostream m_os;
13701 CoutStream() : m_os(
Catch::
cout().rdbuf() ) {}
13702 ~CoutStream()
override =
default;
13705 std::ostream& stream()
const override {
return m_os; }
13710 class DebugOutStream :
public IStream {
13711 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13712 mutable std::ostream m_os;
13715 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13716 m_os( m_streamBuf.
get() )
13719 ~DebugOutStream()
override =
default;
13722 std::ostream& stream()
const override {
return m_os; }
13729 auto makeStream( StringRef
const &filename ) -> IStream
const* {
13730 if( filename.empty() )
13731 return new Detail::CoutStream();
13732 else if( filename[0] ==
'%' ) {
13733 if( filename ==
"%debug" )
13734 return new Detail::DebugOutStream();
13736 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13739 return new Detail::FileStream( filename );
13743 struct StringStreams {
13744 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13745 std::vector<std::size_t> m_unused;
13746 std::ostringstream m_referenceStream;
13748 auto add() -> std::size_t {
13749 if( m_unused.empty() ) {
13750 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13751 return m_streams.size()-1;
13754 auto index = m_unused.back();
13755 m_unused.pop_back();
13760 void release( std::size_t index ) {
13761 m_streams[index]->copyfmt( m_referenceStream );
13762 m_unused.push_back(index);
13767 : m_index( Singleton<StringStreams>::getMutable().add() ),
13768 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].
get() )
13772 static_cast<std::ostringstream*
>(
m_oss )->
str(
"");
13774 Singleton<StringStreams>::getMutable().release(
m_index );
13778 return static_cast<std::ostringstream*
>(
m_oss )->
str();
13783 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
13792 #include <algorithm>
13801 char toLowerCh(
char c) {
13802 return static_cast<char>( std::tolower(
static_cast<unsigned char>(c) ) );
13806 bool startsWith( std::string
const& s, std::string
const& prefix ) {
13807 return s.size() >= prefix.size() &&
std::equal(prefix.begin(), prefix.end(), s.begin());
13809 bool startsWith( std::string
const& s,
char prefix ) {
13810 return !s.empty() && s[0] == prefix;
13812 bool endsWith( std::string
const& s, std::string
const& suffix ) {
13813 return s.size() >= suffix.size() &&
std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13815 bool endsWith( std::string
const& s,
char suffix ) {
13816 return !s.empty() && s[s.size()-1] == suffix;
13818 bool contains( std::string
const& s, std::string
const& infix ) {
13819 return s.find( infix ) != std::string::npos;
13822 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13824 std::string
toLower( std::string
const& s ) {
13825 std::string lc = s;
13829 std::string
trim( std::string
const& str ) {
13830 static char const* whitespaceChars =
"\n\r\t ";
13831 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13832 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13834 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13837 StringRef
trim(StringRef ref) {
13838 const auto is_ws = [](
char c) {
13839 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r';
13841 size_t real_begin = 0;
13842 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13843 size_t real_end = ref.size();
13844 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13846 return ref.substr(real_begin, real_end - real_begin);
13849 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
13850 bool replaced =
false;
13851 std::size_t i = str.find( replaceThis );
13852 while( i != std::string::npos ) {
13854 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13855 if( i < str.size()-withThis.size() )
13856 i = str.find( replaceThis, i+withThis.size() );
13858 i = std::string::npos;
13863 std::vector<StringRef>
splitStringRef( StringRef str,
char delimiter ) {
13864 std::vector<StringRef> subStrings;
13865 std::size_t start = 0;
13866 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13867 if( str[pos] == delimiter ) {
13868 if( pos - start > 1 )
13869 subStrings.push_back( str.substr( start, pos-start ) );
13873 if( start < str.size() )
13874 subStrings.push_back( str.substr( start, str.size()-start ) );
13878 pluralise::pluralise( std::size_t count, std::string
const& label )
13879 : m_count( count ),
13883 std::ostream&
operator << ( std::ostream& os, pluralise
const& pluraliser ) {
13884 os << pluraliser.m_count <<
' ' << pluraliser.m_label;
13885 if( pluraliser.m_count != 1 )
13894 #include <algorithm>
13912 auto StringRef::substr( size_type start, size_type size )
const noexcept -> StringRef {
13913 if (start < m_size) {
13914 return StringRef(m_start + start, (std::min)(m_size - start, size));
13916 return StringRef();
13920 return m_size == other.m_size
13921 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13924 auto operator << ( std::ostream& os, StringRef
const& str ) -> std::ostream& {
13925 return os.write(str.data(), str.size());
13928 auto operator+=( std::string& lhs, StringRef
const& rhs ) -> std::string& {
13929 lhs.append(rhs.data(), rhs.size());
13938 TagAlias::TagAlias(std::string
const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13962 TagAliasRegistry::~TagAliasRegistry() {}
13965 auto it = m_registry.find( alias );
13966 if( it != m_registry.end() )
13967 return &(it->second);
13972 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
13973 std::string expandedTestSpec = unexpandedTestSpec;
13974 for(
auto const& registryKvp : m_registry ) {
13975 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13976 if( pos != std::string::npos ) {
13977 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13978 registryKvp.second.tag +
13979 expandedTestSpec.substr( pos + registryKvp.first.size() );
13982 return expandedTestSpec;
13985 void TagAliasRegistry::add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo ) {
13987 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
13989 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13990 "error: tag alias, '" << alias <<
"' already registered.\n"
13991 <<
"\tFirst seen at: " <<
find(alias)->lineInfo <<
"\n"
13992 <<
"\tRedefined at: " << lineInfo );
13995 ITagAliasRegistry::~ITagAliasRegistry() {}
14006 #include <exception>
14007 #include <algorithm>
14017 else if( tag ==
"!throws" )
14019 else if( tag ==
"!shouldfail" )
14021 else if( tag ==
"!mayfail" )
14023 else if( tag ==
"!nonportable" )
14025 else if( tag ==
"!benchmark" )
14030 bool isReservedTag( std::string
const& tag ) {
14031 return parseSpecialTag( tag ) ==
TestCaseInfo::None && tag.size() > 0 && !std::isalnum(
static_cast<unsigned char>(tag[0]) );
14033 void enforceNotReservedTag( std::string
const& tag, SourceLineInfo
const& _lineInfo ) {
14035 "Tag name: [" << tag <<
"] is not allowed.\n"
14036 <<
"Tag names starting with non alphanumeric characters are reserved\n"
14042 std::string
const& _className,
14043 NameAndTags
const& nameAndTags,
14044 SourceLineInfo
const& _lineInfo )
14046 bool isHidden =
false;
14049 std::vector<std::string> tags;
14050 std::string desc, tag;
14051 bool inTag =
false;
14052 for (
char c : nameAndTags.tags) {
14065 enforceNotReservedTag( tag, _lineInfo );
14070 if (
startsWith(tag,
'.') && tag.size() > 1) {
14073 tags.push_back( tag );
14083 tags.insert( tags.end(), {
".",
"!hide" } );
14086 TestCaseInfo info(
static_cast<std::string
>(nameAndTags.name), _className, desc, tags, _lineInfo );
14087 return TestCase( _testCase, std::move(info) );
14090 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14091 std::sort(begin(tags), end(tags));
14092 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14093 testCaseInfo.lcaseTags.clear();
14095 for(
auto const& tag : tags ) {
14096 std::string lcaseTag =
toLower( tag );
14098 testCaseInfo.lcaseTags.push_back( lcaseTag );
14100 testCaseInfo.tags = std::move(tags);
14104 std::string
const& _className,
14105 std::string
const& _description,
14106 std::vector<std::string>
const& _tags,
14107 SourceLineInfo
const& _lineInfo )
14109 className( _className ),
14110 description( _description ),
14111 lineInfo( _lineInfo ),
14114 setTags( *
this, _tags );
14133 std::size_t full_size = 2 *
tags.size();
14134 for (
const auto& tag :
tags) {
14135 full_size += tag.size();
14137 ret.reserve(full_size);
14138 for (
const auto& tag :
tags) {
14139 ret.push_back(
'[');
14141 ret.push_back(
']');
14147 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo(
std::move(info) ), test( testCase ) {}
14151 other.name = _newName;
14160 return test.get() == other.test.get() &&
14161 name == other.name &&
14166 return name < other.name;
14178 #include <algorithm>
14184 struct TestHasher {
14185 using hash_t = uint64_t;
14187 explicit TestHasher( hash_t hashSuffix ):
14188 m_hashSuffix{ hashSuffix } {}
14190 uint32_t operator()( TestCase
const& t )
const {
14192 const hash_t prime = 1099511628211u;
14193 hash_t hash = 14695981039346656037u;
14194 for (
const char c : t.name ) {
14198 hash ^= m_hashSuffix;
14200 const uint32_t low{
static_cast<uint32_t
>( hash ) };
14201 const uint32_t high{
static_cast<uint32_t
>( hash >> 32 ) };
14206 hash_t m_hashSuffix;
14210 std::vector<TestCase> sortTests( IConfig
const& config, std::vector<TestCase>
const& unsortedTestCases ) {
14211 switch( config.runOrder() ) {
14217 std::vector<TestCase> sorted = unsortedTestCases;
14218 std::sort( sorted.begin(), sorted.end() );
14224 TestHasher h{ config.rngSeed() };
14226 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14227 std::vector<hashedTest> indexed_tests;
14228 indexed_tests.reserve( unsortedTestCases.size() );
14230 for (
auto const& testCase : unsortedTestCases) {
14231 indexed_tests.emplace_back(h(testCase), &testCase);
14234 std::sort(indexed_tests.begin(), indexed_tests.end(),
14235 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14236 if (lhs.first == rhs.first) {
14237 return lhs.second->name < rhs.second->name;
14239 return lhs.first < rhs.first;
14242 std::vector<TestCase> sorted;
14243 sorted.reserve( indexed_tests.size() );
14245 for (
auto const& hashed : indexed_tests) {
14246 sorted.emplace_back(*hashed.second);
14252 return unsortedTestCases;
14255 bool isThrowSafe( TestCase
const& testCase, IConfig
const& config ) {
14256 return !testCase.throws() || config.allowThrows();
14259 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config ) {
14260 return testSpec.matches( testCase ) &&
isThrowSafe( testCase, config );
14263 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14264 std::set<TestCase> seenFunctions;
14265 for(
auto const&
function : functions ) {
14266 auto prev = seenFunctions.insert(
function );
14268 "error: TEST_CASE( \"" <<
function.name <<
"\" ) already defined.\n"
14269 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n"
14270 <<
"\tRedefined at " <<
function.getTestCaseInfo().lineInfo );
14274 std::vector<TestCase>
filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config ) {
14275 std::vector<TestCase> filtered;
14276 filtered.reserve( testCases.size() );
14277 for (
auto const& testCase : testCases) {
14278 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14279 (testSpec.hasFilters() &&
matchTest(testCase, testSpec, config))) {
14280 filtered.push_back(testCase);
14289 void TestRegistry::registerTest( TestCase
const& testCase ) {
14290 std::string name = testCase.getTestCaseInfo().name;
14291 if( name.empty() ) {
14292 ReusableStringStream rss;
14293 rss <<
"Anonymous test case " << ++m_unnamedCount;
14294 return registerTest( testCase.withName( rss.str() ) );
14296 m_functions.push_back( testCase );
14299 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14300 return m_functions;
14302 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted( IConfig
const& config )
const {
14303 if( m_sortedFunctions.empty() )
14304 enforceNoDuplicateTestCases( m_functions );
14306 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14307 m_sortedFunctions = sortTests( config, m_functions );
14308 m_currentSortOrder = config.runOrder();
14310 return m_sortedFunctions;
14314 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14316 void TestInvokerAsFunction::invoke()
const {
14317 m_testAsFunction();
14320 std::string extractClassName( StringRef
const& classOrQualifiedMethodName ) {
14321 std::string className(classOrQualifiedMethodName);
14324 std::size_t lastColons = className.rfind(
"::" );
14325 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14326 if( penultimateColons == std::string::npos )
14327 penultimateColons = 1;
14328 className = className.substr( penultimateColons, lastColons-penultimateColons );
14337 #include <algorithm>
14339 #include <stdexcept>
14343 #if defined(__clang__)
14344 # pragma clang diagnostic push
14345 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14349 namespace TestCaseTracking {
14351 NameAndLocation::NameAndLocation( std::string
const& _name, SourceLineInfo
const& _location )
14353 location( _location )
14356 ITracker::~ITracker() =
default;
14358 ITracker& TrackerContext::startRun() {
14359 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}",
CATCH_INTERNAL_LINEINFO ), *
this,
nullptr );
14360 m_currentTracker =
nullptr;
14361 m_runState = Executing;
14362 return *m_rootTracker;
14365 void TrackerContext::endRun() {
14366 m_rootTracker.reset();
14367 m_currentTracker =
nullptr;
14368 m_runState = NotStarted;
14371 void TrackerContext::startCycle() {
14372 m_currentTracker = m_rootTracker.get();
14373 m_runState = Executing;
14375 void TrackerContext::completeCycle() {
14376 m_runState = CompletedCycle;
14379 bool TrackerContext::completedCycle()
const {
14380 return m_runState == CompletedCycle;
14382 ITracker& TrackerContext::currentTracker() {
14383 return *m_currentTracker;
14385 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14386 m_currentTracker = tracker;
14389 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14390 ITracker(nameAndLocation),
14395 bool TrackerBase::isComplete()
const {
14396 return m_runState == CompletedSuccessfully || m_runState == Failed;
14398 bool TrackerBase::isSuccessfullyCompleted()
const {
14399 return m_runState == CompletedSuccessfully;
14401 bool TrackerBase::isOpen()
const {
14402 return m_runState != NotStarted && !isComplete();
14404 bool TrackerBase::hasChildren()
const {
14405 return !m_children.empty();
14408 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14409 m_children.push_back( child );
14412 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14413 auto it = std::find_if( m_children.begin(), m_children.end(),
14414 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14416 tracker->nameAndLocation().location == nameAndLocation.location &&
14417 tracker->nameAndLocation().name == nameAndLocation.name;
14419 return( it != m_children.end() )
14423 ITracker& TrackerBase::parent() {
14424 assert( m_parent );
14428 void TrackerBase::openChild() {
14429 if( m_runState != ExecutingChildren ) {
14430 m_runState = ExecutingChildren;
14432 m_parent->openChild();
14436 bool TrackerBase::isSectionTracker()
const {
return false; }
14437 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14439 void TrackerBase::open() {
14440 m_runState = Executing;
14443 m_parent->openChild();
14446 void TrackerBase::close() {
14449 while( &m_ctx.currentTracker() !=
this )
14450 m_ctx.currentTracker().close();
14452 switch( m_runState ) {
14453 case NeedsAnotherRun:
14457 m_runState = CompletedSuccessfully;
14459 case ExecutingChildren:
14460 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const& t){ return t->isComplete(); }) )
14461 m_runState = CompletedSuccessfully;
14465 case CompletedSuccessfully:
14473 m_ctx.completeCycle();
14475 void TrackerBase::fail() {
14476 m_runState = Failed;
14478 m_parent->markAsNeedingAnotherRun();
14480 m_ctx.completeCycle();
14482 void TrackerBase::markAsNeedingAnotherRun() {
14483 m_runState = NeedsAnotherRun;
14486 void TrackerBase::moveToParent() {
14487 assert( m_parent );
14488 m_ctx.setCurrentTracker( m_parent );
14490 void TrackerBase::moveToThis() {
14491 m_ctx.setCurrentTracker(
this );
14494 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14495 : TrackerBase( nameAndLocation, ctx, parent ),
14496 m_trimmed_name(
trim(nameAndLocation.name))
14499 while( !parent->isSectionTracker() )
14500 parent = &parent->parent();
14502 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14503 addNextFilters( parentSection.m_filters );
14507 bool SectionTracker::isComplete()
const {
14508 bool complete =
true;
14510 if (m_filters.empty()
14511 || m_filters[0] ==
""
14512 ||
std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14513 complete = TrackerBase::isComplete();
14518 bool SectionTracker::isSectionTracker()
const {
return true; }
14520 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14521 std::shared_ptr<SectionTracker> section;
14523 ITracker& currentTracker = ctx.currentTracker();
14524 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14525 assert( childTracker );
14526 assert( childTracker->isSectionTracker() );
14527 section = std::static_pointer_cast<SectionTracker>( childTracker );
14530 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14531 currentTracker.addChild( section );
14533 if( !ctx.completedCycle() )
14534 section->tryOpen();
14538 void SectionTracker::tryOpen() {
14539 if( !isComplete() )
14543 void SectionTracker::addInitialFilters( std::vector<std::string>
const& filters ) {
14544 if( !filters.empty() ) {
14545 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14546 m_filters.emplace_back(
"");
14547 m_filters.emplace_back(
"");
14548 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14551 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14552 if( filters.size() > 1 )
14553 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14556 std::vector<std::string>
const& SectionTracker::getFilters()
const {
14560 std::string
const& SectionTracker::trimmedName()
const {
14561 return m_trimmed_name;
14566 using TestCaseTracking::ITracker;
14567 using TestCaseTracking::TrackerContext;
14568 using TestCaseTracking::SectionTracker;
14572 #if defined(__clang__)
14573 # pragma clang diagnostic pop
14580 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14581 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14584 NameAndTags::NameAndTags( StringRef
const& name_ , StringRef
const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14586 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo
const& lineInfo, StringRef
const& classOrMethod, NameAndTags
const& nameAndTags ) noexcept {
14592 extractClassName( classOrMethod ),
14606 #include <algorithm>
14613 TestSpec::Pattern::Pattern( std::string
const& name )
14617 TestSpec::Pattern::~Pattern() =
default;
14619 std::string
const& TestSpec::Pattern::name()
const {
14623 TestSpec::NamePattern::NamePattern( std::string
const& name, std::string
const& filterString )
14624 : Pattern( filterString )
14625 , m_wildcardPattern(
toLower( name ), CaseSensitive::No )
14628 bool TestSpec::NamePattern::matches( TestCaseInfo
const& testCase )
const {
14629 return m_wildcardPattern.matches( testCase.name );
14632 TestSpec::TagPattern::TagPattern( std::string
const& tag, std::string
const& filterString )
14633 : Pattern( filterString )
14637 bool TestSpec::TagPattern::matches( TestCaseInfo
const& testCase )
const {
14638 return std::find(begin(testCase.lcaseTags),
14639 end(testCase.lcaseTags),
14640 m_tag) != end(testCase.lcaseTags);
14643 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14644 : Pattern( underlyingPattern->name() )
14645 , m_underlyingPattern( underlyingPattern )
14648 bool TestSpec::ExcludedPattern::matches( TestCaseInfo
const& testCase )
const {
14649 return !m_underlyingPattern->matches( testCase );
14652 bool TestSpec::Filter::matches( TestCaseInfo
const& testCase )
const {
14653 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const& p ){ return p->matches( testCase ); } );
14656 std::string TestSpec::Filter::name()
const {
14658 for(
auto const& p : m_patterns )
14663 bool TestSpec::hasFilters()
const {
14664 return !m_filters.empty();
14667 bool TestSpec::matches( TestCaseInfo
const& testCase )
const {
14668 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const& f ){ return f.matches( testCase ); } );
14671 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase>
const& testCases, IConfig
const& config )
const
14673 Matches matches( m_filters.size() );
14674 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter
const&
filter ){
14675 std::vector<TestCase const*> currentMatches;
14676 for( auto const& test : testCases )
14677 if( isThrowSafe( test, config ) && filter.matches( test ) )
14678 currentMatches.emplace_back( &test );
14679 return FilterMatch{ filter.name(), currentMatches };
14684 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14685 return (m_invalidArgs);
14694 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14696 TestSpecParser& TestSpecParser::parse( std::string
const& arg ) {
14698 m_exclusion =
false;
14699 m_arg = m_tagAliases->expandAliases( arg );
14700 m_escapeChars.clear();
14701 m_substring.reserve(m_arg.size());
14702 m_patternName.reserve(m_arg.size());
14703 m_realPatternPos = 0;
14705 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14707 if( !visitChar( m_arg[m_pos] ) ){
14708 m_testSpec.m_invalidArgs.push_back(arg);
14714 TestSpec TestSpecParser::testSpec() {
14718 bool TestSpecParser::visitChar(
char c ) {
14719 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14721 addCharToPattern(c);
14723 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14729 if( processNoneChar( c ) )
14733 processNameChar( c );
14737 addCharToPattern(c);
14742 if( processOtherChar( c ) )
14748 if( !isControlChar( c ) ) {
14749 m_patternName += c;
14750 m_realPatternPos++;
14756 bool TestSpecParser::processNoneChar(
char c ) {
14761 m_exclusion =
true;
14764 startNewMode( Tag );
14767 startNewMode( QuotedName );
14770 startNewMode( Name );
14774 void TestSpecParser::processNameChar(
char c ) {
14776 if( m_substring ==
"exclude:" )
14777 m_exclusion =
true;
14780 startNewMode( Tag );
14783 bool TestSpecParser::processOtherChar(
char c ) {
14784 if( !isControlChar( c ) )
14790 void TestSpecParser::startNewMode( Mode mode ) {
14793 void TestSpecParser::endMode() {
14797 return addNamePattern();
14799 return addTagPattern();
14801 revertBackToLastMode();
14805 return startNewMode( None );
14808 void TestSpecParser::escape() {
14810 m_mode = EscapedName;
14811 m_escapeChars.push_back(m_realPatternPos);
14813 bool TestSpecParser::isControlChar(
char c )
const {
14826 return c ==
'[' || c ==
']';
14830 void TestSpecParser::addFilter() {
14831 if( !m_currentFilter.m_patterns.empty() ) {
14832 m_testSpec.m_filters.push_back( m_currentFilter );
14833 m_currentFilter = TestSpec::Filter();
14837 void TestSpecParser::saveLastMode() {
14841 void TestSpecParser::revertBackToLastMode() {
14845 bool TestSpecParser::separate() {
14846 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14849 m_pos = m_arg.size();
14850 m_substring.clear();
14851 m_patternName.clear();
14852 m_realPatternPos = 0;
14860 std::string TestSpecParser::preprocessPattern() {
14861 std::string token = m_patternName;
14862 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14863 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14864 m_escapeChars.clear();
14866 m_exclusion =
true;
14867 token = token.substr(8);
14870 m_patternName.clear();
14871 m_realPatternPos = 0;
14876 void TestSpecParser::addNamePattern() {
14877 auto token = preprocessPattern();
14879 if (!token.empty()) {
14880 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14882 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14883 m_currentFilter.m_patterns.push_back(pattern);
14885 m_substring.clear();
14886 m_exclusion =
false;
14890 void TestSpecParser::addTagPattern() {
14891 auto token = preprocessPattern();
14893 if (!token.empty()) {
14896 if (token.size() > 1 && token[0] ==
'.') {
14897 token.erase(token.begin());
14898 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14900 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14902 m_currentFilter.m_patterns.push_back(pattern);
14905 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14908 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14910 m_currentFilter.m_patterns.push_back(pattern);
14912 m_substring.clear();
14913 m_exclusion =
false;
14917 TestSpec parseTestSpec( std::string
const& arg ) {
14927 static const uint64_t nanosecondsInSecond = 1000000000;
14932 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14936 auto estimateClockResolution() -> uint64_t {
14938 static const uint64_t iterations = 1000000;
14942 for( std::size_t i = 0; i < iterations; ++i ) {
14948 }
while( ticks == baseTicks );
14950 auto delta = ticks - baseTicks;
14956 if (ticks > startTime + 3 * nanosecondsInSecond) {
14957 return sum / ( i + 1u );
14963 return sum/iterations;
14967 static auto s_resolution = estimateClockResolution();
14968 return s_resolution;
14971 void Timer::start() {
14974 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14977 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14978 return getElapsedNanoseconds()/1000;
14980 auto Timer::getElapsedMilliseconds() const ->
unsigned int {
14981 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14983 auto Timer::getElapsedSeconds() const ->
double {
14984 return getElapsedMicroseconds()/1000000.0;
14991 #if defined(__clang__)
14992 # pragma clang diagnostic push
14993 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14994 # pragma clang diagnostic ignored "-Wglobal-constructors"
14998 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14999 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15012 const int hexThreshold = 255;
15014 struct Endianness {
15015 enum Arch { Big, Little };
15017 static Arch which() {
15021 auto value = *
reinterpret_cast<char*
>(&
one);
15022 return value ? Little : Big;
15029 int i = 0, end =
static_cast<int>( size ), inc = 1;
15030 if( Endianness::which() == Endianness::Little ) {
15035 unsigned char const *bytes =
static_cast<unsigned char const *
>(object);
15036 ReusableStringStream rss;
15037 rss <<
"0x" << std::setfill(
'0') << std::hex;
15038 for( ; i != end; i += inc )
15039 rss <<
std::setw(2) << static_cast<unsigned>(bytes[i]);
15044 template<
typename T>
15045 std::string fpToString( T
value,
int precision ) {
15046 if (Catch::isnan(
value)) {
15050 ReusableStringStream rss;
15051 rss << std::setprecision( precision )
15054 std::string d = rss.str();
15055 std::size_t i = d.find_last_not_of(
'0' );
15056 if( i != std::string::npos && i != d.size()-1 ) {
15059 d = d.substr( 0, i+1 );
15072 return '"' + str + '"';
15075 std::string s(
"\"");
15076 for (
char c : str) {
15093 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15103 return{
"{null string}" };
15110 return{
"{null string}" };
15114 #ifdef CATCH_CONFIG_WCHAR
15117 s.reserve(wstr.size());
15118 for (
auto c : wstr) {
15119 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15124 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15134 return{
"{null string}" };
15141 return{
"{null string}" };
15146 #if defined(CATCH_CONFIG_CPP17_BYTE)
15151 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15160 ReusableStringStream rss;
15162 if (
value > Detail::hexThreshold) {
15163 rss <<
" (0x" << std::hex <<
value <<
')';
15175 ReusableStringStream rss;
15177 if (
value > Detail::hexThreshold) {
15178 rss <<
" (0x" << std::hex <<
value <<
')';
15184 return b ?
"true" :
"false";
15188 if (
value ==
'\r') {
15190 }
else if (
value ==
'\f') {
15192 }
else if (
value ==
'\n') {
15194 }
else if (
value ==
'\t') {
15199 char chstr[] =
"' '";
15218 return fpToString(
value, precision) + 'f';
15224 return fpToString(
value, precision);
15227 std::string ratio_string<std::atto>::symbol() {
return "a"; }
15228 std::string ratio_string<std::femto>::symbol() {
return "f"; }
15229 std::string ratio_string<std::pico>::symbol() {
return "p"; }
15230 std::string ratio_string<std::nano>::symbol() {
return "n"; }
15231 std::string ratio_string<std::micro>::symbol() {
return "u"; }
15232 std::string ratio_string<std::milli>::symbol() {
return "m"; }
15236 #if defined(__clang__)
15237 # pragma clang diagnostic pop
15284 Totals diff = *
this - prevTotals;
15285 if( diff.assertions.failed > 0 )
15287 else if( diff.assertions.failedButOk > 0 )
15307 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15308 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15310 #if defined(_MSC_VER)
15311 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15312 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15316 #include <exception>
15318 #if defined(__cpp_lib_uncaught_exceptions) \
15319 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15321 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15322 #endif // __cpp_lib_uncaught_exceptions
15324 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15325 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15326 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15328 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15331 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15333 #include <exception>
15336 bool uncaught_exceptions() {
15337 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15339 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15340 return std::uncaught_exceptions() > 0;
15342 return std::uncaught_exception();
15354 (
unsigned int _majorVersion,
15355 unsigned int _minorVersion,
15356 unsigned int _patchNumber,
15357 char const *
const _branchName,
15358 unsigned int _buildNumber )
15359 : majorVersion( _majorVersion ),
15360 minorVersion( _minorVersion ),
15361 patchNumber( _patchNumber ),
15362 branchName( _branchName ),
15363 buildNumber( _buildNumber )
15366 std::ostream&
operator << ( std::ostream& os, Version
const& version ) {
15367 os << version.majorVersion <<
'.'
15368 << version.minorVersion <<
'.'
15369 << version.patchNumber;
15371 if (version.branchName[0]) {
15372 os <<
'-' << version.branchName
15373 <<
'.' << version.buildNumber;
15378 Version
const& libraryVersion() {
15379 static Version version( 2, 13, 5,
"", 0 );
15389 WildcardPattern::WildcardPattern( std::string
const& pattern,
15391 : m_caseSensitivity( caseSensitivity ),
15392 m_pattern( normaliseString( pattern ) )
15395 m_pattern = m_pattern.substr( 1 );
15396 m_wildcard = WildcardAtStart;
15398 if(
endsWith( m_pattern,
'*' ) ) {
15399 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15400 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15404 bool WildcardPattern::matches( std::string
const& str )
const {
15405 switch( m_wildcard ) {
15407 return m_pattern == normaliseString( str );
15408 case WildcardAtStart:
15409 return endsWith( normaliseString( str ), m_pattern );
15410 case WildcardAtEnd:
15411 return startsWith( normaliseString( str ), m_pattern );
15412 case WildcardAtBothEnds:
15413 return contains( normaliseString( str ), m_pattern );
15419 std::string WildcardPattern::normaliseString( std::string
const& str )
const {
15427 #include <type_traits>
15433 size_t trailingBytes(
unsigned char c) {
15434 if ((c & 0xE0) == 0xC0) {
15437 if ((c & 0xF0) == 0xE0) {
15440 if ((c & 0xF8) == 0xF0) {
15446 uint32_t headerValue(
unsigned char c) {
15447 if ((c & 0xE0) == 0xC0) {
15450 if ((c & 0xF0) == 0xE0) {
15453 if ((c & 0xF8) == 0xF0) {
15459 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15460 std::ios_base::fmtflags f(os.flags());
15462 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15463 <<
static_cast<int>(c);
15467 bool shouldNewline(XmlFormatting fmt) {
15468 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15471 bool shouldIndent(XmlFormatting fmt) {
15472 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15477 XmlFormatting
operator | (XmlFormatting lhs, XmlFormatting rhs) {
15478 return static_cast<XmlFormatting
>(
15479 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15480 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15484 XmlFormatting
operator & (XmlFormatting lhs, XmlFormatting rhs) {
15485 return static_cast<XmlFormatting
>(
15486 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15487 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15491 XmlEncode::XmlEncode( std::string
const& str, ForWhat forWhat )
15493 m_forWhat( forWhat )
15496 void XmlEncode::encodeTo( std::ostream& os )
const {
15500 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15501 unsigned char c = m_str[idx];
15503 case '<': os <<
"<";
break;
15504 case '&': os <<
"&";
break;
15508 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15515 if (m_forWhat == ForAttributes)
15526 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15527 hexEscapeChar(os, c);
15545 hexEscapeChar(os, c);
15549 auto encBytes = trailingBytes(c);
15551 if (idx + encBytes - 1 >= m_str.size()) {
15552 hexEscapeChar(os, c);
15559 uint32_t
value = headerValue(c);
15560 for (std::size_t
n = 1;
n < encBytes; ++
n) {
15561 unsigned char nc = m_str[idx + n];
15562 valid &= ((nc & 0xC0) == 0x80);
15571 (0x80 <=
value && value < 0x800 && encBytes > 2) ||
15572 (0x800 <
value && value < 0x10000 && encBytes > 3) ||
15574 (
value >= 0x110000)
15576 hexEscapeChar(os, c);
15581 for (std::size_t
n = 0;
n < encBytes; ++
n) {
15582 os << m_str[idx + n];
15584 idx += encBytes - 1;
15590 std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15591 xmlEncode.encodeTo( os );
15595 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15596 : m_writer( writer ),
15600 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15601 : m_writer( other.m_writer ),
15604 other.m_writer =
nullptr;
15605 other.m_fmt = XmlFormatting::None;
15607 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15609 m_writer->endElement();
15611 m_writer = other.m_writer;
15612 other.m_writer =
nullptr;
15613 m_fmt = other.m_fmt;
15614 other.m_fmt = XmlFormatting::None;
15618 XmlWriter::ScopedElement::~ScopedElement() {
15620 m_writer->endElement(m_fmt);
15624 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string
const& text, XmlFormatting fmt ) {
15625 m_writer->writeText( text, fmt );
15629 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15631 writeDeclaration();
15634 XmlWriter::~XmlWriter() {
15635 while (!m_tags.empty()) {
15638 newlineIfNecessary();
15641 XmlWriter& XmlWriter::startElement( std::string
const& name, XmlFormatting fmt ) {
15643 newlineIfNecessary();
15644 if (shouldIndent(fmt)) {
15648 m_os <<
'<' << name;
15649 m_tags.push_back( name );
15650 m_tagIsOpen =
true;
15651 applyFormatting(fmt);
15655 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string
const& name, XmlFormatting fmt ) {
15656 ScopedElement scoped(
this, fmt );
15657 startElement( name, fmt );
15661 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15662 m_indent = m_indent.substr(0, m_indent.size() - 2);
15664 if( m_tagIsOpen ) {
15666 m_tagIsOpen =
false;
15668 newlineIfNecessary();
15669 if (shouldIndent(fmt)) {
15672 m_os <<
"</" << m_tags.back() <<
">";
15674 m_os << std::flush;
15675 applyFormatting(fmt);
15680 XmlWriter& XmlWriter::writeAttribute( std::string
const& name, std::string
const& attribute ) {
15681 if( !name.empty() && !attribute.empty() )
15682 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15686 XmlWriter& XmlWriter::writeAttribute( std::string
const& name,
bool attribute ) {
15687 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15691 XmlWriter& XmlWriter::writeText( std::string
const& text, XmlFormatting fmt) {
15692 if( !text.empty() ){
15693 bool tagWasOpen = m_tagIsOpen;
15695 if (tagWasOpen && shouldIndent(fmt)) {
15698 m_os << XmlEncode( text );
15699 applyFormatting(fmt);
15704 XmlWriter& XmlWriter::writeComment( std::string
const& text, XmlFormatting fmt) {
15706 if (shouldIndent(fmt)) {
15709 m_os <<
"<!--" << text <<
"-->";
15710 applyFormatting(fmt);
15714 void XmlWriter::writeStylesheetRef( std::string
const& url ) {
15715 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15718 XmlWriter& XmlWriter::writeBlankLine() {
15724 void XmlWriter::ensureTagClosed() {
15725 if( m_tagIsOpen ) {
15726 m_os << '>
' << std::flush;
15727 newlineIfNecessary();
15728 m_tagIsOpen = false;
15732 void XmlWriter::applyFormatting(XmlFormatting fmt) {
15733 m_needsNewline = shouldNewline(fmt);
15736 void XmlWriter::writeDeclaration() {
15737 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15740 void XmlWriter::newlineIfNecessary() {
15741 if( m_needsNewline ) {
15743 m_needsNewline = false;
15747 // end catch_xmlwriter.cpp
15748 // start catch_reporter_bases.cpp
15757 void prepareExpandedExpression(AssertionResult& result) {
15758 result.getExpandedExpression();
15761 // Because formatting using c++ streams is stateful, drop down to C is required
15762 // Alternatively we could use stringstream, but its performance is... not good.
15763 std::string getFormattedDuration( double duration ) {
15764 // Max exponent + 1 is required to represent the whole part
15765 // + 1 for decimal point
15766 // + 3 for the 3 decimal places
15767 // + 1 for null terminator
15768 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15769 char buffer[maxDoubleSize];
15771 // Save previous errno, to prevent sprintf from overwriting it
15774 sprintf_s(buffer, "%.3f", duration);
15776 std::sprintf(buffer, "%.3f", duration);
15778 return std::string(buffer);
15781 bool shouldShowDuration( IConfig const& config, double duration ) {
15782 if ( config.showDurations() == ShowDurations::Always ) {
15785 if ( config.showDurations() == ShowDurations::Never ) {
15788 const double min = config.minDuration();
15789 return min >= 0 && duration >= min;
15792 std::string serializeFilters( std::vector<std::string> const& container ) {
15793 ReusableStringStream oss;
15795 for (auto&& filter : container)
15807 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15808 :StreamingReporterBase(_config) {}
15810 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15811 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15814 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15816 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15820 } // end namespace Catch
15821 // end catch_reporter_bases.cpp
15822 // start catch_reporter_compact.cpp
15826 #ifdef CATCH_PLATFORM_MAC
15827 const char* failedString() { return "FAILED"; }
15828 const char* passedString() { return "PASSED"; }
15830 const char* failedString() { return "failed"; }
15831 const char* passedString() { return "passed"; }
15834 // Colour::LightGrey
15835 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15837 std::string bothOrAll( std::size_t count ) {
15838 return count == 1 ? std::string() :
15839 count == 2 ? "both " : "all " ;
15842 } // anon namespace
15846 // Colour, message variants:
15847 // - white: No tests ran.
15848 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15849 // - white: Passed [both/all] N test cases (no assertions).
15850 // - red: Failed N tests cases, failed M assertions.
15851 // - green: Passed [both/all] N tests cases with M assertions.
15852 void printTotals(std::ostream& out, const Totals& totals) {
15853 if (totals.testCases.total() == 0) {
15854 out << "No tests ran.";
15855 } else if (totals.testCases.failed == totals.testCases.total()) {
15856 Colour colour(Colour::ResultError);
15857 const std::string qualify_assertions_failed =
15858 totals.assertions.failed == totals.assertions.total() ?
15859 bothOrAll(totals.assertions.failed) : std::string();
15861 "Failed " << bothOrAll(totals.testCases.failed)
15862 << pluralise(totals.testCases.failed, "test case") << ", "
15863 "failed " << qualify_assertions_failed <<
15864 pluralise(totals.assertions.failed, "assertion") << '.
';
15865 } else if (totals.assertions.total() == 0) {
15867 "Passed " << bothOrAll(totals.testCases.total())
15868 << pluralise(totals.testCases.total(), "test case")
15869 << " (no assertions).";
15870 } else if (totals.assertions.failed) {
15871 Colour colour(Colour::ResultError);
15873 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15874 "failed " << pluralise(totals.assertions.failed, "assertion") << '.
';
15876 Colour colour(Colour::ResultSuccess);
15878 "Passed " << bothOrAll(totals.testCases.passed)
15879 << pluralise(totals.testCases.passed, "test case") <<
15880 " with " << pluralise(totals.assertions.passed, "assertion") << '.
';
15884 // Implementation of CompactReporter formatting
15885 class AssertionPrinter {
15887 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15888 AssertionPrinter(AssertionPrinter const&) = delete;
15889 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15891 , result(_stats.assertionResult)
15892 , messages(_stats.infoMessages)
15893 , itMessage(_stats.infoMessages.begin())
15894 , printInfoMessages(_printInfoMessages) {}
15899 itMessage = messages.begin();
15901 switch (result.getResultType()) {
15902 case ResultWas::Ok:
15903 printResultType(Colour::ResultSuccess, passedString());
15904 printOriginalExpression();
15905 printReconstructedExpression();
15906 if (!result.hasExpression())
15907 printRemainingMessages(Colour::None);
15909 printRemainingMessages();
15911 case ResultWas::ExpressionFailed:
15913 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15915 printResultType(Colour::Error, failedString());
15916 printOriginalExpression();
15917 printReconstructedExpression();
15918 printRemainingMessages();
15920 case ResultWas::ThrewException:
15921 printResultType(Colour::Error, failedString());
15922 printIssue("unexpected exception with message:");
15924 printExpressionWas();
15925 printRemainingMessages();
15927 case ResultWas::FatalErrorCondition:
15928 printResultType(Colour::Error, failedString());
15929 printIssue("fatal error condition with message:");
15931 printExpressionWas();
15932 printRemainingMessages();
15934 case ResultWas::DidntThrowException:
15935 printResultType(Colour::Error, failedString());
15936 printIssue("expected exception, got none");
15937 printExpressionWas();
15938 printRemainingMessages();
15940 case ResultWas::Info:
15941 printResultType(Colour::None, "info");
15943 printRemainingMessages();
15945 case ResultWas::Warning:
15946 printResultType(Colour::None, "warning");
15948 printRemainingMessages();
15950 case ResultWas::ExplicitFailure:
15951 printResultType(Colour::Error, failedString());
15952 printIssue("explicitly");
15953 printRemainingMessages(Colour::None);
15955 // These cases are here to prevent compiler warnings
15956 case ResultWas::Unknown:
15957 case ResultWas::FailureBit:
15958 case ResultWas::Exception:
15959 printResultType(Colour::Error, "** internal error **");
15965 void printSourceInfo() const {
15966 Colour colourGuard(Colour::FileName);
15967 stream << result.getSourceInfo() << ':
';
15970 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15971 if (!passOrFail.empty()) {
15973 Colour colourGuard(colour);
15974 stream << ' ' << passOrFail;
15980 void printIssue(std::string const& issue) const {
15981 stream << ' ' << issue;
15984 void printExpressionWas() {
15985 if (result.hasExpression()) {
15988 Colour colour(dimColour());
15989 stream << " expression was:";
15991 printOriginalExpression();
15995 void printOriginalExpression() const {
15996 if (result.hasExpression()) {
15997 stream << ' ' << result.getExpression();
16001 void printReconstructedExpression() const {
16002 if (result.hasExpandedExpression()) {
16004 Colour colour(dimColour());
16005 stream << " for: ";
16007 stream << result.getExpandedExpression();
16011 void printMessage() {
16012 if (itMessage != messages.end()) {
16013 stream << " '" << itMessage->message << '\'';
16018 void printRemainingMessages(Colour::Code colour = dimColour()) {
16019 if (itMessage == messages.end())
16022 const auto itEnd = messages.cend();
16023 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16026 Colour colourGuard(colour);
16027 stream << " with
" << pluralise(N, "message
") << ':';
16030 while (itMessage != itEnd) {
16031 // If this assertion is a warning ignore any INFO messages
16032 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16034 if (itMessage != itEnd) {
16035 Colour colourGuard(dimColour());
16045 std::ostream& stream;
16046 AssertionResult const& result;
16047 std::vector<MessageInfo> messages;
16048 std::vector<MessageInfo>::const_iterator itMessage;
16049 bool printInfoMessages;
16052 } // anon namespace
16054 std::string CompactReporter::getDescription() {
16055 return "Reports test results on a single line, suitable
for IDEs
";
16058 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
16059 stream << "No test cases matched
'" << spec << '\
'' << std::endl;
16062 void CompactReporter::assertionStarting( AssertionInfo
const& ) {}
16064 bool CompactReporter::assertionEnded( AssertionStats
const& _assertionStats ) {
16065 AssertionResult
const& result = _assertionStats.assertionResult;
16067 bool printInfoMessages =
true;
16070 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16073 printInfoMessages =
false;
16076 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16079 stream << std::endl;
16083 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
16084 double dur = _sectionStats.durationInSeconds;
16085 if ( shouldShowDuration( *m_config, dur ) ) {
16086 stream << getFormattedDuration( dur ) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16090 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
16091 printTotals( stream, _testRunStats.totals );
16092 stream <<
'\n' << std::endl;
16093 StreamingReporterBase::testRunEnded( _testRunStats );
16096 CompactReporter::~CompactReporter() {}
16098 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
16107 #if defined(_MSC_VER)
16108 #pragma warning(push)
16109 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16113 #if defined(__clang__)
16114 # pragma clang diagnostic push
16116 # pragma clang diagnostic ignored "-Wunused-function"
16124 class ConsoleAssertionPrinter {
16126 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter
const&) =
delete;
16127 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
16128 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
16131 result(_stats.assertionResult),
16132 colour(Colour::None),
16133 message(result.getMessage()),
16134 messages(_stats.infoMessages),
16135 printInfoMessages(_printInfoMessages) {
16136 switch (result.getResultType()) {
16138 colour = Colour::Success;
16139 passOrFail =
"PASSED";
16141 if (_stats.infoMessages.size() == 1)
16142 messageLabel =
"with message";
16143 if (_stats.infoMessages.size() > 1)
16144 messageLabel =
"with messages";
16147 if (result.isOk()) {
16148 colour = Colour::Success;
16149 passOrFail =
"FAILED - but was ok";
16151 colour = Colour::Error;
16152 passOrFail =
"FAILED";
16154 if (_stats.infoMessages.size() == 1)
16155 messageLabel =
"with message";
16156 if (_stats.infoMessages.size() > 1)
16157 messageLabel =
"with messages";
16160 colour = Colour::Error;
16161 passOrFail =
"FAILED";
16162 messageLabel =
"due to unexpected exception with ";
16163 if (_stats.infoMessages.size() == 1)
16164 messageLabel += "message";
16165 if (_stats.infoMessages.size() > 1)
16166 messageLabel += "messages";
16169 colour = Colour::Error;
16170 passOrFail =
"FAILED";
16171 messageLabel =
"due to a fatal error condition";
16174 colour = Colour::Error;
16175 passOrFail =
"FAILED";
16176 messageLabel =
"because no exception was thrown where one was expected";
16179 messageLabel =
"info";
16182 messageLabel =
"warning";
16185 passOrFail =
"FAILED";
16186 colour = Colour::Error;
16187 if (_stats.infoMessages.size() == 1)
16188 messageLabel =
"explicitly with message";
16189 if (_stats.infoMessages.size() > 1)
16190 messageLabel =
"explicitly with messages";
16196 passOrFail =
"** internal error **";
16197 colour = Colour::Error;
16202 void print()
const {
16204 if (stats.totals.assertions.total() > 0) {
16206 printOriginalExpression();
16207 printReconstructedExpression();
16215 void printResultType()
const {
16216 if (!passOrFail.empty()) {
16217 Colour colourGuard(colour);
16218 stream << passOrFail <<
":\n";
16221 void printOriginalExpression()
const {
16222 if (result.hasExpression()) {
16223 Colour colourGuard(Colour::OriginalExpression);
16225 stream << result.getExpressionInMacro();
16229 void printReconstructedExpression()
const {
16230 if (result.hasExpandedExpression()) {
16231 stream <<
"with expansion:\n";
16232 Colour colourGuard(Colour::ReconstructedExpression);
16233 stream << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16236 void printMessage()
const {
16237 if (!messageLabel.empty())
16238 stream << messageLabel <<
':' <<
'\n';
16239 for (
auto const& msg : messages) {
16242 stream << Column(msg.message).indent(2) <<
'\n';
16245 void printSourceInfo()
const {
16246 Colour colourGuard(Colour::FileName);
16247 stream << result.getSourceInfo() <<
": ";
16250 std::ostream& stream;
16251 AssertionStats
const& stats;
16252 AssertionResult
const& result;
16253 Colour::Code colour;
16254 std::string passOrFail;
16255 std::string messageLabel;
16256 std::string message;
16257 std::vector<MessageInfo> messages;
16258 bool printInfoMessages;
16261 std::size_t makeRatio(std::size_t
number, std::size_t total) {
16262 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH *
number / total : 0;
16263 return (ratio == 0 &&
number > 0) ? 1 : ratio;
16266 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16267 if (i > j && i > k)
16275 struct ColumnInfo {
16279 Justification justification;
16281 struct ColumnBreak {};
16282 struct RowBreak {};
16293 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16294 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16295 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16296 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16298 double m_inNanoseconds;
16302 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16303 : m_inNanoseconds(inNanoseconds),
16305 if (m_units == Unit::Auto) {
16306 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16307 m_units = Unit::Nanoseconds;
16308 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16309 m_units = Unit::Microseconds;
16310 else if (m_inNanoseconds < s_nanosecondsInASecond)
16311 m_units = Unit::Milliseconds;
16312 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16313 m_units = Unit::Seconds;
16315 m_units = Unit::Minutes;
16320 auto value() const ->
double {
16322 case Unit::Microseconds:
16323 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16324 case Unit::Milliseconds:
16325 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16326 case Unit::Seconds:
16327 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16328 case Unit::Minutes:
16329 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16331 return m_inNanoseconds;
16334 auto unitsAsString() const ->
std::
string {
16336 case Unit::Nanoseconds:
16338 case Unit::Microseconds:
16340 case Unit::Milliseconds:
16342 case Unit::Seconds:
16344 case Unit::Minutes:
16347 return "** internal error **";
16351 friend auto operator << (std::ostream& os, Duration
const& duration) -> std::ostream& {
16352 return os << duration.value() <<
' ' << duration.unitsAsString();
16357 class TablePrinter {
16358 std::ostream& m_os;
16359 std::vector<ColumnInfo> m_columnInfos;
16360 std::ostringstream m_oss;
16361 int m_currentColumn = -1;
16362 bool m_isOpen =
false;
16365 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16367 m_columnInfos(
std::move( columnInfos ) ) {}
16369 auto columnInfos() const ->
std::vector<ColumnInfo> const& {
16370 return m_columnInfos;
16376 *
this << RowBreak();
16378 Columns headerCols;
16380 for (
auto const& info : m_columnInfos) {
16381 headerCols += Column(info.name).width(static_cast<
std::size_t>(info.width - 2));
16382 headerCols += spacer;
16384 m_os << headerCols <<
'\n';
16386 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16391 *
this << RowBreak();
16397 template<
typename T>
16403 friend TablePrinter&
operator << (TablePrinter& tp, ColumnBreak) {
16404 auto colStr = tp.m_oss.str();
16405 const auto strSize = colStr.size();
16408 if (tp.m_currentColumn ==
static_cast<int>(tp.m_columnInfos.size() - 1)) {
16409 tp.m_currentColumn = -1;
16412 tp.m_currentColumn++;
16414 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16415 auto padding = (strSize + 1 < static_cast<
std::size_t>(colInfo.width))
16416 ? std::string(colInfo.width - (strSize + 1), ' ')
16419 tp.m_os << colStr << padding <<
' ';
16421 tp.m_os << padding << colStr <<
' ';
16425 friend TablePrinter&
operator << (TablePrinter& tp, RowBreak) {
16426 if (tp.m_currentColumn > 0) {
16428 tp.m_currentColumn = -1;
16434 ConsoleReporter::ConsoleReporter(ReporterConfig
const& config)
16435 : StreamingReporterBase(config),
16436 m_tablePrinter(new TablePrinter(config.stream(),
16437 [&config]() ->
std::vector<ColumnInfo> {
16438 if (config.fullConfig()->benchmarkNoAnalysis())
16441 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16450 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16457 ConsoleReporter::~ConsoleReporter() =
default;
16459 std::string ConsoleReporter::getDescription() {
16460 return "Reports test results as plain lines of text";
16463 void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16464 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16467 void ConsoleReporter::reportInvalidArguments(std::string
const&arg){
16468 stream <<
"Invalid Filter: " << arg << std::endl;
16471 void ConsoleReporter::assertionStarting(AssertionInfo
const&) {}
16473 bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16474 AssertionResult
const& result = _assertionStats.assertionResult;
16476 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16484 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16486 stream << std::endl;
16490 void ConsoleReporter::sectionStarting(SectionInfo
const& _sectionInfo) {
16491 m_tablePrinter->close();
16492 m_headerPrinted =
false;
16493 StreamingReporterBase::sectionStarting(_sectionInfo);
16495 void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16496 m_tablePrinter->close();
16497 if (_sectionStats.missingAssertions) {
16499 Colour colour(Colour::ResultError);
16500 if (m_sectionStack.size() > 1)
16501 stream <<
"\nNo assertions in section";
16503 stream <<
"\nNo assertions in test case";
16504 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16506 double dur = _sectionStats.durationInSeconds;
16507 if (shouldShowDuration(*m_config, dur)) {
16508 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16510 if (m_headerPrinted) {
16511 m_headerPrinted =
false;
16513 StreamingReporterBase::sectionEnded(_sectionStats);
16516 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16517 void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16518 lazyPrintWithoutClosingBenchmarkTable();
16520 auto nameCol = Column(name).width(
static_cast<std::size_t
>(m_tablePrinter->columnInfos()[0].width - 2));
16522 bool firstLine =
true;
16523 for (
auto line : nameCol) {
16525 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16529 (*m_tablePrinter) << line << ColumnBreak();
16533 void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16534 (*m_tablePrinter) << info.samples << ColumnBreak()
16535 << info.iterations << ColumnBreak();
16536 if (!m_config->benchmarkNoAnalysis())
16537 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16539 void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16540 if (m_config->benchmarkNoAnalysis())
16542 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16546 (*m_tablePrinter) << ColumnBreak()
16547 << Duration(stats.mean.point.count()) << ColumnBreak()
16548 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16549 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16550 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16551 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16552 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16556 void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16557 Colour colour(Colour::Red);
16559 <<
"Benchmark failed (" << error <<
')'
16560 << ColumnBreak() << RowBreak();
16562 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16564 void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16565 m_tablePrinter->close();
16566 StreamingReporterBase::testCaseEnded(_testCaseStats);
16567 m_headerPrinted =
false;
16569 void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16570 if (currentGroupInfo.used) {
16571 printSummaryDivider();
16572 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16573 printTotals(_testGroupStats.totals);
16574 stream <<
'\n' << std::endl;
16576 StreamingReporterBase::testGroupEnded(_testGroupStats);
16578 void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16579 printTotalsDivider(_testRunStats.totals);
16580 printTotals(_testRunStats.totals);
16581 stream << std::endl;
16582 StreamingReporterBase::testRunEnded(_testRunStats);
16584 void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16585 StreamingReporterBase::testRunStarting(_testInfo);
16586 printTestFilters();
16589 void ConsoleReporter::lazyPrint() {
16591 m_tablePrinter->close();
16592 lazyPrintWithoutClosingBenchmarkTable();
16595 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16597 if (!currentTestRunInfo.used)
16598 lazyPrintRunInfo();
16599 if (!currentGroupInfo.used)
16600 lazyPrintGroupInfo();
16602 if (!m_headerPrinted) {
16603 printTestCaseAndSectionHeader();
16604 m_headerPrinted =
true;
16607 void ConsoleReporter::lazyPrintRunInfo() {
16608 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16609 Colour colour(Colour::SecondaryText);
16610 stream << currentTestRunInfo->name
16611 <<
" is a Catch v" << libraryVersion() <<
" host application.\n"
16612 <<
"Run with -? for options\n\n";
16614 if (m_config->rngSeed() != 0)
16615 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16617 currentTestRunInfo.used =
true;
16619 void ConsoleReporter::lazyPrintGroupInfo() {
16620 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16621 printClosedHeader(
"Group: " + currentGroupInfo->name);
16622 currentGroupInfo.used =
true;
16625 void ConsoleReporter::printTestCaseAndSectionHeader() {
16626 assert(!m_sectionStack.empty());
16627 printOpenHeader(currentTestCaseInfo->name);
16629 if (m_sectionStack.size() > 1) {
16630 Colour colourGuard(Colour::Headers);
16633 it = m_sectionStack.begin() + 1,
16634 itEnd = m_sectionStack.end();
16635 for (; it != itEnd; ++it)
16636 printHeaderString(it->name, 2);
16639 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16641 stream << getLineOfChars<
'-'>() <<
'\n';
16642 Colour colourGuard(Colour::FileName);
16643 stream << lineInfo <<
'\n';
16644 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16647 void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16648 printOpenHeader(_name);
16649 stream << getLineOfChars<
'.'>() <<
'\n';
16651 void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16652 stream << getLineOfChars<
'-'>() <<
'\n';
16654 Colour colourGuard(Colour::Headers);
16655 printHeaderString(_name);
16661 void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16662 std::size_t i = _string.find(
": ");
16663 if (i != std::string::npos)
16667 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16670 struct SummaryColumn {
16672 SummaryColumn( std::string _label, Colour::Code _colour )
16673 : label(
std::move( _label ) ),
16674 colour( _colour ) {}
16675 SummaryColumn addRow( std::size_t count ) {
16676 ReusableStringStream rss;
16678 std::string row = rss.str();
16679 for (
auto& oldRow : rows) {
16680 while (oldRow.size() < row.size())
16681 oldRow =
' ' + oldRow;
16682 while (oldRow.size() > row.size())
16685 rows.push_back(row);
16690 Colour::Code colour;
16691 std::vector<std::string> rows;
16695 void ConsoleReporter::printTotals( Totals
const& totals ) {
16696 if (totals.testCases.total() == 0) {
16697 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16698 }
else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16699 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16701 << pluralise(totals.assertions.passed,
"assertion") <<
" in "
16702 << pluralise(totals.testCases.passed,
"test case") <<
')'
16706 std::vector<SummaryColumn> columns;
16707 columns.push_back(SummaryColumn(
"", Colour::None)
16708 .addRow(totals.testCases.total())
16709 .addRow(totals.assertions.total()));
16710 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16711 .addRow(totals.testCases.passed)
16712 .addRow(totals.assertions.passed));
16713 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16714 .addRow(totals.testCases.failed)
16715 .addRow(totals.assertions.failed));
16716 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16717 .addRow(totals.testCases.failedButOk)
16718 .addRow(totals.assertions.failedButOk));
16720 printSummaryRow(
"test cases", columns, 0);
16721 printSummaryRow(
"assertions", columns, 1);
16724 void ConsoleReporter::printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row) {
16725 for (
auto col : cols) {
16726 std::string
value = col.rows[row];
16727 if (col.label.empty()) {
16728 stream << label <<
": ";
16732 stream << Colour(Colour::Warning) <<
"- none -";
16733 }
else if (
value !=
"0") {
16734 stream << Colour(Colour::LightGrey) <<
" | ";
16735 stream << Colour(col.colour)
16736 <<
value <<
' ' << col.label;
16742 void ConsoleReporter::printTotalsDivider(Totals
const& totals) {
16743 if (totals.testCases.total() > 0) {
16744 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16745 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16746 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16747 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16748 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16749 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16750 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16752 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16753 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16754 if (totals.testCases.allPassed())
16755 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16757 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16759 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16763 void ConsoleReporter::printSummaryDivider() {
16764 stream << getLineOfChars<
'-'>() <<
'\n';
16767 void ConsoleReporter::printTestFilters() {
16768 if (m_config->testSpec().hasFilters()) {
16769 Colour guard(Colour::BrightYellow);
16770 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16774 CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16778 #if defined(_MSC_VER)
16779 #pragma warning(pop)
16782 #if defined(__clang__)
16783 # pragma clang diagnostic pop
16791 #include <algorithm>
16796 std::string getCurrentTimestamp() {
16800 std::time(&rawtime);
16801 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16804 std::tm timeInfo = {};
16805 gmtime_s(&timeInfo, &rawtime);
16808 timeInfo = std::gmtime(&rawtime);
16811 char timeStamp[timeStampSize];
16812 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16815 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16817 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16819 return std::string(timeStamp);
16822 std::string fileNameTag(
const std::vector<std::string> &tags) {
16823 auto it = std::find_if(begin(tags),
16825 [] (std::string
const& tag) {
return tag.front() ==
'#'; });
16826 if (it != tags.end())
16827 return it->substr(1);
16828 return std::string();
16832 JunitReporter::JunitReporter( ReporterConfig
const& _config )
16833 : CumulativeReporterBase( _config ),
16834 xml( _config.stream() )
16836 m_reporterPrefs.shouldRedirectStdOut =
true;
16837 m_reporterPrefs.shouldReportAllAssertions =
true;
16840 JunitReporter::~JunitReporter() {}
16842 std::string JunitReporter::getDescription() {
16843 return "Reports test results in an XML format that looks like Ant's junitreport target";
16846 void JunitReporter::noMatchingTestCases( std::string
const& ) {}
16848 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16849 CumulativeReporterBase::testRunStarting( runInfo );
16850 xml.startElement(
"testsuites" );
16853 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16854 suiteTimer.start();
16855 stdOutForSuite.clear();
16856 stdErrForSuite.clear();
16857 unexpectedExceptions = 0;
16858 CumulativeReporterBase::testGroupStarting( groupInfo );
16861 void JunitReporter::testCaseStarting( TestCaseInfo
const& testCaseInfo ) {
16862 m_okToFail = testCaseInfo.okToFail();
16865 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16867 unexpectedExceptions++;
16868 return CumulativeReporterBase::assertionEnded( assertionStats );
16871 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16872 stdOutForSuite += testCaseStats.stdOut;
16873 stdErrForSuite += testCaseStats.stdErr;
16874 CumulativeReporterBase::testCaseEnded( testCaseStats );
16877 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16878 double suiteTime = suiteTimer.getElapsedSeconds();
16879 CumulativeReporterBase::testGroupEnded( testGroupStats );
16880 writeGroup( *m_testGroups.back(), suiteTime );
16883 void JunitReporter::testRunEndedCumulative() {
16887 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16888 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
16890 TestGroupStats
const& stats = groupNode.value;
16891 xml.writeAttribute(
"name", stats.groupInfo.name );
16892 xml.writeAttribute(
"errors", unexpectedExceptions );
16893 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16894 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16895 xml.writeAttribute(
"hostname",
"tbd" );
16897 xml.writeAttribute(
"time",
"" );
16899 xml.writeAttribute(
"time", suiteTime );
16900 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16903 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16904 auto properties = xml.scopedElement(
"properties");
16905 if (m_config->hasTestFilters()) {
16906 xml.scopedElement(
"property")
16907 .writeAttribute(
"name",
"filters")
16908 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16910 if (m_config->rngSeed() != 0) {
16911 xml.scopedElement(
"property")
16912 .writeAttribute(
"name",
"random-seed")
16913 .writeAttribute(
"value", m_config->rngSeed());
16918 for(
auto const& child : groupNode.children )
16919 writeTestCase( *child );
16921 xml.scopedElement(
"system-out" ).writeText(
trim( stdOutForSuite ), XmlFormatting::Newline );
16922 xml.scopedElement(
"system-err" ).writeText(
trim( stdErrForSuite ), XmlFormatting::Newline );
16925 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16926 TestCaseStats
const& stats = testCaseNode.value;
16930 assert( testCaseNode.children.size() == 1 );
16931 SectionNode
const& rootSection = *testCaseNode.children.front();
16933 std::string className = stats.testInfo.className;
16935 if( className.empty() ) {
16936 className = fileNameTag(stats.testInfo.tags);
16937 if ( className.empty() )
16938 className =
"global";
16941 if ( !m_config->name().empty() )
16942 className = m_config->name() + "." + className;
16944 writeSection( className,
"", rootSection );
16947 void JunitReporter::writeSection( std::string
const& className,
16948 std::string
const& rootName,
16949 SectionNode
const& sectionNode ) {
16950 std::string name =
trim( sectionNode.stats.sectionInfo.name );
16951 if( !rootName.empty() )
16952 name = rootName + '/' + name;
16954 if( !sectionNode.assertions.empty() ||
16955 !sectionNode.stdOut.empty() ||
16956 !sectionNode.stdErr.empty() ) {
16957 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
16958 if( className.empty() ) {
16959 xml.writeAttribute(
"classname", name );
16960 xml.writeAttribute(
"name",
"root" );
16963 xml.writeAttribute(
"classname", className );
16964 xml.writeAttribute(
"name", name );
16971 xml.writeAttribute(
"status",
"run" );
16973 writeAssertions( sectionNode );
16975 if( !sectionNode.stdOut.empty() )
16976 xml.scopedElement(
"system-out" ).writeText(
trim( sectionNode.stdOut ), XmlFormatting::Newline );
16977 if( !sectionNode.stdErr.empty() )
16978 xml.scopedElement(
"system-err" ).writeText(
trim( sectionNode.stdErr ), XmlFormatting::Newline );
16980 for(
auto const& childNode : sectionNode.childSections )
16981 if( className.empty() )
16982 writeSection( name,
"", *childNode );
16984 writeSection( className, name, *childNode );
16987 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
16988 for(
auto const& assertion : sectionNode.assertions )
16989 writeAssertion( assertion );
16992 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
16993 AssertionResult
const& result = stats.assertionResult;
16994 if( !result.isOk() ) {
16995 std::string elementName;
16996 switch( result.getResultType() ) {
16999 elementName =
"error";
17004 elementName =
"failure";
17014 elementName =
"internalError";
17018 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17020 xml.writeAttribute(
"message", result.getExpression() );
17021 xml.writeAttribute(
"type", result.getTestMacroName() );
17023 ReusableStringStream rss;
17024 if (stats.totals.assertions.total() > 0) {
17025 rss <<
"FAILED" <<
":\n";
17026 if (result.hasExpression()) {
17028 rss << result.getExpressionInMacro();
17031 if (result.hasExpandedExpression()) {
17032 rss <<
"with expansion:\n";
17033 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
17039 if( !result.getMessage().empty() )
17040 rss << result.getMessage() <<
'\n';
17041 for(
auto const& msg : stats.infoMessages )
17043 rss << msg.message <<
'\n';
17045 rss <<
"at " << result.getSourceInfo();
17046 xml.writeText( rss.str(), XmlFormatting::Newline );
17050 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
17060 ListeningReporter::ListeningReporter() {
17062 m_preferences.shouldReportAllAssertions =
true;
17065 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17066 m_listeners.push_back( std::move( listener ) );
17069 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17070 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
17071 m_reporter = std::move( reporter );
17072 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17075 ReporterPreferences ListeningReporter::getPreferences()
const {
17076 return m_preferences;
17079 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17080 return std::set<Verbosity>{ };
17083 void ListeningReporter::noMatchingTestCases( std::string
const& spec ) {
17084 for (
auto const& listener : m_listeners ) {
17085 listener->noMatchingTestCases( spec );
17087 m_reporter->noMatchingTestCases( spec );
17090 void ListeningReporter::reportInvalidArguments(std::string
const&arg){
17091 for (
auto const& listener : m_listeners ) {
17092 listener->reportInvalidArguments( arg );
17094 m_reporter->reportInvalidArguments( arg );
17097 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17098 void ListeningReporter::benchmarkPreparing( std::string
const& name ) {
17099 for (
auto const& listener : m_listeners) {
17100 listener->benchmarkPreparing(name);
17102 m_reporter->benchmarkPreparing(name);
17104 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
17105 for (
auto const& listener : m_listeners ) {
17106 listener->benchmarkStarting( benchmarkInfo );
17108 m_reporter->benchmarkStarting( benchmarkInfo );
17110 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
17111 for (
auto const& listener : m_listeners ) {
17112 listener->benchmarkEnded( benchmarkStats );
17114 m_reporter->benchmarkEnded( benchmarkStats );
17117 void ListeningReporter::benchmarkFailed( std::string
const& error ) {
17118 for (
auto const& listener : m_listeners) {
17119 listener->benchmarkFailed(error);
17121 m_reporter->benchmarkFailed(error);
17123 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17125 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
17126 for (
auto const& listener : m_listeners ) {
17127 listener->testRunStarting( testRunInfo );
17129 m_reporter->testRunStarting( testRunInfo );
17132 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17133 for (
auto const& listener : m_listeners ) {
17134 listener->testGroupStarting( groupInfo );
17136 m_reporter->testGroupStarting( groupInfo );
17139 void ListeningReporter::testCaseStarting( TestCaseInfo
const& testInfo ) {
17140 for (
auto const& listener : m_listeners ) {
17141 listener->testCaseStarting( testInfo );
17143 m_reporter->testCaseStarting( testInfo );
17146 void ListeningReporter::sectionStarting( SectionInfo
const& sectionInfo ) {
17147 for (
auto const& listener : m_listeners ) {
17148 listener->sectionStarting( sectionInfo );
17150 m_reporter->sectionStarting( sectionInfo );
17153 void ListeningReporter::assertionStarting( AssertionInfo
const& assertionInfo ) {
17154 for (
auto const& listener : m_listeners ) {
17155 listener->assertionStarting( assertionInfo );
17157 m_reporter->assertionStarting( assertionInfo );
17161 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17162 for(
auto const& listener : m_listeners ) {
17163 static_cast<void>( listener->assertionEnded( assertionStats ) );
17165 return m_reporter->assertionEnded( assertionStats );
17168 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
17169 for (
auto const& listener : m_listeners ) {
17170 listener->sectionEnded( sectionStats );
17172 m_reporter->sectionEnded( sectionStats );
17175 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17176 for (
auto const& listener : m_listeners ) {
17177 listener->testCaseEnded( testCaseStats );
17179 m_reporter->testCaseEnded( testCaseStats );
17182 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17183 for (
auto const& listener : m_listeners ) {
17184 listener->testGroupEnded( testGroupStats );
17186 m_reporter->testGroupEnded( testGroupStats );
17189 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17190 for (
auto const& listener : m_listeners ) {
17191 listener->testRunEnded( testRunStats );
17193 m_reporter->testRunEnded( testRunStats );
17196 void ListeningReporter::skipTest( TestCaseInfo
const& testInfo ) {
17197 for (
auto const& listener : m_listeners ) {
17198 listener->skipTest( testInfo );
17200 m_reporter->skipTest( testInfo );
17203 bool ListeningReporter::isMulti()
const {
17211 #if defined(_MSC_VER)
17212 #pragma warning(push)
17213 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
17219 XmlReporter::XmlReporter( ReporterConfig
const& _config )
17220 : StreamingReporterBase( _config ),
17221 m_xml(_config.stream())
17223 m_reporterPrefs.shouldRedirectStdOut =
true;
17224 m_reporterPrefs.shouldReportAllAssertions =
true;
17227 XmlReporter::~XmlReporter() =
default;
17229 std::string XmlReporter::getDescription() {
17230 return "Reports test results as an XML document";
17233 std::string XmlReporter::getStylesheetRef()
const {
17234 return std::string();
17237 void XmlReporter::writeSourceInfo( SourceLineInfo
const& sourceInfo ) {
17239 .writeAttribute(
"filename", sourceInfo.file )
17240 .writeAttribute(
"line", sourceInfo.line );
17243 void XmlReporter::noMatchingTestCases( std::string
const& s ) {
17244 StreamingReporterBase::noMatchingTestCases( s );
17247 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17248 StreamingReporterBase::testRunStarting( testInfo );
17249 std::string stylesheetRef = getStylesheetRef();
17250 if( !stylesheetRef.empty() )
17251 m_xml.writeStylesheetRef( stylesheetRef );
17252 m_xml.startElement(
"Catch" );
17253 if( !m_config->name().empty() )
17254 m_xml.writeAttribute(
"name", m_config->name() );
17255 if (m_config->testSpec().hasFilters())
17256 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17257 if( m_config->rngSeed() != 0 )
17258 m_xml.scopedElement(
"Randomness" )
17259 .writeAttribute(
"seed", m_config->rngSeed() );
17262 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17263 StreamingReporterBase::testGroupStarting( groupInfo );
17264 m_xml.startElement(
"Group" )
17265 .writeAttribute(
"name", groupInfo.name );
17268 void XmlReporter::testCaseStarting( TestCaseInfo
const& testInfo ) {
17269 StreamingReporterBase::testCaseStarting(testInfo);
17270 m_xml.startElement(
"TestCase" )
17271 .writeAttribute(
"name",
trim( testInfo.name ) )
17272 .writeAttribute(
"description", testInfo.description )
17273 .writeAttribute(
"tags", testInfo.tagsAsString() );
17275 writeSourceInfo( testInfo.lineInfo );
17278 m_testCaseTimer.start();
17279 m_xml.ensureTagClosed();
17282 void XmlReporter::sectionStarting( SectionInfo
const& sectionInfo ) {
17283 StreamingReporterBase::sectionStarting( sectionInfo );
17284 if( m_sectionDepth++ > 0 ) {
17285 m_xml.startElement(
"Section" )
17286 .writeAttribute(
"name",
trim( sectionInfo.name ) );
17287 writeSourceInfo( sectionInfo.lineInfo );
17288 m_xml.ensureTagClosed();
17292 void XmlReporter::assertionStarting( AssertionInfo
const& ) { }
17294 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17296 AssertionResult
const& result = assertionStats.assertionResult;
17298 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17302 for(
auto const& msg : assertionStats.infoMessages ) {
17304 m_xml.scopedElement(
"Info" )
17305 .writeText( msg.message );
17307 m_xml.scopedElement(
"Warning" )
17308 .writeText( msg.message );
17318 if( result.hasExpression() ) {
17319 m_xml.startElement(
"Expression" )
17320 .writeAttribute(
"success", result.succeeded() )
17321 .writeAttribute(
"type", result.getTestMacroName() );
17323 writeSourceInfo( result.getSourceInfo() );
17325 m_xml.scopedElement(
"Original" )
17326 .writeText( result.getExpression() );
17327 m_xml.scopedElement(
"Expanded" )
17328 .writeText( result.getExpandedExpression() );
17332 switch( result.getResultType() ) {
17334 m_xml.startElement(
"Exception" );
17335 writeSourceInfo( result.getSourceInfo() );
17336 m_xml.writeText( result.getMessage() );
17337 m_xml.endElement();
17340 m_xml.startElement(
"FatalErrorCondition" );
17341 writeSourceInfo( result.getSourceInfo() );
17342 m_xml.writeText( result.getMessage() );
17343 m_xml.endElement();
17346 m_xml.scopedElement(
"Info" )
17347 .writeText( result.getMessage() );
17353 m_xml.startElement(
"Failure" );
17354 writeSourceInfo( result.getSourceInfo() );
17355 m_xml.writeText( result.getMessage() );
17356 m_xml.endElement();
17362 if( result.hasExpression() )
17363 m_xml.endElement();
17368 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17369 StreamingReporterBase::sectionEnded( sectionStats );
17370 if( --m_sectionDepth > 0 ) {
17371 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
17372 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17373 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17374 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17377 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17379 m_xml.endElement();
17383 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17384 StreamingReporterBase::testCaseEnded( testCaseStats );
17385 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
17386 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17389 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17391 if( !testCaseStats.stdOut.empty() )
17392 m_xml.scopedElement(
"StdOut" ).writeText(
trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17393 if( !testCaseStats.stdErr.empty() )
17394 m_xml.scopedElement(
"StdErr" ).writeText(
trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17396 m_xml.endElement();
17399 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17400 StreamingReporterBase::testGroupEnded( testGroupStats );
17402 m_xml.scopedElement(
"OverallResults" )
17403 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17404 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17405 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17406 m_xml.scopedElement(
"OverallResultsCases")
17407 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed )
17408 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed )
17409 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk );
17410 m_xml.endElement();
17413 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17414 StreamingReporterBase::testRunEnded( testRunStats );
17415 m_xml.scopedElement(
"OverallResults" )
17416 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17417 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17418 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17419 m_xml.scopedElement(
"OverallResultsCases")
17420 .writeAttribute(
"successes", testRunStats.totals.testCases.passed )
17421 .writeAttribute(
"failures", testRunStats.totals.testCases.failed )
17422 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk );
17423 m_xml.endElement();
17426 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17427 void XmlReporter::benchmarkPreparing(std::string
const& name) {
17428 m_xml.startElement(
"BenchmarkResults")
17429 .writeAttribute(
"name", name);
17432 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &info) {
17433 m_xml.writeAttribute(
"samples", info.samples)
17434 .writeAttribute(
"resamples", info.resamples)
17435 .writeAttribute(
"iterations", info.iterations)
17436 .writeAttribute(
"clockResolution", info.clockResolution)
17437 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17438 .writeComment(
"All values in nano seconds");
17441 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17442 m_xml.startElement(
"mean")
17443 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17444 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17445 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17446 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17447 m_xml.endElement();
17448 m_xml.startElement(
"standardDeviation")
17449 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17450 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17451 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17452 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17453 m_xml.endElement();
17454 m_xml.startElement(
"outliers")
17455 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17456 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17457 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17458 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17459 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17460 m_xml.endElement();
17461 m_xml.endElement();
17464 void XmlReporter::benchmarkFailed(std::string
const &error) {
17465 m_xml.scopedElement(
"failed").
17466 writeAttribute(
"message", error);
17467 m_xml.endElement();
17469 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17471 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17475 #if defined(_MSC_VER)
17476 #pragma warning(pop)
17481 LeakDetector leakDetector;
17485 #pragma clang diagnostic pop
17491 #ifdef CATCH_CONFIG_MAIN
17496 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17498 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17501 int main (
int argc,
char * argv[]) {
17504 return Catch::Session().run( argc, argv );
17510 int main (
int argc,
char *
const argv[]) {
17511 #if !CATCH_ARC_ENABLED
17512 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17515 Catch::registerTestMethods();
17516 int result = Catch::Session().run( argc, (
char**)argv );
17518 #if !CATCH_ARC_ENABLED
17530 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17532 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17533 # undef CLARA_CONFIG_MAIN
17536 #if !defined(CATCH_CONFIG_DISABLE)
17539 #ifdef CATCH_CONFIG_PREFIX_ALL
17541 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17542 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17544 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17545 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17546 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17547 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17548 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17549 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17550 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17552 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17553 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17554 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17555 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17556 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17558 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17559 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17560 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17561 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17562 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17563 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17564 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17566 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17567 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17569 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17570 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17572 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17573 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17574 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17575 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17577 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17578 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17579 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17580 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17581 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17582 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17583 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17584 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17585 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17587 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17589 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17590 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17591 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17592 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17593 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17594 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17595 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17596 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17597 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17599 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17600 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17601 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17602 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17603 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17604 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17605 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17606 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17609 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17610 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
17611 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17613 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
17614 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17618 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17619 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17620 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17621 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17622 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17623 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17624 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17625 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17627 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17628 #define CATCH_BENCHMARK(...) \
17629 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__,,))
17630 #define CATCH_BENCHMARK_ADVANCED(name) \
17631 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17632 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17637 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17638 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17640 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17641 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17642 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17643 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17644 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17645 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17646 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17648 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17649 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17650 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17651 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17652 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17654 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17655 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17656 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17657 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17658 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17659 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17660 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17662 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17663 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17665 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17666 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17668 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17669 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17670 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17671 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17673 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17674 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17675 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17676 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17677 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17678 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17679 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17680 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17681 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17682 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17684 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17685 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17686 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17687 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17688 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17689 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17690 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17691 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17692 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17693 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17694 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17696 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17697 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17698 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17699 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17700 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17701 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17702 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17703 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17704 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17705 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17708 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17709 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17710 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17712 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
17713 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17718 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17721 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17722 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17724 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17725 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17726 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17727 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17728 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17729 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17731 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17732 #define BENCHMARK(...) \
17733 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__,,))
17734 #define BENCHMARK_ADVANCED(name) \
17735 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17736 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17740 #else // CATCH_CONFIG_DISABLE
17744 #ifdef CATCH_CONFIG_PREFIX_ALL
17746 #define CATCH_REQUIRE( ... ) (void)(0)
17747 #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
17749 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17750 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17751 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17752 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17753 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17754 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17755 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17757 #define CATCH_CHECK( ... ) (void)(0)
17758 #define CATCH_CHECK_FALSE( ... ) (void)(0)
17759 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
17760 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17761 #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
17763 #define CATCH_CHECK_THROWS( ... ) (void)(0)
17764 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17765 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17766 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17767 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17768 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17769 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17771 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17772 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
17774 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17775 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17777 #define CATCH_INFO( msg ) (void)(0)
17778 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17779 #define CATCH_WARN( msg ) (void)(0)
17780 #define CATCH_CAPTURE( msg ) (void)(0)
17782 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17783 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17784 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
17785 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17786 #define CATCH_SECTION( ... )
17787 #define CATCH_DYNAMIC_SECTION( ... )
17788 #define CATCH_FAIL( ... ) (void)(0)
17789 #define CATCH_FAIL_CHECK( ... ) (void)(0)
17790 #define CATCH_SUCCEED( ... ) (void)(0)
17792 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17794 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17795 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17796 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17797 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17798 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17799 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17800 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17801 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17802 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17804 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17805 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17806 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17807 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17808 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17809 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17810 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17811 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17815 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17816 #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 )
17817 #define CATCH_GIVEN( desc )
17818 #define CATCH_AND_GIVEN( desc )
17819 #define CATCH_WHEN( desc )
17820 #define CATCH_AND_WHEN( desc )
17821 #define CATCH_THEN( desc )
17822 #define CATCH_AND_THEN( desc )
17824 #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
17825 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17830 #define REQUIRE( ... ) (void)(0)
17831 #define REQUIRE_FALSE( ... ) (void)(0)
17833 #define REQUIRE_THROWS( ... ) (void)(0)
17834 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17835 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17836 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17837 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17838 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17839 #define REQUIRE_NOTHROW( ... ) (void)(0)
17841 #define CHECK( ... ) (void)(0)
17842 #define CHECK_FALSE( ... ) (void)(0)
17843 #define CHECKED_IF( ... ) if (__VA_ARGS__)
17844 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17845 #define CHECK_NOFAIL( ... ) (void)(0)
17847 #define CHECK_THROWS( ... ) (void)(0)
17848 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17849 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17850 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17851 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17852 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17853 #define CHECK_NOTHROW( ... ) (void)(0)
17855 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17856 #define CHECK_THAT( arg, matcher ) (void)(0)
17858 #define REQUIRE_THAT( arg, matcher ) (void)(0)
17859 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17861 #define INFO( msg ) (void)(0)
17862 #define UNSCOPED_INFO( msg ) (void)(0)
17863 #define WARN( msg ) (void)(0)
17864 #define CAPTURE( msg ) (void)(0)
17866 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17867 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17868 #define METHOD_AS_TEST_CASE( method, ... )
17869 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17870 #define SECTION( ... )
17871 #define DYNAMIC_SECTION( ... )
17872 #define FAIL( ... ) (void)(0)
17873 #define FAIL_CHECK( ... ) (void)(0)
17874 #define SUCCEED( ... ) (void)(0)
17875 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17877 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17878 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17879 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17880 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17881 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17882 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17883 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17884 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17885 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17887 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17888 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17889 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17890 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17891 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17892 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17893 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17894 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17897 #define STATIC_REQUIRE( ... ) (void)(0)
17898 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17902 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17905 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
17906 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17908 #define GIVEN( desc )
17909 #define AND_GIVEN( desc )
17910 #define WHEN( desc )
17911 #define AND_WHEN( desc )
17912 #define THEN( desc )
17913 #define AND_THEN( desc )
17919 #endif // ! CATCH_CONFIG_IMPL_ONLY
17925 # ifdef __ICC // icpc defines the __clang__ macro
17926 # pragma warning(pop)
17928 # pragma clang diagnostic pop
17930 #elif defined __GNUC__
17931 # pragma GCC diagnostic pop
17936 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED