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 10
21# pragma clang system_header
23# pragma GCC system_header
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"
42# pragma GCC diagnostic ignored "-Wparentheses"
44# pragma GCC diagnostic push
45# pragma GCC diagnostic ignored "-Wunused-variable"
46# pragma GCC diagnostic ignored "-Wpadded"
49#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
51# define CATCH_CONFIG_ALL_PARTS
56#if defined(CATCH_CONFIG_ALL_PARTS)
57# define CATCH_CONFIG_EXTERNAL_INTERFACES
58# if defined(CATCH_CONFIG_DISABLE_MATCHERS)
59# undef CATCH_CONFIG_DISABLE_MATCHERS
61# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
62# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
66#if !defined(CATCH_CONFIG_IMPL_ONLY)
72# include <TargetConditionals.h>
73# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
74 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
75# define CATCH_PLATFORM_MAC
76# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
77# define CATCH_PLATFORM_IPHONE
80#elif defined(linux) || defined(__linux) || defined(__linux__)
81# define CATCH_PLATFORM_LINUX
83#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
84# define CATCH_PLATFORM_WINDOWS
90# ifndef CLARA_CONFIG_MAIN
91# define CLARA_CONFIG_MAIN_NOT_DEFINED
92# define CLARA_CONFIG_MAIN
99 unsigned int rngSeed();
128# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
129# define CATCH_CPP14_OR_GREATER
132# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
133# define CATCH_CPP17_OR_GREATER
140#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
141# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
142# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
144# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
148#if defined(__clang__)
150# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
151# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
164# if !defined(__ibmxl__) && !defined(__CUDACC__)
165# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
168# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
169 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
170 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
172# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
173 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
175# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
176 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
178# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
179 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
181# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
182 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
188#if !defined(CATCH_PLATFORM_WINDOWS)
189 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
194#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
195 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
199# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
200# define CATCH_CONFIG_COLOUR_NONE
205#if defined(__ANDROID__)
206# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
207# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
212#if defined(__MINGW32__)
213# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
218#if defined(__ORBIS__)
219# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
231# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
232 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
234# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
245# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
246# define CATCH_CONFIG_COLOUR_NONE
248# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
251# if !defined(__clang__)
256# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
257# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
261# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
262# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
267#if defined(_REENTRANT) || defined(_MSC_VER)
269# define CATCH_INTERNAL_CONFIG_USE_ASYNC
274#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
275# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
281# define CATCH_INTERNAL_CONFIG_NO_WCHAR
286#if defined(__BORLANDC__)
287 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
297#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
298 #define CATCH_INTERNAL_CONFIG_COUNTER
306#if defined(UNDER_RTSS) || defined(RTX64_BUILD)
307 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
308 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
309 #define CATCH_CONFIG_COLOUR_NONE
312#if !defined(_GLIBCXX_USE_C99_MATH_TR1)
313#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
317#if defined(__has_include)
319 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
320 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
324 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
325 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
329 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
331 # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
332 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
337 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
338 # if defined(__clang__) && (__clang_major__ < 8)
342 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
343 # define CATCH_CONFIG_NO_CPP17_VARIANT
345 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
348 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
353#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
354# define CATCH_CONFIG_COUNTER
356#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
357# define CATCH_CONFIG_WINDOWS_SEH
360#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
361# define CATCH_CONFIG_POSIX_SIGNALS
364#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
365# define CATCH_CONFIG_WCHAR
368#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
369# define CATCH_CONFIG_CPP11_TO_STRING
372#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
373# define CATCH_CONFIG_CPP17_OPTIONAL
376#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
377# define CATCH_CONFIG_CPP17_STRING_VIEW
380#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
381# define CATCH_CONFIG_CPP17_VARIANT
384#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
385# define CATCH_CONFIG_CPP17_BYTE
388#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
389# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
392#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
393# define CATCH_CONFIG_NEW_CAPTURE
396#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
397# define CATCH_CONFIG_DISABLE_EXCEPTIONS
400#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
401# define CATCH_CONFIG_POLYFILL_ISNAN
404#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
405# define CATCH_CONFIG_USE_ASYNC
408#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
409# define CATCH_CONFIG_ANDROID_LOGWRITE
412#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
413# define CATCH_CONFIG_GLOBAL_NEXTAFTER
418#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
419# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
421#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
422# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
424#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
425# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
427#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
428# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
430#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
431# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
433#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
434# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
439#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
440# define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
443#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
444# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
445#elif defined(__clang__) && (__clang_major__ < 5)
446# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
449#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
450# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
453#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
454#define CATCH_TRY if ((true))
455#define CATCH_CATCH_ALL if ((false))
456#define CATCH_CATCH_ANON(type) if ((false))
459#define CATCH_CATCH_ALL catch (...)
460#define CATCH_CATCH_ANON(type) catch (type)
463#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
464#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
468#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
469#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
470#ifdef CATCH_CONFIG_COUNTER
471# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
473# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
515 bool empty()
const noexcept {
return file[0] ==
'\0'; }
523 std::ostream& operator << ( std::ostream& os,
SourceLineInfo const& info );
535 std::string operator+()
const;
543#define CATCH_INTERNAL_LINEINFO \
544 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
555#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
556 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
557 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
558 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
559 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
573 virtual void invoke ()
const = 0;
582 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
583 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config )
const = 0;
587 bool matchTest(
TestCase const& testCase, TestSpec
const& testSpec,
IConfig const& config );
588 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
IConfig const& config );
589 std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config );
608 using size_type = std::size_t;
609 using const_iterator =
const char*;
612 static constexpr char const*
const s_empty =
"";
614 char const* m_start = s_empty;
615 size_type m_size = 0;
618 constexpr StringRef()
noexcept =
default;
620 StringRef(
char const* rawChars )
noexcept;
622 constexpr StringRef(
char const* rawChars, size_type size ) noexcept
623 : m_start( rawChars ),
627 StringRef( std::string
const& stdString ) noexcept
628 : m_start( stdString.c_str() ),
629 m_size( stdString.size() )
632 explicit operator std::string()
const {
633 return std::string(m_start, m_size);
637 auto operator == (
StringRef const& other )
const noexcept -> bool;
638 auto operator != (
StringRef const& other)
const noexcept ->
bool {
639 return !(*
this == other);
642 auto operator[] ( size_type index )
const noexcept ->
char {
643 assert(index < m_size);
644 return m_start[index];
648 constexpr auto empty()
const noexcept ->
bool {
651 constexpr auto size()
const noexcept -> size_type {
657 auto c_str()
const ->
char const*;
663 auto substr( size_type start, size_type length )
const noexcept ->
StringRef;
666 auto data()
const noexcept ->
char const*;
668 constexpr auto isNullTerminated()
const noexcept ->
bool {
669 return m_start[m_size] ==
'\0';
673 constexpr const_iterator begin()
const {
return m_start; }
674 constexpr const_iterator end()
const {
return m_start + m_size; }
677 auto operator += ( std::string& lhs,
StringRef const& sr ) -> std::string&;
678 auto operator << ( std::ostream& os,
StringRef const& sr ) -> std::ostream&;
680 constexpr auto operator "" _sr(
char const* rawChars, std::size_t size )
noexcept ->
StringRef {
685constexpr auto operator "" _catch_sr(
char const* rawChars, std::size_t size )
noexcept ->
Catch::StringRef {
693#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
694#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
695#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
696#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
697#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
698#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
700#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
701#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
703#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
704#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
706#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
709#define CATCH_REC_END(...)
713#define CATCH_DEFER(id) id CATCH_EMPTY()
715#define CATCH_REC_GET_END2() 0, CATCH_REC_END
716#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
717#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
718#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
719#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
720#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
722#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
723#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
724#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
726#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
727#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
728#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
733#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
735#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
737#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
738#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
739#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
740#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
741#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
742#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
743#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
744#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
747#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
748#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
749#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
752#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
753#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
755#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
757#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
758#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
759#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
761#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
762#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
765#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
766 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
768#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
769#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
770#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
771#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
772#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
773#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
774#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
775#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
776#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
777#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
778#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
780#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
782#define INTERNAL_CATCH_TYPE_GEN\
783 template<typename...> struct TypeList {};\
784 template<typename...Ts>\
785 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
786 template<template<typename...> class...> struct TemplateTypeList{};\
787 template<template<typename...> class...Cs>\
788 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
789 template<typename...>\
791 template<typename...>\
793 template<template<typename...> class, typename...>\
795 template<template<typename...> class, typename>\
798 template<typename T> \
799 struct append<T> { using type = T; };\
800 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
801 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
802 template< template<typename...> class L1, typename...E1, typename...Rest>\
803 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
805 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
806 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
807 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
808 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
810 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
811 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
812 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
813 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
815#define INTERNAL_CATCH_NTTP_1(signature, ...)\
816 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
817 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
818 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
819 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
820 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
821 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
824 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
825 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
826 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
827 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
828 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
830#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
831#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
832 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
833 static void TestName()
834#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
835 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
836 static void TestName()
838#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
839#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
840 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
841 static void TestName()
842#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
843 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
844 static void TestName()
846#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
847 template<typename Type>\
848 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
850 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
853#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
854 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
855 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
857 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
860#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
861 template<typename Type>\
862 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
864 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
867#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
868 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
869 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
871 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
874#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
875#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
876 template<typename TestType> \
877 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
881#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
882 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
883 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
887#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
888#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
889 template<typename TestType> \
890 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
891#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
892 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
893 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
895#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
896#define INTERNAL_CATCH_NTTP_0
897#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
898#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
899#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
900#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
901#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
902#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
903#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
904#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
906#define INTERNAL_CATCH_NTTP_0(signature)
907#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
908#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
909#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
910#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
911#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
912#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
913#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
914#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
921#include <type_traits>
930 template <
typename Fun,
typename... Args>
932 template <
typename...>
933 std::false_type
static test(...);
936 template <
typename T>
939 template <
typename Fun,
typename... Args>
940 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
942#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
945 template <
typename Func,
typename... U>
946 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
949 template <
typename Func,
typename... U>
950 using FunctionReturnType =
typename std::remove_reference<
typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
964 void (
C::*m_testAsMethod)();
968 void invoke()
const override {
970 (obj.*m_testAsMethod)();
974auto makeTestInvoker(
void(*testAsFunction)() ) noexcept ->
ITestInvoker*;
977auto makeTestInvoker(
void (
C::*testAsMethod)() ) noexcept ->
ITestInvoker* {
994#if defined(CATCH_CONFIG_DISABLE)
995 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
996 static void TestName()
997 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
999 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1003 void TestName::test()
1004 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1005 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1006 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1008 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1009 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1012 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1014 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1015 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1016 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__ )
1018 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1019 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__ ) )
1022 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1023 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1024 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__ )
1026 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1027 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__ ) )
1030 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1031 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1032 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__ )
1034 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1035 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__ ) )
1038 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1039 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1040 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__ )
1042 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1043 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__ ) )
1048 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1049 static void TestName(); \
1050 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1051 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1052 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } \
1053 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1054 static void TestName()
1055 #define INTERNAL_CATCH_TESTCASE( ... ) \
1056 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), __VA_ARGS__ )
1059 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1060 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1061 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1062 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); }
\
1063 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1066 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1067 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1068 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1070 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1073 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); \
1075 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1076 void TestName::test()
1077 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1078 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), ClassName, __VA_ARGS__ )
1081 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1082 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1083 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1084 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); \
1085 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1088 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1089 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1090 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1091 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1092 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1093 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1095 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1096 INTERNAL_CATCH_TYPE_GEN\
1097 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1098 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1099 template<typename...Types> \
1103 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1104 using expander = int[];\
1105 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };
\
1108 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1109 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1114 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1115 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1117#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1118 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1119 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__ )
1121 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1122 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__ ) )
1125#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1126 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1127 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__ )
1129 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1130 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__ ) )
1133 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1134 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1135 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1136 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1137 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1138 template<typename TestType> static void TestFuncName(); \
1140 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1141 INTERNAL_CATCH_TYPE_GEN \
1142 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1143 template<typename... Types> \
1145 void reg_tests() { \
1147 using expander = int[]; \
1148 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1149 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1150 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1151 (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++)... };
\
1154 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1155 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; \
1162 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1163 template<typename TestType> \
1164 static void TestFuncName()
1166#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1167 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1168 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__)
1170 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1171 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__ ) )
1174#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1175 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1176 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__)
1178 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1179 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__ ) )
1182 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1183 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1184 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1185 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1186 template<typename TestType> static void TestFunc(); \
1188 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1189 INTERNAL_CATCH_TYPE_GEN\
1190 template<typename... Types> \
1192 void reg_tests() { \
1194 using expander = int[]; \
1195 (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++)... };
\
1198 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1199 using TestInit = typename convert<TestName, TmplList>::type; \
1205 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1206 template<typename TestType> \
1207 static void TestFunc()
1209 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1210 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 )
1212 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1213 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1214 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1215 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1216 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1218 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1219 INTERNAL_CATCH_TYPE_GEN\
1220 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1221 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1222 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1223 template<typename...Types> \
1224 struct TestNameClass{\
1227 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1228 using expander = int[];\
1229 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };
\
1232 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1233 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1238 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1239 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1241#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1242 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1243 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__ )
1245 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1246 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__ ) )
1249#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1250 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1251 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__ )
1253 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1254 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__ ) )
1257 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1258 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1259 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1260 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1261 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1262 template<typename TestType> \
1263 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1267 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1268 INTERNAL_CATCH_TYPE_GEN \
1269 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1270 template<typename...Types>\
1271 struct TestNameClass{\
1274 using expander = int[];\
1275 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1276 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1277 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1278 (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++)... };
\
1281 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1282 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;\
1289 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1290 template<typename TestType> \
1291 void TestName<TestType>::test()
1293#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1294 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1295 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__ )
1297 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1298 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__ ) )
1301#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1302 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1303 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__ )
1305 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1306 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__ ) )
1309 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1310 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1311 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1312 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1313 template<typename TestType> \
1314 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1318 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1319 INTERNAL_CATCH_TYPE_GEN\
1320 template<typename...Types>\
1321 struct TestNameClass{\
1324 using expander = int[];\
1325 (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++)... };
\
1328 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1329 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1335 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1336 template<typename TestType> \
1337 void TestName<TestType>::test()
1339#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1340 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 )
1362 ExpressionFailed = FailureBit | 1,
1363 ExplicitFailure = FailureBit | 2,
1365 Exception = 0x100 | FailureBit,
1367 ThrewException = Exception | 1,
1368 DidntThrowException = Exception | 2,
1370 FatalErrorCondition = 0x200 | FailureBit
1374 bool isOk( ResultWas::OfType resultType );
1375 bool isJustInfo(
int flags );
1381 ContinueOnFailure = 0x02,
1386 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1388 bool shouldContinueOnFailure(
int flags );
1389 inline bool isFalseTest(
int flags ) {
return ( flags & ResultDisposition::FalseTest ) != 0; }
1390 bool shouldSuppressFailure(
int flags );
1402 ResultDisposition::Flags resultDisposition;
1418#include <type_traits>
1428 std::ostream& cout();
1429 std::ostream& cerr();
1430 std::ostream& clog();
1436 virtual std::ostream& stream()
const = 0;
1442 std::size_t m_index;
1443 std::ostream* m_oss;
1448 auto str()
const -> std::string;
1450 template<
typename T>
1455 auto get() -> std::ostream& {
return *m_oss; }
1469 std::vector<std::pair<int, StringRef>> m_values;
1482 template<
typename E>
1484 static_assert(
sizeof(int) >=
sizeof(
E),
"Cannot serialize enum to int");
1485 std::vector<int> intValues;
1486 intValues.reserve( values.size() );
1487 for(
auto enumValue : values )
1488 intValues.push_back(
static_cast<int>( enumValue ) );
1489 return registerEnum( enumName, allEnums, intValues );
1497#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1498#include <string_view>
1504#import <Foundation/Foundation.h>
1507#define CATCH_ARC_ENABLED __has_feature(objc_arc)
1509#define CATCH_ARC_ENABLED 0
1512void arcSafeRelease( NSObject* obj );
1513id performOptionalSelector(
id obj,
SEL sel );
1515#if !CATCH_ARC_ENABLED
1516inline void arcSafeRelease( NSObject* obj ) {
1519inline id performOptionalSelector(
id obj,
SEL sel ) {
1520 if( [obj respondsToSelector: sel] )
1521 return [obj performSelector: sel];
1524#define CATCH_UNSAFE_UNRETAINED
1525#define CATCH_ARC_STRONG
1527inline void arcSafeRelease( NSObject* ){}
1528inline id performOptionalSelector(
id obj,
SEL sel ) {
1530#pragma clang diagnostic push
1531#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1533 if( [obj respondsToSelector: sel] )
1534 return [obj performSelector: sel];
1536#pragma clang diagnostic pop
1540#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1541#define CATCH_ARC_STRONG __strong
1548#pragma warning(push)
1549#pragma warning(disable:4180)
1555 extern const std::string unprintableString;
1557 std::string rawMemoryToString(
const void *
object, std::size_t size );
1559 template<
typename T>
1560 std::string rawMemoryToString(
const T&
object ) {
1561 return rawMemoryToString( &
object,
sizeof(
object) );
1564 template<
typename T>
1566 template<
typename Stream,
typename U>
1567 static auto test(
int)
1568 ->
decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1570 template<
typename,
typename>
1571 static auto test(...)->std::false_type;
1574 static const bool value =
decltype(test<std::ostream, const T&>(0))::value;
1577 template<
typename E>
1578 std::string convertUnknownEnumToString(
E e );
1580 template<
typename T>
1581 typename std::enable_if<
1582 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1583 std::string>::type convertUnstreamable( T
const& ) {
1584 return Detail::unprintableString;
1586 template<
typename T>
1587 typename std::enable_if<
1588 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1589 std::string>::type convertUnstreamable(T
const& ex) {
1593 template<
typename T>
1594 typename std::enable_if<
1595 std::is_enum<T>::value
1596 , std::string>::type convertUnstreamable( T
const& value ) {
1597 return convertUnknownEnumToString( value );
1600#if defined(_MANAGED)
1602 template<
typename T>
1603 std::string clrReferenceToString( T^ ref ) {
1605 return std::string(
"null");
1606 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1607 cli::pin_ptr<System::Byte> p = &bytes[0];
1608 return std::string(
reinterpret_cast<char const *
>(p), bytes->Length);
1615 template <
typename T,
typename =
void>
1617 template <
typename Fake = T>
1619 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1620 convert(
const Fake& value) {
1624 rss.operator<<(value);
1628 template <
typename Fake = T>
1630 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1631 convert(
const Fake& value ) {
1632#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1633 return Detail::convertUnstreamable(value);
1635 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1644 template <
typename T>
1645 std::string stringify(
const T& e) {
1646 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1649 template<
typename E>
1650 std::string convertUnknownEnumToString(
E e ) {
1651 return ::Catch::Detail::stringify(
static_cast<typename std::underlying_type<E>::type
>(e));
1654#if defined(_MANAGED)
1655 template <
typename T>
1656 std::string stringify( T^ e ) {
1657 return ::Catch::StringMaker<T^>::convert(e);
1667 static std::string convert(
const std::string& str);
1670#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1673 static std::string convert(std::string_view str);
1679 static std::string convert(
char const * str);
1683 static std::string convert(
char * str);
1686#ifdef CATCH_CONFIG_WCHAR
1689 static std::string convert(
const std::wstring& wstr);
1692# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1695 static std::string convert(std::wstring_view str);
1701 static std::string convert(
wchar_t const * str);
1705 static std::string convert(
wchar_t * str);
1713 static std::string convert(
char const* str) {
1714 return ::Catch::Detail::stringify(std::string{ str });
1719 static std::string convert(
signed char const* str) {
1720 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const *
>(str) });
1725 static std::string convert(
unsigned char const* str) {
1726 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const *
>(str) });
1730#if defined(CATCH_CONFIG_CPP17_BYTE)
1733 static std::string convert(std::byte value);
1738 static std::string convert(
int value);
1742 static std::string convert(
long value);
1746 static std::string convert(
long long value);
1750 static std::string convert(
unsigned int value);
1754 static std::string convert(
unsigned long value);
1758 static std::string convert(
unsigned long long value);
1763 static std::string convert(
bool b);
1768 static std::string convert(
char c);
1772 static std::string convert(
signed char c);
1776 static std::string convert(
unsigned char c);
1781 static std::string convert(std::nullptr_t);
1786 static std::string convert(
float value);
1787 static int precision;
1792 static std::string convert(
double value);
1793 static int precision;
1796 template <
typename T>
1798 template <
typename U>
1799 static std::string convert(U* p) {
1801 return ::Catch::Detail::rawMemoryToString(p);
1808 template <
typename R,
typename C>
1810 static std::string convert(R
C::* p) {
1812 return ::Catch::Detail::rawMemoryToString(p);
1819#if defined(_MANAGED)
1820 template <
typename T>
1822 static std::string convert( T^ ref ) {
1823 return ::Catch::Detail::clrReferenceToString(ref);
1829 template<
typename InputIterator,
typename Sentinel = InputIterator>
1830 std::string rangeToString(InputIterator first, Sentinel last) {
1831 ReusableStringStream rss;
1833 if (first != last) {
1834 rss << ::Catch::Detail::stringify(*first);
1835 for (++first; first != last; ++first)
1836 rss <<
", " << ::Catch::Detail::stringify(*first);
1845 struct StringMaker<NSString*> {
1846 static std::string convert(NSString * nsstring) {
1849 return std::string(
"@") + [nsstring UTF8String];
1853 struct StringMaker<NSObject*> {
1854 static std::string convert(NSObject* nsObject) {
1855 return ::Catch::Detail::stringify([nsObject description]);
1860 inline std::string stringify( NSString* nsstring ) {
1861 return StringMaker<NSString*>::convert( nsstring );
1873#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1874# define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1875# define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1876# define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1877# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1878# define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1882#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1885 template<
typename T1,
typename T2>
1886 struct StringMaker<std::pair<T1, T2> > {
1887 static std::string convert(
const std::pair<T1, T2>& pair) {
1888 ReusableStringStream rss;
1890 << ::Catch::Detail::stringify(pair.first)
1892 << ::Catch::Detail::stringify(pair.second)
1900#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1903 template<
typename T>
1904 struct StringMaker<std::optional<T> > {
1905 static std::string convert(
const std::optional<T>& optional) {
1906 ReusableStringStream rss;
1907 if (optional.has_value()) {
1908 rss << ::Catch::Detail::stringify(*optional);
1919#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1926 bool = (N < std::tuple_size<Tuple>::value)
1928 struct TupleElementPrinter {
1929 static void print(
const Tuple& tuple, std::ostream& os) {
1930 os << (N ?
", " :
" ")
1931 << ::Catch::Detail::stringify(std::get<N>(tuple));
1932 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1940 struct TupleElementPrinter<Tuple, N, false> {
1941 static void print(
const Tuple&, std::ostream&) {}
1946 template<
typename ...Types>
1947 struct StringMaker<std::tuple<Types...>> {
1948 static std::string convert(
const std::tuple<Types...>& tuple) {
1949 ReusableStringStream rss;
1951 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1959#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1963 struct StringMaker<std::monostate> {
1964 static std::string convert(
const std::monostate&) {
1969 template<
typename... Elements>
1970 struct StringMaker<std::variant<Elements...>> {
1971 static std::string convert(
const std::variant<Elements...>& variant) {
1972 if (variant.valueless_by_exception()) {
1973 return "{valueless variant}";
1976 [](
const auto& value) {
1977 return ::Catch::Detail::stringify(value);
1993 template <
typename...>
1998 template <
typename T,
typename =
void>
2002 template <
typename T>
2007 template <
typename T>
2011#if defined(_MANAGED)
2012 template <
typename T>
2014 static const bool value =
false;
2018 template<
typename Range>
2019 std::string rangeToString( Range
const& range ) {
2020 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2024 template<
typename Allocator>
2025 std::string rangeToString( std::vector<bool, Allocator>
const& v ) {
2026 ReusableStringStream rss;
2034 rss << ::Catch::Detail::stringify( b );
2040 template<
typename R>
2041 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2042 static std::string convert( R
const& range ) {
2043 return rangeToString( range );
2047 template <
typename T,
int SZ>
2049 static std::string convert(T
const(&arr)[SZ]) {
2050 return rangeToString(arr);
2057#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2064template <
class Ratio>
2065struct ratio_string {
2066 static std::string symbol();
2069template <
class Ratio>
2070std::string ratio_string<Ratio>::symbol() {
2072 rss <<
'[' << Ratio::num <<
'/'
2073 << Ratio::den <<
']';
2077struct ratio_string<std::atto> {
2078 static std::string symbol();
2081struct ratio_string<std::femto> {
2082 static std::string symbol();
2085struct ratio_string<std::pico> {
2086 static std::string symbol();
2089struct ratio_string<std::nano> {
2090 static std::string symbol();
2093struct ratio_string<std::micro> {
2094 static std::string symbol();
2097struct ratio_string<std::milli> {
2098 static std::string symbol();
2103 template<
typename Value,
typename Ratio>
2104 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2105 static std::string convert(std::chrono::duration<Value, Ratio>
const& duration) {
2106 ReusableStringStream rss;
2107 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2111 template<
typename Value>
2112 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2113 static std::string convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2114 ReusableStringStream rss;
2115 rss << duration.count() <<
" s";
2119 template<
typename Value>
2120 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2121 static std::string convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2122 ReusableStringStream rss;
2123 rss << duration.count() <<
" m";
2127 template<
typename Value>
2128 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2129 static std::string convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2130 ReusableStringStream rss;
2131 rss << duration.count() <<
" h";
2139 template<
typename Clock,
typename Duration>
2140 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2141 static std::string convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2142 return ::Catch::Detail::stringify(time_point.time_since_epoch()) +
" since epoch";
2146 template<
typename Duration>
2147 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2148 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2149 auto converted = std::chrono::system_clock::to_time_t(time_point);
2152 std::tm timeInfo = {};
2153 gmtime_s(&timeInfo, &converted);
2155 std::tm* timeInfo = std::gmtime(&converted);
2158 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2159 char timeStamp[timeStampSize];
2160 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2163 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2165 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2167 return std::string(timeStamp);
2173#define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2175 template<> struct StringMaker<enumName> { \
2176 static std::string convert( enumName value ) { \
2177 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2178 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2183#define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2193#pragma warning(push)
2194#pragma warning(disable:4389)
2195#pragma warning(disable:4018)
2196#pragma warning(disable:4312)
2197#pragma warning(disable:4180)
2198#pragma warning(disable:4800)
2204 auto isBinaryExpression()
const ->
bool {
return m_isBinaryExpression; }
2205 auto getResult()
const ->
bool {
return m_result; }
2206 virtual void streamReconstructedExpression( std::ostream &os )
const = 0;
2209 : m_isBinaryExpression( isBinaryExpression ),
2217 bool m_isBinaryExpression;
2222 void formatReconstructedExpression( std::ostream &os, std::string
const& lhs,
StringRef op, std::string
const& rhs );
2224 template<
typename LhsT,
typename RhsT>
2230 void streamReconstructedExpression( std::ostream &os )
const override {
2231 formatReconstructedExpression
2232 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2243 template<
typename T>
2246 "chained comparisons are not supported inside assertions, "
2247 "wrap the expression inside parentheses, or decompose it");
2250 template<
typename T>
2253 "chained comparisons are not supported inside assertions, "
2254 "wrap the expression inside parentheses, or decompose it");
2257 template<
typename T>
2260 "chained comparisons are not supported inside assertions, "
2261 "wrap the expression inside parentheses, or decompose it");
2264 template<
typename T>
2267 "chained comparisons are not supported inside assertions, "
2268 "wrap the expression inside parentheses, or decompose it");
2271 template<
typename T>
2274 "chained comparisons are not supported inside assertions, "
2275 "wrap the expression inside parentheses, or decompose it");
2278 template<
typename T>
2281 "chained comparisons are not supported inside assertions, "
2282 "wrap the expression inside parentheses, or decompose it");
2285 template<
typename T>
2288 "chained comparisons are not supported inside assertions, "
2289 "wrap the expression inside parentheses, or decompose it");
2292 template<
typename T>
2295 "chained comparisons are not supported inside assertions, "
2296 "wrap the expression inside parentheses, or decompose it");
2300 template<
typename LhsT>
2304 void streamReconstructedExpression( std::ostream &os )
const override {
2305 os << Catch::Detail::stringify( m_lhs );
2316 template<
typename LhsT,
typename RhsT>
2317 auto compareEqual( LhsT
const& lhs, RhsT
const& rhs ) ->
bool {
return static_cast<bool>(lhs == rhs); }
2318 template<
typename T>
2319 auto compareEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2320 template<
typename T>
2321 auto compareEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs ==
reinterpret_cast<void const*
>( rhs ); }
2322 template<
typename T>
2323 auto compareEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2324 template<
typename T>
2325 auto compareEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) == rhs; }
2327 template<
typename LhsT,
typename RhsT>
2328 auto compareNotEqual( LhsT
const& lhs, RhsT&& rhs ) ->
bool {
return static_cast<bool>(lhs != rhs); }
2329 template<
typename T>
2330 auto compareNotEqual( T*
const& lhs,
int rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2331 template<
typename T>
2332 auto compareNotEqual( T*
const& lhs,
long rhs ) ->
bool {
return lhs !=
reinterpret_cast<void const*
>( rhs ); }
2333 template<
typename T>
2334 auto compareNotEqual(
int lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2335 template<
typename T>
2336 auto compareNotEqual(
long lhs, T*
const& rhs ) ->
bool {
return reinterpret_cast<void const*
>( lhs ) != rhs; }
2338 template<
typename LhsT>
2342 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2344 template<
typename RhsT>
2346 return { compareEqual( m_lhs, rhs ), m_lhs,
"==", rhs };
2349 return { m_lhs == rhs, m_lhs,
"==", rhs };
2352 template<
typename RhsT>
2354 return { compareNotEqual( m_lhs, rhs ), m_lhs,
"!=", rhs };
2357 return { m_lhs != rhs, m_lhs,
"!=", rhs };
2360 template<
typename RhsT>
2362 return {
static_cast<bool>(m_lhs > rhs), m_lhs,
">", rhs };
2364 template<
typename RhsT>
2366 return {
static_cast<bool>(m_lhs < rhs), m_lhs,
"<", rhs };
2368 template<
typename RhsT>
2370 return {
static_cast<bool>(m_lhs >= rhs), m_lhs,
">=", rhs };
2372 template<
typename RhsT>
2374 return {
static_cast<bool>(m_lhs <= rhs), m_lhs,
"<=", rhs };
2376 template <
typename RhsT>
2378 return {
static_cast<bool>(m_lhs | rhs), m_lhs,
"|", rhs };
2380 template <
typename RhsT>
2382 return {
static_cast<bool>(m_lhs & rhs), m_lhs,
"&", rhs };
2384 template <
typename RhsT>
2386 return {
static_cast<bool>(m_lhs ^ rhs), m_lhs,
"^", rhs };
2389 template<
typename RhsT>
2392 "operator&& is not supported inside assertions, "
2393 "wrap the expression inside parentheses, or decompose it");
2396 template<
typename RhsT>
2399 "operator|| is not supported inside assertions, "
2400 "wrap the expression inside parentheses, or decompose it");
2410 template<
typename T>
2411 void handleExpression(
ExprLhs<T> const& expr ) {
2412 handleExpression( expr.makeUnaryExpr() );
2416 template<
typename T>
2440 class AssertionResult;
2441 struct AssertionInfo;
2443 struct SectionEndInfo;
2445 struct MessageBuilder;
2447 struct AssertionReaction;
2448 struct SourceLineInfo;
2450 struct ITransientExpression;
2451 struct IGeneratorTracker;
2453#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2454 struct BenchmarkInfo;
2455 template <
typename Duration = std::chrono::duration<
double, std::nano>>
2456 struct BenchmarkStats;
2463 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
2464 Counts& assertions ) = 0;
2466 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo ) = 0;
2470#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2471 virtual void benchmarkPreparing( std::string
const& name ) = 0;
2472 virtual void benchmarkStarting( BenchmarkInfo
const& info ) = 0;
2473 virtual void benchmarkEnded( BenchmarkStats<>
const& stats ) = 0;
2474 virtual void benchmarkFailed( std::string
const& error ) = 0;
2477 virtual void pushScopedMessage(
MessageInfo const& message ) = 0;
2478 virtual void popScopedMessage(
MessageInfo const& message ) = 0;
2480 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder ) = 0;
2482 virtual void handleFatalErrorCondition(
StringRef message ) = 0;
2484 virtual void handleExpr
2488 virtual void handleMessage
2490 ResultWas::OfType resultType,
2493 virtual void handleUnexpectedExceptionNotThrown
2496 virtual void handleUnexpectedInflightException
2498 std::string
const& message,
2500 virtual void handleIncomplete
2502 virtual void handleNonExpr
2504 ResultWas::OfType resultType,
2507 virtual bool lastAssertionPassed() = 0;
2508 virtual void assertionPassed() = 0;
2511 virtual std::string getCurrentTestName()
const = 0;
2512 virtual const AssertionResult* getLastResult()
const = 0;
2513 virtual void exceptionEarlyReported() = 0;
2523 struct AssertionResultData;
2529 friend struct AssertionStats;
2530 friend class RunContext;
2539 explicit operator bool()
const;
2545 bool shouldDebugBreak =
false;
2546 bool shouldThrow =
false;
2552 bool m_completed =
false;
2560 ResultDisposition::Flags resultDisposition );
2562 if ( !m_completed ) {
2563 m_resultCapture.handleIncomplete( m_assertionInfo );
2567 template<
typename T>
2569 handleExpr( expr.makeUnaryExpr() );
2573 void handleMessage(ResultWas::OfType resultType,
StringRef const& message);
2575 void handleExceptionThrownAsExpected();
2576 void handleUnexpectedExceptionNotThrown();
2577 void handleExceptionNotThrownAsExpected();
2578 void handleThrowingCallSkipped();
2579 void handleUnexpectedInflightException();
2582 void setCompleted();
2585 auto allowThrows()
const -> bool;
2603 ResultWas::OfType _type );
2606 std::string message;
2608 ResultWas::OfType type;
2609 unsigned int sequence;
2611 bool operator == (
MessageInfo const& other )
const;
2612 bool operator < (
MessageInfo const& other )
const;
2614 static unsigned int globalCount;
2619 template<
typename T>
2631 ResultWas::OfType type );
2633 template<
typename T>
2654 std::vector<MessageInfo> m_messages;
2656 size_t m_captured = 0;
2661 void captureValue(
size_t index, std::string
const& value );
2663 template<
typename T>
2664 void captureValues(
size_t index, T
const& value ) {
2665 captureValue( index, Catch::Detail::stringify( value ) );
2668 template<
typename T,
typename... Ts>
2669 void captureValues(
size_t index, T
const& value, Ts
const&... values ) {
2670 captureValue( index, Catch::Detail::stringify(value) );
2671 captureValues( index+1, values... );
2678#if !defined(CATCH_CONFIG_DISABLE)
2680#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2681 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2683 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2686#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2691#define INTERNAL_CATCH_TRY
2692#define INTERNAL_CATCH_CATCH( capturer )
2696#define INTERNAL_CATCH_TRY try
2697#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2701#define INTERNAL_CATCH_REACT( handler ) handler.complete();
2704#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2706 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2707 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2708 INTERNAL_CATCH_TRY { \
2709 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2710 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2711 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2712 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2713 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2714 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2715 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2718#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2719 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2720 if( Catch::getResultCapture().lastAssertionPassed() )
2723#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2724 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2725 if( !Catch::getResultCapture().lastAssertionPassed() )
2728#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2730 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2732 static_cast<void>(__VA_ARGS__); \
2733 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2736 catchAssertionHandler.handleUnexpectedInflightException(); \
2738 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2742#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2744 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2745 if( catchAssertionHandler.allowThrows() ) \
2747 static_cast<void>(__VA_ARGS__); \
2748 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2751 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2754 catchAssertionHandler.handleThrowingCallSkipped(); \
2755 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2759#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2761 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2762 if( catchAssertionHandler.allowThrows() ) \
2764 static_cast<void>(expr); \
2765 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2767 catch( exceptionType const& ) { \
2768 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2771 catchAssertionHandler.handleUnexpectedInflightException(); \
2774 catchAssertionHandler.handleThrowingCallSkipped(); \
2775 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2779#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2781 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2782 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2783 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2787#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2788 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2789 varName.captureValues( 0, __VA_ARGS__ )
2792#define INTERNAL_CATCH_INFO( macroName, log ) \
2793 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2796#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2797 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2801#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2803 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2804 if( catchAssertionHandler.allowThrows() ) \
2806 static_cast<void>(__VA_ARGS__); \
2807 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2810 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2813 catchAssertionHandler.handleThrowingCallSkipped(); \
2814 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2834 std::size_t total()
const;
2835 bool allPassed()
const;
2838 std::size_t passed = 0;
2839 std::size_t failed = 0;
2840 std::size_t failedButOk = 0;
2864 std::string
const& _name );
2869 std::string
const& _name,
2870 std::string
const& ) :
SectionInfo( _lineInfo, _name ) {}
2873 std::string description;
2880 double durationInSeconds;
2892 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2893 auto getEstimatedClockResolution() -> uint64_t;
2896 uint64_t m_nanoseconds = 0;
2899 auto getElapsedNanoseconds()
const -> uint64_t;
2900 auto getElapsedMicroseconds()
const -> uint64_t;
2901 auto getElapsedMilliseconds()
const ->
unsigned int;
2902 auto getElapsedSeconds()
const -> double;
2918 explicit operator bool()
const;
2925 bool m_sectionIncluded;
2931#define INTERNAL_CATCH_SECTION( ... ) \
2932 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2933 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2934 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2935 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2937#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2938 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2939 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2940 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2941 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2954 struct ITestCaseRegistry;
2955 struct IExceptionTranslatorRegistry;
2956 struct IExceptionTranslator;
2957 struct IReporterRegistry;
2958 struct IReporterFactory;
2959 struct ITagAliasRegistry;
2960 struct IMutableEnumValuesRegistry;
2962 class StartupExceptionRegistry;
2964 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2969 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2971 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2974 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
2979 virtual void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory ) = 0;
2980 virtual void registerListener( IReporterFactoryPtr
const& factory ) = 0;
2981 virtual void registerTest(
TestCase const& testInfo ) = 0;
2983 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag,
SourceLineInfo const& lineInfo ) = 0;
2984 virtual void registerStartupException()
noexcept = 0;
2991 std::string translateActiveException();
2996#if defined(CATCH_CONFIG_DISABLE)
2997 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2998 static std::string translatorName( signature )
3006 using exceptionTranslateFunction = std::string(*)();
3008 struct IExceptionTranslator;
3009 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3013 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
3019 virtual std::string translateActiveException()
const = 0;
3023 template<
typename T>
3027 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3028 : m_translateFunction( translateFunction )
3031 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const override {
3032#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3037 std::rethrow_exception(std::current_exception());
3039 return (*it)->translate( it+1, itEnd );
3042 return m_translateFunction( ex );
3048 std::string(*m_translateFunction)( T& );
3052 template<
typename T>
3054 getMutableRegistryHub().registerTranslator
3055 (
new ExceptionTranslator<T>( translateFunction ) );
3061#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3062 static std::string translatorName( signature ); \
3063 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3064 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3065 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3066 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3067 static std::string translatorName( signature )
3069#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3074#include <type_traits>
3081 bool equalityComparisonImpl(
double other)
const;
3084 void setMargin(
double margin);
3087 void setEpsilon(
double epsilon);
3090 explicit Approx (
double value );
3094 Approx operator-()
const;
3096 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3097 Approx operator()( T
const& value )
const {
3098 Approx approx(
static_cast<double>(value) );
3099 approx.m_epsilon = m_epsilon;
3100 approx.m_margin = m_margin;
3101 approx.m_scale = m_scale;
3105 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3106 explicit Approx( T
const& value ):
Approx(
static_cast<double>(value))
3109 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3110 friend bool operator == (
const T& lhs,
Approx const& rhs ) {
3111 auto lhs_v =
static_cast<double>(lhs);
3112 return rhs.equalityComparisonImpl(lhs_v);
3115 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3116 friend bool operator == (
Approx const& lhs,
const T& rhs ) {
3117 return operator==( rhs, lhs );
3120 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3121 friend bool operator != ( T
const& lhs,
Approx const& rhs ) {
3122 return !operator==( lhs, rhs );
3125 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3126 friend bool operator != (
Approx const& lhs, T
const& rhs ) {
3127 return !operator==( rhs, lhs );
3130 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3131 friend bool operator <= ( T
const& lhs,
Approx const& rhs ) {
3132 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3135 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3136 friend bool operator <= (
Approx const& lhs, T
const& rhs ) {
3137 return lhs.m_value <
static_cast<double>(rhs) || lhs == rhs;
3140 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3141 friend bool operator >= ( T
const& lhs,
Approx const& rhs ) {
3142 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3145 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3146 friend bool operator >= (
Approx const& lhs, T
const& rhs ) {
3147 return lhs.m_value >
static_cast<double>(rhs) || lhs == rhs;
3150 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3151 Approx& epsilon( T
const& newEpsilon ) {
3152 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3153 setEpsilon(epsilonAsDouble);
3157 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3158 Approx& margin( T
const& newMargin ) {
3159 double marginAsDouble =
static_cast<double>(newMargin);
3160 setMargin(marginAsDouble);
3164 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3165 Approx& scale( T
const& newScale ) {
3166 m_scale =
static_cast<double>(newScale);
3170 std::string toString()
const;
3201 bool startsWith( std::string
const& s, std::string
const& prefix );
3202 bool startsWith( std::string
const& s,
char prefix );
3203 bool endsWith( std::string
const& s, std::string
const& suffix );
3204 bool endsWith( std::string
const& s,
char suffix );
3205 bool contains( std::string
const& s, std::string
const& infix );
3206 void toLowerInPlace( std::string& s );
3207 std::string toLower( std::string
const& s );
3209 std::string trim( std::string
const& str );
3211 StringRef trim(StringRef ref);
3214 std::vector<StringRef> splitStringRef( StringRef str,
char delimiter );
3215 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
3218 pluralise( std::size_t count, std::string
const& label );
3220 friend std::ostream& operator << ( std::ostream& os,
pluralise const& pluraliser );
3222 std::size_t m_count;
3223 std::string m_label;
3228#ifndef CATCH_CONFIG_DISABLE_MATCHERS
3240 template<
typename ArgT>
struct MatchAllOf;
3241 template<
typename ArgT>
struct MatchAnyOf;
3242 template<
typename ArgT>
struct MatchNotOf;
3249 std::string toString()
const;
3253 virtual std::string describe()
const = 0;
3254 mutable std::string m_cachedToString;
3258# pragma clang diagnostic push
3259# pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3262 template<
typename ObjectT>
3264 virtual bool match( ObjectT
const& arg )
const = 0;
3267#if defined(__OBJC__)
3272 virtual bool match( NSString* arg )
const = 0;
3277# pragma clang diagnostic pop
3280 template<
typename T>
3288 template<
typename ArgT>
3290 bool match( ArgT
const& arg )
const override {
3291 for(
auto matcher : m_matchers ) {
3292 if (!matcher->match(arg))
3297 std::string describe()
const override {
3298 std::string description;
3299 description.reserve( 4 + m_matchers.size()*32 );
3300 description +=
"( ";
3302 for(
auto matcher : m_matchers ) {
3306 description +=
" and ";
3307 description += matcher->toString();
3309 description +=
" )";
3315 copy.m_matchers.push_back( &other );
3319 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3321 template<
typename ArgT>
3324 bool match( ArgT
const& arg )
const override {
3325 for(
auto matcher : m_matchers ) {
3326 if (matcher->match(arg))
3331 std::string describe()
const override {
3332 std::string description;
3333 description.reserve( 4 + m_matchers.size()*32 );
3334 description +=
"( ";
3336 for(
auto matcher : m_matchers ) {
3340 description +=
" or ";
3341 description += matcher->toString();
3343 description +=
" )";
3349 copy.m_matchers.push_back( &other );
3353 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3356 template<
typename ArgT>
3361 bool match( ArgT
const& arg )
const override {
3362 return !m_underlyingMatcher.match( arg );
3365 std::string describe()
const override {
3366 return "not " + m_underlyingMatcher.toString();
3371 template<
typename T>
3375 template<
typename T>
3377 return MatchAnyOf<T>() || *
this || other;
3379 template<
typename T>
3381 return MatchNotOf<T>( *
this );
3388using namespace Matchers;
3389using Matchers::Impl::MatcherBase;
3398namespace Exception {
3401 std::string m_message;
3408 bool match(std::exception
const& ex)
const override;
3410 std::string describe()
const override;
3426 namespace Floating {
3428 enum class FloatingPointKind : uint8_t;
3432 bool match(
double const& matchee)
const override;
3433 std::string describe()
const override;
3441 bool match(
double const& matchee)
const override;
3442 std::string describe()
const override;
3446 FloatingPointKind m_type;
3457 bool match(
double const& matchee)
const override;
3458 std::string describe()
const override;
3484#include <functional>
3492 std::string finalizeDescription(
const std::string& desc);
3495template <
typename T>
3497 std::function<bool(T
const&)> m_predicate;
3498 std::string m_description;
3501 PredicateMatcher(std::function<
bool(T
const&)>
const& elem, std::string
const& descr)
3502 :m_predicate(std::move(elem)),
3503 m_description(Detail::finalizeDescription(descr))
3506 bool match( T
const& item )
const override {
3507 return m_predicate(item);
3510 std::string describe()
const override {
3511 return m_description;
3521 template<
typename T>
3537 namespace StdString {
3541 CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity );
3542 std::string adjustString( std::string
const& str )
const;
3543 std::string caseSensitivitySuffix()
const;
3545 CaseSensitive::Choice m_caseSensitivity;
3551 std::string describe()
const override;
3554 std::string m_operation;
3559 bool match( std::string
const& source )
const override;
3563 bool match( std::string
const& source )
const override;
3567 bool match( std::string
const& source )
const override;
3571 bool match( std::string
const& source )
const override;
3575 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3576 bool match( std::string
const& matchee )
const override;
3577 std::string describe()
const override;
3580 std::string m_regex;
3581 CaseSensitive::Choice m_caseSensitivity;
3589 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3593 StdString::RegexMatcher Matches( std::string
const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3607 template<
typename T,
typename Alloc>
3612 bool match(std::vector<T, Alloc>
const &v)
const override {
3613 for (
auto const& el : v) {
3614 if (el == m_comparator) {
3621 std::string describe()
const override {
3622 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3625 T
const& m_comparator;
3628 template<
typename T,
typename AllocComp,
typename AllocMatch>
3631 ContainsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3633 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3635 if (m_comparator.size() > v.size())
3637 for (
auto const& comparator : m_comparator) {
3638 auto present =
false;
3639 for (
const auto& el : v) {
3640 if (el == comparator) {
3651 std::string describe()
const override {
3652 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3655 std::vector<T, AllocComp>
const& m_comparator;
3658 template<
typename T,
typename AllocComp,
typename AllocMatch>
3661 EqualsMatcher(std::vector<T, AllocComp>
const &comparator) : m_comparator( comparator ) {}
3663 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3668 if (m_comparator.size() != v.size())
3670 for (std::size_t i = 0; i < v.size(); ++i)
3671 if (m_comparator[i] != v[i])
3675 std::string describe()
const override {
3676 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3678 std::vector<T, AllocComp>
const& m_comparator;
3681 template<
typename T,
typename AllocComp,
typename AllocMatch>
3684 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator( comparator ) {}
3686 bool match(std::vector<T, AllocMatch>
const &v)
const override {
3687 if (m_comparator.size() != v.size())
3689 for (std::size_t i = 0; i < v.size(); ++i)
3690 if (m_comparator[i] != approx(v[i]))
3694 std::string describe()
const override {
3695 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3697 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3699 approx.epsilon(newEpsilon);
3702 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3704 approx.margin(newMargin);
3707 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3709 approx.scale(newScale);
3713 std::vector<T, AllocComp>
const& m_comparator;
3717 template<
typename T,
typename AllocComp,
typename AllocMatch>
3720 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3721 if (m_target.size() != vec.size()) {
3724 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3727 std::string describe()
const override {
3728 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3731 std::vector<T, AllocComp>
const& m_target;
3739 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3744 template<
typename T,
typename Alloc = std::allocator<T>>
3749 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3750 Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp>
const& comparator ) {
3751 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
3754 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3755 Vector::ApproxMatcher<T, AllocComp, AllocMatch>
Approx( std::vector<T, AllocComp>
const& comparator ) {
3756 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
3759 template<
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
3760 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp>
const& target) {
3761 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
3770 template<
typename ArgT,
typename MatcherT>
3776 MatchExpr( ArgT
const& arg, MatcherT
const& matcher,
StringRef const& matcherString )
3779 m_matcher( matcher ),
3780 m_matcherString( matcherString )
3783 void streamReconstructedExpression( std::ostream &os )
const override {
3784 auto matcherAsString = m_matcher.toString();
3785 os << Catch::Detail::stringify( m_arg ) <<
' ';
3786 if( matcherAsString == Detail::unprintableString )
3787 os << m_matcherString;
3789 os << matcherAsString;
3797 template<
typename ArgT,
typename MatcherT>
3805#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3807 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3808 INTERNAL_CATCH_TRY { \
3809 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3810 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3811 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3815#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3817 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3818 if( catchAssertionHandler.allowThrows() ) \
3820 static_cast<void>(__VA_ARGS__ ); \
3821 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3823 catch( exceptionType const& ex ) { \
3824 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3827 catchAssertionHandler.handleUnexpectedInflightException(); \
3830 catchAssertionHandler.handleThrowingCallSkipped(); \
3831 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3845 namespace Generators {
3854 virtual bool next() = 0;
3856 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3862 virtual auto hasGenerator()
const ->
bool = 0;
3863 virtual auto getGenerator()
const -> Generators::GeneratorBasePtr
const& = 0;
3864 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3875#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3876 template <
typename Ex>
3878 void throw_exception(Ex
const& e) {
3883 void throw_exception(std::exception
const& e);
3887 void throw_logic_error(std::string
const& msg);
3889 void throw_domain_error(std::string
const& msg);
3891 void throw_runtime_error(std::string
const& msg);
3895#define CATCH_MAKE_MSG(...) \
3896 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3898#define CATCH_INTERNAL_ERROR(...) \
3899 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3901#define CATCH_ERROR(...) \
3902 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3904#define CATCH_RUNTIME_ERROR(...) \
3905 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3907#define CATCH_ENFORCE( condition, ... ) \
3908 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3921 const char*
const m_msg =
"";
3928 const char* what()
const noexcept override final;
3931namespace Generators {
3935 template<
typename T,
typename... Args>
3936 std::unique_ptr<T> make_unique( Args&&... args ) {
3937 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
3941 template<
typename T>
3949 virtual T
const& get()
const = 0;
3953 template<
typename T>
3959 T
const& get()
const override {
3962 bool next()
override {
3967 template<
typename T>
3969 static_assert(!std::is_same<T, bool>::value,
3970 "FixedValuesGenerator does not support bools because of std::vector<bool>"
3971 "specialization, use SingleValue Generator instead.");
3972 std::vector<T> m_values;
3977 T
const& get()
const override {
3978 return m_values[m_idx];
3980 bool next()
override {
3982 return m_idx < m_values.size();
3986 template <
typename T>
3988 std::unique_ptr<IGenerator<T>> m_generator;
3991 m_generator(std::move(generator))
3993 T
const& get()
const {
3994 return m_generator->get();
3997 return m_generator->next();
4001 template <
typename T>
4005 template <
typename T>
4006 GeneratorWrapper<T> values(std::initializer_list<T> values) {
4007 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4010 template<
typename T>
4012 std::vector<GeneratorWrapper<T>> m_generators;
4013 size_t m_current = 0;
4016 m_generators.emplace_back(std::move(generator));
4018 void populate(T&& val) {
4019 m_generators.emplace_back(value(std::forward<T>(val)));
4021 template<
typename U>
4022 void populate(U&& val) {
4023 populate(T(std::forward<U>(val)));
4025 template<
typename U,
typename... Gs>
4026 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4027 populate(std::forward<U>(valueOrGenerator));
4028 populate(std::forward<Gs>(moreGenerators)...);
4032 template <
typename... Gs>
4034 m_generators.reserve(
sizeof...(Gs));
4035 populate(std::forward<Gs>(moreGenerators)...);
4038 T
const& get()
const override {
4039 return m_generators[m_current].get();
4042 bool next()
override {
4043 if (m_current >= m_generators.size()) {
4046 const bool current_status = m_generators[m_current].next();
4047 if (!current_status) {
4050 return m_current < m_generators.size();
4054 template<
typename... Ts>
4055 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples ) {
4056 return values<std::tuple<Ts...>>( tuples );
4060 template <
typename T>
4063 template<
typename T,
typename... Gs>
4065 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4067 template<
typename T>
4068 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4069 return Generators<T>(std::move(generator));
4071 template<
typename T,
typename... Gs>
4072 auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4073 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4075 template<
typename T,
typename U,
typename... Gs>
4076 auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4077 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4080 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker&;
4082 template<
typename L>
4086 auto generate( StringRef generatorName, SourceLineInfo
const& lineInfo, L
const& generatorExpression ) ->
decltype(std::declval<decltype(generatorExpression())>().get()) {
4087 using UnderlyingType =
typename decltype(generatorExpression())::type;
4089 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4090 if (!tracker.hasGenerator()) {
4091 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4094 auto const& generator =
static_cast<IGenerator<UnderlyingType> const&
>( *tracker.getGenerator() );
4095 return generator.get();
4101#define GENERATE( ... ) \
4102 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4103 CATCH_INTERNAL_LINEINFO, \
4104 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4105#define GENERATE_COPY( ... ) \
4106 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4107 CATCH_INTERNAL_LINEINFO, \
4108 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4109#define GENERATE_REF( ... ) \
4110 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4111 CATCH_INTERNAL_LINEINFO, \
4112 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4118namespace Generators {
4120 template <
typename T>
4123 size_t m_returned = 0;
4127 m_generator(std::move(generator)),
4130 assert(target != 0 &&
"Empty generators are not allowed");
4132 T
const& get()
const override {
4133 return m_generator.get();
4135 bool next()
override {
4137 if (m_returned >= m_target) {
4141 const auto success = m_generator.next();
4145 m_returned = m_target;
4151 template <
typename T>
4156 template <
typename T,
typename Predicate>
4159 Predicate m_predicate;
4161 template <
typename P = Predicate>
4163 m_generator(std::move(generator)),
4164 m_predicate(std::forward<P>(pred))
4166 if (!m_predicate(m_generator.get())) {
4169 auto has_initial_value = nextImpl();
4170 if (!has_initial_value) {
4171 Catch::throw_exception(
GeneratorException(
"No valid value found in filtered generator"));
4176 T
const& get()
const override {
4177 return m_generator.get();
4180 bool next()
override {
4186 bool success = m_generator.next();
4190 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) ==
true);
4195 template <
typename T,
typename Predicate>
4200 template <
typename T>
4202 static_assert(!std::is_same<T, bool>::value,
4203 "RepeatGenerator currently does not support bools"
4204 "because of std::vector<bool> specialization");
4206 mutable std::vector<T> m_returned;
4207 size_t m_target_repeats;
4208 size_t m_current_repeat = 0;
4209 size_t m_repeat_index = 0;
4212 m_generator(std::move(generator)),
4213 m_target_repeats(repeats)
4215 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4218 T
const& get()
const override {
4219 if (m_current_repeat == 0) {
4220 m_returned.push_back(m_generator.get());
4221 return m_returned.back();
4223 return m_returned[m_repeat_index];
4226 bool next()
override {
4233 if (m_current_repeat == 0) {
4234 const auto success = m_generator.next();
4238 return m_current_repeat < m_target_repeats;
4243 if (m_repeat_index == m_returned.size()) {
4247 return m_current_repeat < m_target_repeats;
4251 template <
typename T>
4256 template <
typename T,
typename U,
typename Func>
4264 template <
typename F2 = Func>
4266 m_generator(std::move(generator)),
4267 m_function(std::forward<F2>(function)),
4268 m_cache(m_function(m_generator.get()))
4271 T
const& get()
const override {
4274 bool next()
override {
4275 const auto success = m_generator.next();
4277 m_cache = m_function(m_generator.get());
4283 template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4290 template <
typename T,
typename U,
typename Func>
4291 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4292 return GeneratorWrapper<T>(
4293 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4297 template <
typename T>
4299 std::vector<T> m_chunk;
4300 size_t m_chunk_size;
4302 bool m_used_up =
false;
4305 m_chunk_size(size), m_generator(std::move(generator))
4307 m_chunk.reserve(m_chunk_size);
4308 if (m_chunk_size != 0) {
4309 m_chunk.push_back(m_generator.get());
4310 for (
size_t i = 1; i < m_chunk_size; ++i) {
4311 if (!m_generator.next()) {
4312 Catch::throw_exception(
GeneratorException(
"Not enough values to initialize the first chunk"));
4314 m_chunk.push_back(m_generator.get());
4318 std::vector<T>
const& get()
const override {
4321 bool next()
override {
4323 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4324 if (!m_generator.next()) {
4327 m_chunk.push_back(m_generator.get());
4333 template <
typename T>
4336 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4352 struct IResultCapture;
4355 struct IMutableContext;
4357 using IConfigPtr = std::shared_ptr<IConfig const>;
4364 virtual IRunner* getRunner() = 0;
4365 virtual IConfigPtr
const& getConfig()
const = 0;
4371 virtual void setResultCapture(
IResultCapture* resultCapture ) = 0;
4372 virtual void setRunner(
IRunner* runner ) = 0;
4373 virtual void setConfig( IConfigPtr
const& config ) = 0;
4378 friend void cleanUpContext();
4379 static void createContext();
4384 if( !IMutableContext::currentContext )
4385 IMutableContext::createContext();
4387 return *IMutableContext::currentContext;
4390 inline IContext& getCurrentContext()
4392 return getCurrentMutableContext();
4395 void cleanUpContext();
4409 template<
typename T>
4412 Option() : nullableValue(
nullptr ) {}
4413 Option( T
const& _value )
4414 : nullableValue(
new( storage ) T( _value ) )
4417 : nullableValue( _other ?
new( storage ) T( *_other ) :
nullptr )
4425 if( &_other !=
this ) {
4428 nullableValue =
new( storage ) T( *_other );
4432 Option& operator = ( T
const& _value ) {
4434 nullableValue =
new( storage ) T( _value );
4440 nullableValue->~T();
4441 nullableValue =
nullptr;
4444 T& operator*() {
return *nullableValue; }
4445 T
const& operator*()
const {
return *nullableValue; }
4446 T* operator->() {
return nullableValue; }
4447 const T* operator->()
const {
return nullableValue; }
4449 T valueOr( T
const& defaultValue )
const {
4450 return nullableValue ? *nullableValue : defaultValue;
4453 bool some()
const {
return nullableValue !=
nullptr; }
4454 bool none()
const {
return nullableValue ==
nullptr; }
4456 bool operator !()
const {
return nullableValue ==
nullptr; }
4457 explicit operator bool()
const {
4463 alignas(
alignof(T))
char storage[
sizeof(T)];
4477 enum class Verbosity {
4485 NoAssertions = 0x01,
4496 InLexicographicalOrder,
4508 BeforeStartAndExit = BeforeStart | BeforeExit
4517 virtual bool allowThrows()
const = 0;
4518 virtual std::ostream& stream()
const = 0;
4519 virtual std::string name()
const = 0;
4520 virtual bool includeSuccessfulResults()
const = 0;
4521 virtual bool shouldDebugBreak()
const = 0;
4522 virtual bool warnAboutMissingAssertions()
const = 0;
4523 virtual bool warnAboutNoTests()
const = 0;
4524 virtual int abortAfter()
const = 0;
4525 virtual bool showInvisibles()
const = 0;
4526 virtual ShowDurations::OrNot showDurations()
const = 0;
4527 virtual double minDuration()
const = 0;
4528 virtual TestSpec
const& testSpec()
const = 0;
4529 virtual bool hasTestFilters()
const = 0;
4530 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4531 virtual RunTests::InWhatOrder runOrder()
const = 0;
4532 virtual unsigned int rngSeed()
const = 0;
4533 virtual UseColour::YesOrNo useColour()
const = 0;
4534 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4535 virtual Verbosity verbosity()
const = 0;
4537 virtual bool benchmarkNoAnalysis()
const = 0;
4538 virtual int benchmarkSamples()
const = 0;
4539 virtual double benchmarkConfidenceInterval()
const = 0;
4540 virtual unsigned int benchmarkResamples()
const = 0;
4541 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4544 using IConfigPtr = std::shared_ptr<IConfig const>;
4560 using state_type = std::uint64_t;
4562 using result_type = std::uint32_t;
4563 static constexpr result_type (min)() {
4566 static constexpr result_type (max)() {
4567 return static_cast<result_type
>(-1);
4575 void seed(result_type seed_);
4576 void discard(uint64_t skip);
4578 result_type operator()();
4587 std::uint64_t m_state;
4592 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4601namespace Generators {
4603template <
typename Float>
4606 std::uniform_real_distribution<Float> m_dist;
4607 Float m_current_number;
4613 static_cast<void>(next());
4616 Float
const& get()
const override {
4617 return m_current_number;
4619 bool next()
override {
4620 m_current_number = m_dist(m_rng);
4625template <
typename Integer>
4628 std::uniform_int_distribution<Integer> m_dist;
4629 Integer m_current_number;
4635 static_cast<void>(next());
4638 Integer
const& get()
const override {
4639 return m_current_number;
4641 bool next()
override {
4642 m_current_number = m_dist(m_rng);
4649template <
typename T>
4650typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4658template <
typename T>
4659typename std::enable_if<std::is_floating_point<T>::value,
4660GeneratorWrapper<T>>::type
4662 return GeneratorWrapper<T>(
4663 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4667template <
typename T>
4679 m_positive(m_step > T(0))
4681 assert(m_current != m_end &&
"Range start and end cannot be equal");
4682 assert(m_step != T(0) &&
"Step size cannot be zero");
4683 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
"Step moves away from end");
4690 T
const& get()
const override {
4694 bool next()
override {
4695 m_current += m_step;
4696 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4700template <
typename T>
4702 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
"Type must be numeric");
4706template <
typename T>
4707GeneratorWrapper<T> range(T
const& start, T
const& end) {
4708 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
"Type must be an integer");
4709 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4712template <
typename T>
4714 static_assert(!std::is_same<T, bool>::value,
4715 "IteratorGenerator currently does not support bools"
4716 "because of std::vector<bool> specialization");
4718 std::vector<T> m_elems;
4719 size_t m_current = 0;
4721 template <
typename InputIterator,
typename InputSentinel>
4722 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4723 if (m_elems.empty()) {
4724 Catch::throw_exception(
GeneratorException(
"IteratorGenerator received no valid values"));
4728 T
const& get()
const override {
4729 return m_elems[m_current];
4732 bool next()
override {
4734 return m_current != m_elems.size();
4738template <
typename InputIterator,
4739 typename InputSentinel,
4740 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4745template <
typename Container,
4746 typename ResultType =
typename Container::value_type>
4747GeneratorWrapper<ResultType> from_range(Container
const& cnt) {
4748 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4765#pragma clang diagnostic push
4766#pragma clang diagnostic ignored "-Wpadded"
4771 struct ITestInvoker;
4774 enum SpecialProperties{
4777 ShouldFail = 1 << 2,
4780 NonPortable = 1 << 5,
4785 std::string
const& _className,
4786 std::string
const& _description,
4787 std::vector<std::string>
const& _tags,
4790 friend void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4792 bool isHidden()
const;
4793 bool throws()
const;
4794 bool okToFail()
const;
4795 bool expectedToFail()
const;
4797 std::string tagsAsString()
const;
4800 std::string className;
4801 std::string description;
4802 std::vector<std::string> tags;
4803 std::vector<std::string> lcaseTags;
4805 SpecialProperties properties;
4813 TestCase withName( std::string
const& _newName )
const;
4815 void invoke()
const;
4819 bool operator == (
TestCase const& other )
const;
4820 bool operator < (
TestCase const& other )
const;
4823 std::shared_ptr<ITestInvoker> test;
4827 std::string
const& className,
4833#pragma clang diagnostic pop
4843 virtual bool aborting()
const = 0;
4852#import <objc/runtime.h>
4874 class OcMethod :
public ITestInvoker {
4877 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4879 virtual void invoke()
const {
4880 id obj = [[m_cls alloc] init];
4882 performOptionalSelector( obj,
@selector(setUp) );
4883 performOptionalSelector( obj, m_sel );
4884 performOptionalSelector( obj,
@selector(tearDown) );
4886 arcSafeRelease( obj );
4889 virtual ~OcMethod() {}
4897 inline std::string getAnnotation( Class cls,
4898 std::string
const& annotationName,
4899 std::string
const& testCaseName ) {
4900 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4901 SEL sel = NSSelectorFromString( selStr );
4902 arcSafeRelease( selStr );
4903 id value = performOptionalSelector( cls, sel );
4905 return [(NSString*)value UTF8String];
4910 inline std::size_t registerTestMethods() {
4911 std::size_t noTestMethods = 0;
4912 int noClasses = objc_getClassList(
nullptr, 0 );
4914 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
4915 objc_getClassList( classes, noClasses );
4917 for(
int c = 0; c < noClasses; c++ ) {
4918 Class cls = classes[c];
4921 Method* methods = class_copyMethodList( cls, &count );
4922 for( u_int m = 0; m <
count ; m++ ) {
4923 SEL selector = method_getName(methods[m]);
4924 std::string methodName = sel_getName(selector);
4925 if( startsWith( methodName,
"Catch_TestCase_" ) ) {
4926 std::string testCaseName = methodName.substr( 15 );
4927 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
4928 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
4929 const char* className = class_getName( cls );
4931 getMutableRegistryHub().registerTest( makeTestCase(
new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo(
"",0) ) );
4938 return noTestMethods;
4941#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4943 namespace Matchers {
4945 namespace NSStringMatchers {
4947 struct StringHolder : MatcherBase<NSString*>{
4948 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4949 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
4951 arcSafeRelease( m_substr );
4954 bool match( NSString* str )
const override {
4958 NSString* CATCH_ARC_STRONG m_substr;
4961 struct Equals : StringHolder {
4962 Equals( NSString* substr ) : StringHolder( substr ){}
4964 bool match( NSString* str )
const override {
4965 return (str != nil || m_substr == nil ) &&
4966 [str isEqualToString:m_substr];
4969 std::string describe()
const override {
4970 return "equals string: " + Catch::Detail::stringify( m_substr );
4974 struct Contains : StringHolder {
4975 Contains( NSString* substr ) : StringHolder( substr ){}
4977 bool match( NSString* str )
const override {
4978 return (str != nil || m_substr == nil ) &&
4979 [str rangeOfString:m_substr].location != NSNotFound;
4982 std::string describe()
const override {
4983 return "contains string: " + Catch::Detail::stringify( m_substr );
4987 struct StartsWith : StringHolder {
4988 StartsWith( NSString* substr ) : StringHolder( substr ){}
4990 bool match( NSString* str )
const override {
4991 return (str != nil || m_substr == nil ) &&
4992 [str rangeOfString:m_substr].location == 0;
4995 std::string describe()
const override {
4996 return "starts with: " + Catch::Detail::stringify( m_substr );
4999 struct EndsWith : StringHolder {
5000 EndsWith( NSString* substr ) : StringHolder( substr ){}
5002 bool match( NSString* str )
const override {
5003 return (str != nil || m_substr == nil ) &&
5004 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5007 std::string describe()
const override {
5008 return "ends with: " + Catch::Detail::stringify( m_substr );
5015 inline Impl::NSStringMatchers::Equals
5016 Equals( NSString* substr ){
return Impl::NSStringMatchers::Equals( substr ); }
5018 inline Impl::NSStringMatchers::Contains
5019 Contains( NSString* substr ){
return Impl::NSStringMatchers::Contains( substr ); }
5021 inline Impl::NSStringMatchers::StartsWith
5022 StartsWith( NSString* substr ){
return Impl::NSStringMatchers::StartsWith( substr ); }
5024 inline Impl::NSStringMatchers::EndsWith
5025 EndsWith( NSString* substr ){
return Impl::NSStringMatchers::EndsWith( substr ); }
5029 using namespace Matchers;
5036#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5037#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5038+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5042+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5046-(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5048#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5054#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5066#pragma clang diagnostic push
5067#pragma clang diagnostic ignored "-Wpadded"
5073#pragma clang diagnostic push
5074#pragma clang diagnostic ignored "-Wpadded"
5081 class WildcardPattern {
5082 enum WildcardPosition {
5084 WildcardAtStart = 1,
5086 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5091 WildcardPattern( std::string
const& pattern, CaseSensitive::Choice caseSensitivity );
5092 virtual ~WildcardPattern() =
default;
5093 virtual bool matches( std::string
const& str )
const;
5096 std::string normaliseString( std::string
const& str )
const;
5097 CaseSensitive::Choice m_caseSensitivity;
5098 WildcardPosition m_wildcard = NoWildcard;
5099 std::string m_pattern;
5115 explicit Pattern( std::string
const& name );
5117 virtual bool matches( TestCaseInfo
const& testCase )
const = 0;
5118 std::string
const& name()
const;
5120 std::string
const m_name;
5122 using PatternPtr = std::shared_ptr<Pattern>;
5124 class NamePattern :
public Pattern {
5126 explicit NamePattern( std::string
const& name, std::string
const& filterString );
5127 bool matches( TestCaseInfo
const& testCase )
const override;
5129 WildcardPattern m_wildcardPattern;
5132 class TagPattern :
public Pattern {
5134 explicit TagPattern( std::string
const& tag, std::string
const& filterString );
5135 bool matches( TestCaseInfo
const& testCase )
const override;
5140 class ExcludedPattern :
public Pattern {
5142 explicit ExcludedPattern( PatternPtr
const& underlyingPattern );
5143 bool matches( TestCaseInfo
const& testCase )
const override;
5145 PatternPtr m_underlyingPattern;
5149 std::vector<PatternPtr> m_patterns;
5151 bool matches( TestCaseInfo
const& testCase )
const;
5152 std::string name()
const;
5156 struct FilterMatch {
5158 std::vector<TestCase const*> tests;
5160 using Matches = std::vector<FilterMatch>;
5161 using vectorStrings = std::vector<std::string>;
5163 bool hasFilters()
const;
5164 bool matches( TestCaseInfo
const& testCase )
const;
5165 Matches matchesByFilter( std::vector<TestCase>
const& testCases, IConfig
const& config )
const;
5166 const vectorStrings & getInvalidArgs()
const;
5169 std::vector<Filter> m_filters;
5170 std::vector<std::string> m_invalidArgs;
5171 friend class TestSpecParser;
5176#pragma clang diagnostic pop
5188 struct ITagAliasRegistry {
5189 virtual ~ITagAliasRegistry();
5191 virtual TagAlias
const* find( std::string
const& alias )
const = 0;
5192 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
5194 static ITagAliasRegistry
const& get();
5202 class TestSpecParser {
5203 enum Mode{ None, Name, QuotedName,
Tag, EscapedName };
5205 Mode lastMode = None;
5206 bool m_exclusion =
false;
5207 std::size_t m_pos = 0;
5208 std::size_t m_realPatternPos = 0;
5210 std::string m_substring;
5211 std::string m_patternName;
5212 std::vector<std::size_t> m_escapeChars;
5213 TestSpec::Filter m_currentFilter;
5214 TestSpec m_testSpec;
5215 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5218 TestSpecParser( ITagAliasRegistry
const& tagAliases );
5220 TestSpecParser& parse( std::string
const& arg );
5221 TestSpec testSpec();
5224 bool visitChar(
char c );
5225 void startNewMode( Mode mode );
5226 bool processNoneChar(
char c );
5227 void processNameChar(
char c );
5228 bool processOtherChar(
char c );
5231 bool isControlChar(
char c )
const;
5232 void saveLastMode();
5233 void revertBackToLastMode();
5238 std::string preprocessPattern();
5240 void addNamePattern();
5242 void addTagPattern();
5244 inline void addCharToPattern(
char c) {
5251 TestSpec parseTestSpec( std::string
const& arg );
5256#pragma clang diagnostic pop
5266#ifndef CATCH_CONFIG_CONSOLE_WIDTH
5267#define CATCH_CONFIG_CONSOLE_WIDTH 80
5275 bool listTests =
false;
5276 bool listTags =
false;
5277 bool listReporters =
false;
5278 bool listTestNamesOnly =
false;
5280 bool showSuccessfulTests =
false;
5281 bool shouldDebugBreak =
false;
5282 bool noThrow =
false;
5283 bool showHelp =
false;
5284 bool showInvisibles =
false;
5285 bool filenamesAsTags =
false;
5286 bool libIdentify =
false;
5288 int abortAfter = -1;
5289 unsigned int rngSeed = 0;
5291 bool benchmarkNoAnalysis =
false;
5292 unsigned int benchmarkSamples = 100;
5293 double benchmarkConfidenceInterval = 0.95;
5294 unsigned int benchmarkResamples = 100000;
5295 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5297 Verbosity verbosity = Verbosity::Normal;
5298 WarnAbout::What warnings = WarnAbout::Nothing;
5299 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5300 double minDuration = -1;
5301 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5302 UseColour::YesOrNo useColour = UseColour::Auto;
5303 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5305 std::string outputFilename;
5307 std::string processName;
5308#ifndef CATCH_CONFIG_DEFAULT_REPORTER
5309#define CATCH_CONFIG_DEFAULT_REPORTER "console"
5311 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5312#undef CATCH_CONFIG_DEFAULT_REPORTER
5314 std::vector<std::string> testsOrTags;
5315 std::vector<std::string> sectionsToRun;
5318 class Config :
public IConfig {
5322 Config( ConfigData
const& data );
5323 virtual ~Config() =
default;
5325 std::string
const& getFilename()
const;
5327 bool listTests()
const;
5328 bool listTestNamesOnly()
const;
5329 bool listTags()
const;
5330 bool listReporters()
const;
5332 std::string getProcessName()
const;
5333 std::string
const& getReporterName()
const;
5335 std::vector<std::string>
const& getTestsOrTags()
const override;
5336 std::vector<std::string>
const& getSectionsToRun()
const override;
5338 TestSpec
const& testSpec()
const override;
5339 bool hasTestFilters()
const override;
5341 bool showHelp()
const;
5344 bool allowThrows()
const override;
5345 std::ostream& stream()
const override;
5346 std::string name()
const override;
5347 bool includeSuccessfulResults()
const override;
5348 bool warnAboutMissingAssertions()
const override;
5349 bool warnAboutNoTests()
const override;
5350 ShowDurations::OrNot showDurations()
const override;
5351 double minDuration()
const override;
5352 RunTests::InWhatOrder runOrder()
const override;
5353 unsigned int rngSeed()
const override;
5354 UseColour::YesOrNo useColour()
const override;
5355 bool shouldDebugBreak()
const override;
5356 int abortAfter()
const override;
5357 bool showInvisibles()
const override;
5358 Verbosity verbosity()
const override;
5359 bool benchmarkNoAnalysis()
const override;
5360 int benchmarkSamples()
const override;
5361 double benchmarkConfidenceInterval()
const override;
5362 unsigned int benchmarkResamples()
const override;
5363 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5367 IStream
const* openStream();
5370 std::unique_ptr<IStream const> m_stream;
5371 TestSpec m_testSpec;
5372 bool m_hasTestFilters =
false;
5384 struct AssertionResultData
5386 AssertionResultData() =
delete;
5388 AssertionResultData( ResultWas::OfType _resultType, LazyExpression
const& _lazyExpression );
5390 std::string message;
5391 mutable std::string reconstructedExpression;
5392 LazyExpression lazyExpression;
5393 ResultWas::OfType resultType;
5395 std::string reconstructExpression()
const;
5398 class AssertionResult {
5400 AssertionResult() =
delete;
5401 AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data );
5404 bool succeeded()
const;
5405 ResultWas::OfType getResultType()
const;
5406 bool hasExpression()
const;
5407 bool hasMessage()
const;
5408 std::string getExpression()
const;
5409 std::string getExpressionInMacro()
const;
5410 bool hasExpandedExpression()
const;
5411 std::string getExpandedExpression()
const;
5412 std::string getMessage()
const;
5413 SourceLineInfo getSourceInfo()
const;
5414 StringRef getTestMacroName()
const;
5417 AssertionInfo m_info;
5418 AssertionResultData m_resultData;
5424#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5431 namespace Benchmark {
5432 template <
typename Duration>
5435 Duration lower_bound;
5436 Duration upper_bound;
5437 double confidence_interval;
5439 template <
typename Duration2>
5440 operator Estimate<Duration2>()
const {
5441 return { point, lower_bound, upper_bound, confidence_interval };
5453 namespace Benchmark {
5454 struct OutlierClassification {
5455 int samples_seen = 0;
5459 int high_severe = 0;
5462 return low_severe + low_mild + high_mild + high_severe;
5482 struct ReporterConfig {
5483 explicit ReporterConfig( IConfigPtr
const& _fullConfig );
5485 ReporterConfig( IConfigPtr
const& _fullConfig, std::ostream& _stream );
5487 std::ostream& stream()
const;
5488 IConfigPtr fullConfig()
const;
5491 std::ostream* m_stream;
5492 IConfigPtr m_fullConfig;
5495 struct ReporterPreferences {
5496 bool shouldRedirectStdOut =
false;
5497 bool shouldReportAllAssertions =
false;
5500 template<
typename T>
5501 struct LazyStat : Option<T> {
5502 LazyStat& operator=( T
const& _value ) {
5503 Option<T>::operator=( _value );
5514 struct TestRunInfo {
5515 TestRunInfo( std::string
const& _name );
5519 GroupInfo( std::string
const& _name,
5520 std::size_t _groupIndex,
5521 std::size_t _groupsCount );
5524 std::size_t groupIndex;
5525 std::size_t groupsCounts;
5528 struct AssertionStats {
5529 AssertionStats( AssertionResult
const& _assertionResult,
5530 std::vector<MessageInfo>
const& _infoMessages,
5531 Totals
const& _totals );
5533 AssertionStats( AssertionStats
const& ) =
default;
5534 AssertionStats( AssertionStats && ) =
default;
5535 AssertionStats& operator = ( AssertionStats
const& ) =
delete;
5536 AssertionStats& operator = ( AssertionStats && ) =
delete;
5537 virtual ~AssertionStats();
5539 AssertionResult assertionResult;
5540 std::vector<MessageInfo> infoMessages;
5544 struct SectionStats {
5545 SectionStats( SectionInfo
const& _sectionInfo,
5546 Counts
const& _assertions,
5547 double _durationInSeconds,
5548 bool _missingAssertions );
5549 SectionStats( SectionStats
const& ) =
default;
5550 SectionStats( SectionStats && ) =
default;
5551 SectionStats& operator = ( SectionStats
const& ) =
default;
5552 SectionStats& operator = ( SectionStats && ) =
default;
5553 virtual ~SectionStats();
5555 SectionInfo sectionInfo;
5557 double durationInSeconds;
5558 bool missingAssertions;
5561 struct TestCaseStats {
5562 TestCaseStats( TestCaseInfo
const& _testInfo,
5563 Totals
const& _totals,
5564 std::string
const& _stdOut,
5565 std::string
const& _stdErr,
5568 TestCaseStats( TestCaseStats
const& ) =
default;
5569 TestCaseStats( TestCaseStats && ) =
default;
5570 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5571 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5572 virtual ~TestCaseStats();
5574 TestCaseInfo testInfo;
5581 struct TestGroupStats {
5582 TestGroupStats( GroupInfo
const& _groupInfo,
5583 Totals
const& _totals,
5585 TestGroupStats( GroupInfo
const& _groupInfo );
5587 TestGroupStats( TestGroupStats
const& ) =
default;
5588 TestGroupStats( TestGroupStats && ) =
default;
5589 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5590 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5591 virtual ~TestGroupStats();
5593 GroupInfo groupInfo;
5598 struct TestRunStats {
5599 TestRunStats( TestRunInfo
const& _runInfo,
5600 Totals
const& _totals,
5603 TestRunStats( TestRunStats
const& ) =
default;
5604 TestRunStats( TestRunStats && ) =
default;
5605 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5606 TestRunStats& operator = ( TestRunStats && ) =
default;
5607 virtual ~TestRunStats();
5609 TestRunInfo runInfo;
5614#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5615 struct BenchmarkInfo {
5617 double estimatedDuration;
5620 unsigned int resamples;
5621 double clockResolution;
5625 template <
class Duration>
5626 struct BenchmarkStats {
5629 std::vector<Duration> samples;
5630 Benchmark::Estimate<Duration> mean;
5631 Benchmark::Estimate<Duration> standardDeviation;
5632 Benchmark::OutlierClassification outliers;
5633 double outlierVariance;
5635 template <
typename Duration2>
5636 operator BenchmarkStats<Duration2>()
const {
5637 std::vector<Duration2> samples2;
5638 samples2.reserve(samples.size());
5639 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5642 std::move(samples2),
5652 struct IStreamingReporter {
5653 virtual ~IStreamingReporter() =
default;
5659 virtual ReporterPreferences getPreferences()
const = 0;
5661 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5663 virtual void reportInvalidArguments(std::string
const&) {}
5665 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5666 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5668 virtual void testCaseStarting( TestCaseInfo
const& testInfo ) = 0;
5669 virtual void sectionStarting( SectionInfo
const& sectionInfo ) = 0;
5671#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5672 virtual void benchmarkPreparing( std::string
const& ) {}
5673 virtual void benchmarkStarting( BenchmarkInfo
const& ) {}
5674 virtual void benchmarkEnded( BenchmarkStats<>
const& ) {}
5675 virtual void benchmarkFailed( std::string
const& ) {}
5678 virtual void assertionStarting( AssertionInfo
const& assertionInfo ) = 0;
5681 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5683 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5684 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5685 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5686 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5688 virtual void skipTest( TestCaseInfo
const& testInfo ) = 0;
5691 virtual void fatalErrorEncountered( StringRef name );
5693 virtual bool isMulti()
const;
5695 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5697 struct IReporterFactory {
5698 virtual ~IReporterFactory();
5699 virtual IStreamingReporterPtr create( ReporterConfig
const& config )
const = 0;
5700 virtual std::string getDescription()
const = 0;
5702 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5704 struct IReporterRegistry {
5705 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5706 using Listeners = std::vector<IReporterFactoryPtr>;
5708 virtual ~IReporterRegistry();
5709 virtual IStreamingReporterPtr create( std::string
const& name, IConfigPtr
const& config )
const = 0;
5710 virtual FactoryMap
const& getFactories()
const = 0;
5711 virtual Listeners
const& getListeners()
const = 0;
5726 void prepareExpandedExpression(AssertionResult& result);
5729 std::string getFormattedDuration(
double duration );
5732 bool shouldShowDuration( IConfig
const& config,
double duration );
5734 std::string serializeFilters( std::vector<std::string>
const& container );
5736 template<
typename DerivedT>
5737 struct StreamingReporterBase : IStreamingReporter {
5739 StreamingReporterBase( ReporterConfig
const& _config )
5740 : m_config( _config.fullConfig() ),
5741 stream( _config.stream() )
5743 m_reporterPrefs.shouldRedirectStdOut =
false;
5744 if( !DerivedT::getSupportedVerbosities().
count( m_config->verbosity() ) )
5745 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5748 ReporterPreferences getPreferences()
const override {
5749 return m_reporterPrefs;
5752 static std::set<Verbosity> getSupportedVerbosities() {
5753 return { Verbosity::Normal };
5756 ~StreamingReporterBase()
override =
default;
5758 void noMatchingTestCases(std::string
const&)
override {}
5760 void reportInvalidArguments(std::string
const&)
override {}
5762 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5763 currentTestRunInfo = _testRunInfo;
5766 void testGroupStarting(GroupInfo
const& _groupInfo)
override {
5767 currentGroupInfo = _groupInfo;
5770 void testCaseStarting(TestCaseInfo
const& _testInfo)
override {
5771 currentTestCaseInfo = _testInfo;
5773 void sectionStarting(SectionInfo
const& _sectionInfo)
override {
5774 m_sectionStack.push_back(_sectionInfo);
5777 void sectionEnded(SectionStats
const& )
override {
5778 m_sectionStack.pop_back();
5780 void testCaseEnded(TestCaseStats
const& )
override {
5781 currentTestCaseInfo.reset();
5783 void testGroupEnded(TestGroupStats
const& )
override {
5784 currentGroupInfo.reset();
5786 void testRunEnded(TestRunStats
const& )
override {
5787 currentTestCaseInfo.reset();
5788 currentGroupInfo.reset();
5789 currentTestRunInfo.reset();
5792 void skipTest(TestCaseInfo
const&)
override {
5797 IConfigPtr m_config;
5798 std::ostream& stream;
5800 LazyStat<TestRunInfo> currentTestRunInfo;
5801 LazyStat<GroupInfo> currentGroupInfo;
5802 LazyStat<TestCaseInfo> currentTestCaseInfo;
5804 std::vector<SectionInfo> m_sectionStack;
5805 ReporterPreferences m_reporterPrefs;
5808 template<
typename DerivedT>
5809 struct CumulativeReporterBase : IStreamingReporter {
5810 template<
typename T,
typename ChildNodeT>
5812 explicit Node( T
const& _value ) : value( _value ) {}
5815 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5817 ChildNodes children;
5819 struct SectionNode {
5820 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5821 virtual ~SectionNode() =
default;
5823 bool operator == (SectionNode
const& other)
const {
5824 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5826 bool operator == (std::shared_ptr<SectionNode>
const& other)
const {
5827 return operator==(*other);
5831 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5832 using Assertions = std::vector<AssertionStats>;
5833 ChildSections childSections;
5834 Assertions assertions;
5839 struct BySectionInfo {
5840 BySectionInfo( SectionInfo
const& other ) : m_other( other ) {}
5841 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
5842 bool operator() (std::shared_ptr<SectionNode>
const& node)
const {
5843 return ((node->stats.sectionInfo.name == m_other.name) &&
5844 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5846 void operator=(BySectionInfo
const&) =
delete;
5849 SectionInfo
const& m_other;
5852 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5853 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5854 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5856 CumulativeReporterBase( ReporterConfig
const& _config )
5857 : m_config( _config.fullConfig() ),
5858 stream( _config.stream() )
5860 m_reporterPrefs.shouldRedirectStdOut =
false;
5861 if( !DerivedT::getSupportedVerbosities().
count( m_config->verbosity() ) )
5862 CATCH_ERROR(
"Verbosity level not supported by this reporter" );
5864 ~CumulativeReporterBase()
override =
default;
5866 ReporterPreferences getPreferences()
const override {
5867 return m_reporterPrefs;
5870 static std::set<Verbosity> getSupportedVerbosities() {
5871 return { Verbosity::Normal };
5874 void testRunStarting( TestRunInfo
const& )
override {}
5875 void testGroupStarting( GroupInfo
const& )
override {}
5877 void testCaseStarting( TestCaseInfo
const& )
override {}
5879 void sectionStarting( SectionInfo
const& sectionInfo )
override {
5880 SectionStats incompleteStats( sectionInfo, Counts(), 0,
false );
5881 std::shared_ptr<SectionNode> node;
5882 if( m_sectionStack.empty() ) {
5883 if( !m_rootSection )
5884 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5885 node = m_rootSection;
5888 SectionNode& parentNode = *m_sectionStack.back();
5890 std::find_if( parentNode.childSections.begin(),
5891 parentNode.childSections.end(),
5892 BySectionInfo( sectionInfo ) );
5893 if( it == parentNode.childSections.end() ) {
5894 node = std::make_shared<SectionNode>( incompleteStats );
5895 parentNode.childSections.push_back( node );
5900 m_sectionStack.push_back( node );
5901 m_deepestSection = std::move(node);
5904 void assertionStarting(AssertionInfo
const&)
override {}
5906 bool assertionEnded(AssertionStats
const& assertionStats)
override {
5907 assert(!m_sectionStack.empty());
5913 prepareExpandedExpression(
const_cast<AssertionResult&
>( assertionStats.assertionResult ) );
5914 SectionNode& sectionNode = *m_sectionStack.back();
5915 sectionNode.assertions.push_back(assertionStats);
5918 void sectionEnded(SectionStats
const& sectionStats)
override {
5919 assert(!m_sectionStack.empty());
5920 SectionNode& node = *m_sectionStack.back();
5921 node.stats = sectionStats;
5922 m_sectionStack.pop_back();
5924 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
5925 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5926 assert(m_sectionStack.size() == 0);
5927 node->children.push_back(m_rootSection);
5928 m_testCases.push_back(node);
5929 m_rootSection.reset();
5931 assert(m_deepestSection);
5932 m_deepestSection->stdOut = testCaseStats.stdOut;
5933 m_deepestSection->stdErr = testCaseStats.stdErr;
5935 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
5936 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5937 node->children.swap(m_testCases);
5938 m_testGroups.push_back(node);
5940 void testRunEnded(TestRunStats
const& testRunStats)
override {
5941 auto node = std::make_shared<TestRunNode>(testRunStats);
5942 node->children.swap(m_testGroups);
5943 m_testRuns.push_back(node);
5944 testRunEndedCumulative();
5946 virtual void testRunEndedCumulative() = 0;
5948 void skipTest(TestCaseInfo
const&)
override {}
5950 IConfigPtr m_config;
5951 std::ostream& stream;
5952 std::vector<AssertionStats> m_assertions;
5953 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5954 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5955 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5957 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5959 std::shared_ptr<SectionNode> m_rootSection;
5960 std::shared_ptr<SectionNode> m_deepestSection;
5961 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5962 ReporterPreferences m_reporterPrefs;
5966 char const* getLineOfChars() {
5967 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5969 std::memset( line,
C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5970 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5975 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5976 TestEventListenerBase( ReporterConfig
const& _config );
5978 static std::set<Verbosity> getSupportedVerbosities();
5980 void assertionStarting(AssertionInfo
const&)
override;
5981 bool assertionEnded(AssertionStats
const&)
override;
6005 BrightRed = Bright | Red,
6006 BrightGreen = Bright | Green,
6007 LightGrey = Bright | Grey,
6008 BrightWhite = Bright | White,
6009 BrightYellow = Bright | Yellow,
6012 FileName = LightGrey,
6013 Warning = BrightYellow,
6014 ResultError = BrightRed,
6015 ResultSuccess = BrightGreen,
6016 ResultExpectedFailure = Warning,
6021 OriginalExpression = Cyan,
6022 ReconstructedExpression = BrightYellow,
6024 SecondaryText = LightGrey,
6029 Colour( Code _colourCode );
6030 Colour( Colour&& other )
noexcept;
6031 Colour& operator=( Colour&& other )
noexcept;
6035 static void use( Code _colourCode );
6038 bool m_moved =
false;
6041 std::ostream& operator << ( std::ostream& os, Colour
const& );
6051 template<
typename T>
6052 class ReporterRegistrar {
6054 class ReporterFactory :
public IReporterFactory {
6056 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6057 return std::unique_ptr<T>(
new T( config ) );
6060 std::string getDescription()
const override {
6061 return T::getDescription();
6067 explicit ReporterRegistrar( std::string
const& name ) {
6068 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6072 template<
typename T>
6073 class ListenerRegistrar {
6075 class ListenerFactory :
public IReporterFactory {
6077 IStreamingReporterPtr create( ReporterConfig
const& config )
const override {
6078 return std::unique_ptr<T>(
new T( config ) );
6080 std::string getDescription()
const override {
6081 return std::string();
6087 ListenerRegistrar() {
6088 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6093#if !defined(CATCH_CONFIG_DISABLE)
6095#define CATCH_REGISTER_REPORTER( name, reporterType ) \
6096 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6097 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6098 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6099 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6101#define CATCH_REGISTER_LISTENER( listenerType ) \
6102 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6103 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6104 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6105 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6108#define CATCH_REGISTER_REPORTER(name, reporterType)
6109#define CATCH_REGISTER_LISTENER(listenerType)
6119 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6121 using StreamingReporterBase::StreamingReporterBase;
6123 ~CompactReporter()
override;
6125 static std::string getDescription();
6127 void noMatchingTestCases(std::string
const& spec)
override;
6129 void assertionStarting(AssertionInfo
const&)
override;
6131 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6133 void sectionEnded(SectionStats
const& _sectionStats)
override;
6135 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6144#if defined(_MSC_VER)
6145#pragma warning(push)
6146#pragma warning(disable:4061)
6153 struct SummaryColumn;
6156 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6157 std::unique_ptr<TablePrinter> m_tablePrinter;
6159 ConsoleReporter(ReporterConfig
const& config);
6160 ~ConsoleReporter()
override;
6161 static std::string getDescription();
6163 void noMatchingTestCases(std::string
const& spec)
override;
6165 void reportInvalidArguments(std::string
const&arg)
override;
6167 void assertionStarting(AssertionInfo
const&)
override;
6169 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6171 void sectionStarting(SectionInfo
const& _sectionInfo)
override;
6172 void sectionEnded(SectionStats
const& _sectionStats)
override;
6174#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6175 void benchmarkPreparing(std::string
const& name)
override;
6176 void benchmarkStarting(BenchmarkInfo
const& info)
override;
6177 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6178 void benchmarkFailed(std::string
const& error)
override;
6181 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6182 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6183 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6184 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6189 void lazyPrintWithoutClosingBenchmarkTable();
6190 void lazyPrintRunInfo();
6191 void lazyPrintGroupInfo();
6192 void printTestCaseAndSectionHeader();
6194 void printClosedHeader(std::string
const& _name);
6195 void printOpenHeader(std::string
const& _name);
6199 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6201 void printTotals(Totals
const& totals);
6202 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row);
6204 void printTotalsDivider(Totals
const& totals);
6205 void printSummaryDivider();
6206 void printTestFilters();
6209 bool m_headerPrinted =
false;
6214#if defined(_MSC_VER)
6226 enum class XmlFormatting {
6232 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6233 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6237 enum ForWhat { ForTextNodes, ForAttributes };
6239 XmlEncode( std::string
const& str, ForWhat forWhat = ForTextNodes );
6241 void encodeTo( std::ostream& os )
const;
6243 friend std::ostream&
operator << ( std::ostream& os, XmlEncode
const& xmlEncode );
6253 class ScopedElement {
6255 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6257 ScopedElement( ScopedElement&& other )
noexcept;
6258 ScopedElement& operator=( ScopedElement&& other )
noexcept;
6262 ScopedElement& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6264 template<
typename T>
6265 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
6266 m_writer->writeAttribute( name, attribute );
6271 mutable XmlWriter* m_writer =
nullptr;
6272 XmlFormatting m_fmt;
6275 XmlWriter( std::ostream& os = Catch::cout() );
6278 XmlWriter( XmlWriter
const& ) =
delete;
6279 XmlWriter& operator=( XmlWriter
const& ) =
delete;
6281 XmlWriter& startElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6283 ScopedElement scopedElement( std::string
const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6285 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6287 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute );
6289 XmlWriter& writeAttribute( std::string
const& name,
bool attribute );
6291 template<
typename T>
6292 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
6293 ReusableStringStream rss;
6295 return writeAttribute( name, rss.str() );
6298 XmlWriter& writeText( std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6300 XmlWriter& writeComment(std::string
const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6302 void writeStylesheetRef( std::string
const& url );
6304 XmlWriter& writeBlankLine();
6306 void ensureTagClosed();
6310 void applyFormatting(XmlFormatting fmt);
6312 void writeDeclaration();
6314 void newlineIfNecessary();
6316 bool m_tagIsOpen =
false;
6317 bool m_needsNewline =
false;
6318 std::vector<std::string> m_tags;
6319 std::string m_indent;
6328 class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6330 JunitReporter(ReporterConfig
const& _config);
6332 ~JunitReporter()
override;
6334 static std::string getDescription();
6336 void noMatchingTestCases(std::string
const& )
override;
6338 void testRunStarting(TestRunInfo
const& runInfo)
override;
6340 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6342 void testCaseStarting(TestCaseInfo
const& testCaseInfo)
override;
6343 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6345 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6347 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6349 void testRunEndedCumulative()
override;
6351 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6353 void writeTestCase(TestCaseNode
const& testCaseNode);
6355 void writeSection( std::string
const& className,
6356 std::string
const& rootName,
6357 SectionNode
const& sectionNode,
6358 bool testOkToFail );
6360 void writeAssertions(SectionNode
const& sectionNode);
6361 void writeAssertion(AssertionStats
const& stats);
6365 std::string stdOutForSuite;
6366 std::string stdErrForSuite;
6367 unsigned int unexpectedExceptions = 0;
6368 bool m_okToFail =
false;
6377 class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6379 XmlReporter(ReporterConfig
const& _config);
6381 ~XmlReporter()
override;
6383 static std::string getDescription();
6385 virtual std::string getStylesheetRef()
const;
6387 void writeSourceInfo(SourceLineInfo
const& sourceInfo);
6391 void noMatchingTestCases(std::string
const& s)
override;
6393 void testRunStarting(TestRunInfo
const& testInfo)
override;
6395 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6397 void testCaseStarting(TestCaseInfo
const& testInfo)
override;
6399 void sectionStarting(SectionInfo
const& sectionInfo)
override;
6401 void assertionStarting(AssertionInfo
const&)
override;
6403 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6405 void sectionEnded(SectionStats
const& sectionStats)
override;
6407 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6409 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6411 void testRunEnded(TestRunStats
const& testRunStats)
override;
6413#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6414 void benchmarkPreparing(std::string
const& name)
override;
6415 void benchmarkStarting(BenchmarkInfo
const&)
override;
6416 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6417 void benchmarkFailed(std::string
const&)
override;
6421 Timer m_testCaseTimer;
6423 int m_sectionDepth = 0;
6433#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6458 namespace Benchmark {
6459 template <
typename Clock>
6460 using ClockDuration =
typename Clock::duration;
6461 template <
typename Clock>
6462 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6464 template <
typename Clock>
6465 using TimePoint =
typename Clock::time_point;
6467 using default_clock = std::chrono::steady_clock;
6469 template <
typename Clock>
6471 TimePoint<Clock> operator()()
const {
6472 return Clock::now();
6476 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6486#if defined(_MSC_VER)
6491 namespace Benchmark {
6492#if defined(__GNUC__) || defined(__clang__)
6493 template <
typename T>
6494 inline void keep_memory(T* p) {
6495 asm volatile(
"" : :
"g"(p) :
"memory");
6497 inline void keep_memory() {
6498 asm volatile(
"" : : :
"memory");
6502 inline void optimizer_barrier() { keep_memory(); }
6504#elif defined(_MSC_VER)
6506#pragma optimize("", off)
6507 template <
typename T>
6508 inline void keep_memory(T* p) {
6510 *
reinterpret_cast<char volatile*
>(p) = *
reinterpret_cast<char const volatile*
>(p);
6513#pragma optimize("", on)
6516 inline void optimizer_barrier() {
6517 std::atomic_thread_fence(std::memory_order_seq_cst);
6523 template <
typename T>
6524 inline void deoptimize_value(T&& x) {
6528 template <
typename Fn,
typename... Args>
6529 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<!std::is_same<void,
decltype(fn(args...))>::value>::type {
6530 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6533 template <
typename Fn,
typename... Args>
6534 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
typename std::enable_if<std::is_same<void,
decltype(fn(args...))>::value>::type {
6535 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6546#include <type_traits>
6550 namespace Benchmark {
6552 template <
typename T>
6553 struct CompleteType {
using type = T; };
6555 struct CompleteType<void> {
struct type {}; };
6557 template <
typename T>
6558 using CompleteType_t =
typename CompleteType<T>::type;
6560 template <
typename Result>
6561 struct CompleteInvoker {
6562 template <
typename Fun,
typename... Args>
6563 static Result invoke(Fun&& fun, Args&&... args) {
6564 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6568 struct CompleteInvoker<void> {
6569 template <
typename Fun,
typename... Args>
6570 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6571 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6577 template <
typename Fun,
typename... Args>
6578 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6579 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6582 const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6585 template <
typename Fun>
6586 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6588 return Detail::complete_invoke(std::forward<Fun>(fun));
6590 getResultCapture().benchmarkFailed(translateActiveException());
6591 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6599 namespace Benchmark {
6601 struct ChronometerConcept {
6602 virtual void start() = 0;
6603 virtual void finish() = 0;
6604 virtual ~ChronometerConcept() =
default;
6606 template <
typename Clock>
6607 struct ChronometerModel final :
public ChronometerConcept {
6608 void start()
override { started = Clock::now(); }
6609 void finish()
override { finished = Clock::now(); }
6611 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6613 TimePoint<Clock> started;
6614 TimePoint<Clock> finished;
6618 struct Chronometer {
6620 template <
typename Fun>
6621 void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(
int)>()); }
6623 int runs()
const {
return k; }
6625 Chronometer(Detail::ChronometerConcept& meter,
int k)
6630 template <
typename Fun>
6631 void measure(Fun&& fun, std::false_type) {
6632 measure([&fun](
int) {
return fun(); }, std::true_type());
6635 template <
typename Fun>
6636 void measure(Fun&& fun, std::true_type) {
6637 Detail::optimizer_barrier();
6639 for (
int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6641 Detail::optimizer_barrier();
6644 Detail::ChronometerConcept* impl;
6657 namespace Benchmark {
6658 template <
typename Duration>
6659 struct EnvironmentEstimate {
6661 OutlierClassification outliers;
6663 template <
typename Duration2>
6664 operator EnvironmentEstimate<Duration2>()
const {
6665 return { mean, outliers };
6668 template <
typename Clock>
6669 struct Environment {
6670 using clock_type = Clock;
6671 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6672 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6689#include <type_traits>
6694 namespace Benchmark {
6696 template <
typename T>
6697 using Decay =
typename std::decay<T>::type;
6698 template <
typename T,
typename U>
6700 : std::is_same<Decay<T>, Decay<U>> {};
6709 struct BenchmarkFunction {
6712 virtual void call(Chronometer meter)
const = 0;
6713 virtual callable* clone()
const = 0;
6714 virtual ~callable() =
default;
6716 template <
typename Fun>
6717 struct model :
public callable {
6718 model(Fun&& fun) : fun(std::move(fun)) {}
6719 model(Fun
const& fun) : fun(fun) {}
6721 model<Fun>* clone()
const override {
return new model<Fun>(*
this); }
6723 void call(Chronometer meter)
const override {
6724 call(meter, is_callable<Fun(Chronometer)>());
6726 void call(Chronometer meter, std::true_type)
const {
6729 void call(Chronometer meter, std::false_type)
const {
6736 struct do_nothing {
void operator()()
const {} };
6738 template <
typename T>
6739 BenchmarkFunction(model<T>* c) : f(c) {}
6743 : f(new model<do_nothing>{ {} }) {}
6745 template <
typename Fun,
6746 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
int>::type = 0>
6747 BenchmarkFunction(Fun&& fun)
6748 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6750 BenchmarkFunction(BenchmarkFunction&& that)
6751 : f(std::move(that.f)) {}
6753 BenchmarkFunction(BenchmarkFunction
const& that)
6754 : f(that.f->clone()) {}
6756 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6757 f = std::move(that.f);
6761 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6762 f.reset(that.f->clone());
6766 void operator()(Chronometer meter)
const { f->call(meter); }
6769 std::unique_ptr<callable> f;
6781#include <type_traits>
6785 namespace Benchmark {
6787 template <
typename Fun>
6789 void operator()(
int k)
const {
6790 for (
int i = 0; i < k; ++i) {
6796 template <
typename Fun>
6797 repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6798 return { std::forward<Fun>(fun) };
6821#include <type_traits>
6824 namespace Benchmark {
6825 template <
typename Duration,
typename Result>
6831 template <
typename Clock,
typename Func,
typename... Args>
6832 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6840 namespace Benchmark {
6842 template <
typename Clock,
typename Fun,
typename... Args>
6843 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6844 auto start = Clock::now();
6845 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6846 auto end = Clock::now();
6847 auto delta = end - start;
6848 return { delta, std::forward<decltype(r)>(r), 1 };
6856#include <type_traits>
6859 namespace Benchmark {
6861 template <
typename Clock,
typename Fun>
6862 TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6863 return Detail::measure<Clock>(fun, iters);
6865 template <
typename Clock,
typename Fun>
6866 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6867 Detail::ChronometerModel<Clock> meter;
6868 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6870 return { meter.elapsed(), std::move(result), iters };
6873 template <
typename Clock,
typename Fun>
6874 using run_for_at_least_argument_t =
typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer,
int>::type;
6876 struct optimized_away_error : std::exception {
6877 const char* what() const noexcept
override {
6878 return "could not measure benchmark, maybe it was optimized away";
6882 template <
typename Clock,
typename Fun>
6883 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6885 while (iters < (1 << 30)) {
6886 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6888 if (Timing.elapsed >= how_long) {
6889 return { Timing.elapsed, std::move(Timing.result), iters };
6893 Catch::throw_exception(optimized_away_error{});
6904 namespace Benchmark {
6905 template <
typename Duration>
6906 struct ExecutionPlan {
6907 int iterations_per_sample;
6908 Duration estimated_duration;
6909 Detail::BenchmarkFunction benchmark;
6910 Duration warmup_time;
6911 int warmup_iterations;
6913 template <
typename Duration2>
6914 operator ExecutionPlan<Duration2>()
const {
6915 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6918 template <
typename Clock>
6919 std::vector<FloatDuration<Clock>> run(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
6921 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6923 std::vector<FloatDuration<Clock>> times;
6924 times.reserve(cfg.benchmarkSamples());
6925 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [
this, env] {
6926 Detail::ChronometerModel<Clock> model;
6927 this->benchmark(Chronometer(model, iterations_per_sample));
6928 auto sample_time = model.elapsed() - env.clock_cost.mean;
6929 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6930 return sample_time / iterations_per_sample;
6950#include <functional>
6961 namespace Benchmark {
6963 using sample = std::vector<double>;
6965 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6967 template <
typename Iterator>
6968 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6969 std::vector<double> copy(first, last);
6971 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6972 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6974 auto los = q1 - (iqr * 3.);
6975 auto lom = q1 - (iqr * 1.5);
6976 auto him = q3 + (iqr * 1.5);
6977 auto his = q3 + (iqr * 3.);
6979 OutlierClassification o;
6980 for (; first != last; ++first) {
6982 if (t < los) ++o.low_severe;
6983 else if (t < lom) ++o.low_mild;
6984 else if (t > his) ++o.high_severe;
6985 else if (t > him) ++o.high_mild;
6991 template <
typename Iterator>
6992 double mean(Iterator first, Iterator last) {
6993 auto count = last - first;
6994 double sum = std::accumulate(first, last, 0.);
6998 template <
typename URng,
typename Iterator,
typename Estimator>
6999 sample resample(URng& rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
7000 auto n = last - first;
7001 std::uniform_int_distribution<
decltype(n)> dist(0, n - 1);
7004 out.reserve(resamples);
7005 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7006 std::vector<double> resampled;
7007 resampled.reserve(n);
7008 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
return first[dist(rng)]; });
7009 return estimator(resampled.begin(), resampled.end());
7011 std::sort(out.begin(), out.end());
7015 template <
typename Estimator,
typename Iterator>
7016 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7017 auto n = last - first;
7018 auto second = std::next(first);
7022 for (
auto it = first; it != last; ++it) {
7023 std::iter_swap(it, first);
7024 results.push_back(estimator(second, last));
7030 inline double normal_cdf(
double x) {
7031 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7034 double erfc_inv(
double x);
7036 double normal_quantile(
double p);
7038 template <
typename Iterator,
typename Estimator>
7039 Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last, sample
const& resample, Estimator&& estimator) {
7040 auto n_samples = last - first;
7042 double point = estimator(first, last);
7044 if (n_samples == 1)
return { point, point, point, confidence_level };
7046 sample jack = jackknife(estimator, first, last);
7047 double jack_mean = mean(jack.begin(), jack.end());
7048 double sum_squares, sum_cubes;
7049 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> {
7050 auto d = jack_mean - x;
7053 return { sqcb.first + d2, sqcb.second + d3 };
7056 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7057 int n =
static_cast<int>(resample.size());
7058 double prob_n = std::count_if(resample.begin(), resample.end(), [point](
double x) { return x < point; }) / (double)n;
7060 if (prob_n == 0)
return { point, point, point, confidence_level };
7062 double bias = normal_quantile(prob_n);
7063 double z1 = normal_quantile((1. - confidence_level) / 2.);
7065 auto cumn = [n](
double x) ->
int {
7066 return std::lround(normal_cdf(x) * n); };
7067 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7068 double b1 = bias + z1;
7069 double b2 = bias - z1;
7072 auto lo = (std::max)(cumn(a1), 0);
7073 auto hi = (std::min)(cumn(a2), n - 1);
7075 return { point, resample[lo], resample[hi], confidence_level };
7078 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7080 struct bootstrap_analysis {
7081 Estimate<double> mean;
7082 Estimate<double> standard_deviation;
7083 double outlier_variance;
7086 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7099 namespace Benchmark {
7101 template <
typename Clock>
7102 std::vector<double> resolution(
int k) {
7103 std::vector<TimePoint<Clock>> times;
7104 times.reserve(k + 1);
7105 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7107 std::vector<double> deltas;
7109 std::transform(std::next(times.begin()), times.end(), times.begin(),
7110 std::back_inserter(deltas),
7111 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7116 const auto warmup_iterations = 10000;
7117 const auto warmup_time = std::chrono::milliseconds(100);
7118 const auto minimum_ticks = 1000;
7119 const auto warmup_seed = 10000;
7120 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7121 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7122 const auto clock_cost_estimation_tick_limit = 100000;
7123 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7124 const auto clock_cost_estimation_iterations = 10000;
7126 template <
typename Clock>
7128 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7131 template <
typename Clock>
7132 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7133 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7136 FloatDuration<Clock>(mean(r.begin(), r.end())),
7137 classify_outliers(r.begin(), r.end()),
7140 template <
typename Clock>
7141 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7142 auto time_limit = (std::min)(
7143 resolution * clock_cost_estimation_tick_limit,
7144 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7145 auto time_clock = [](
int k) {
7146 return Detail::measure<Clock>([k] {
7147 for (
int i = 0; i < k; ++i) {
7148 volatile auto ignored = Clock::now();
7154 int iters = clock_cost_estimation_iterations;
7155 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7156 std::vector<double> times;
7157 int nsamples =
static_cast<int>(std::ceil(time_limit / r.elapsed));
7158 times.reserve(nsamples);
7159 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7160 return static_cast<double>((time_clock(r.iterations) / r.iterations).
count());
7163 FloatDuration<Clock>(mean(times.begin(), times.end())),
7164 classify_outliers(times.begin(), times.end()),
7168 template <
typename Clock>
7169 Environment<FloatDuration<Clock>> measure_environment() {
7170 static Environment<FloatDuration<Clock>>* env =
nullptr;
7175 auto iters = Detail::warmup<Clock>();
7176 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7177 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7179 env =
new Environment<FloatDuration<Clock>>{ resolution, cost };
7203 namespace Benchmark {
7204 template <
typename Duration>
7205 struct SampleAnalysis {
7206 std::vector<Duration> samples;
7207 Estimate<Duration> mean;
7208 Estimate<Duration> standard_deviation;
7209 OutlierClassification outliers;
7210 double outlier_variance;
7212 template <
typename Duration2>
7213 operator SampleAnalysis<Duration2>()
const {
7214 std::vector<Duration2> samples2;
7215 samples2.reserve(samples.size());
7216 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7218 std::move(samples2),
7235 namespace Benchmark {
7237 template <
typename Duration,
typename Iterator>
7238 SampleAnalysis<Duration> analyse(
const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7239 if (!cfg.benchmarkNoAnalysis()) {
7240 std::vector<double> samples;
7241 samples.reserve(last - first);
7242 std::transform(first, last, std::back_inserter(samples), [](Duration d) {
return d.count(); });
7244 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7245 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7247 auto wrap_estimate = [](Estimate<double> e) {
7248 return Estimate<Duration> {
7250 Duration(e.lower_bound),
7251 Duration(e.upper_bound),
7252 e.confidence_interval,
7255 std::vector<Duration> samples2;
7256 samples2.reserve(samples.size());
7257 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](
double d) { return Duration(d); });
7259 std::move(samples2),
7260 wrap_estimate(analysis.mean),
7261 wrap_estimate(analysis.standard_deviation),
7263 analysis.outlier_variance,
7266 std::vector<Duration> samples;
7267 samples.reserve(last - first);
7269 Duration mean = Duration(0);
7271 for (
auto it = first; it < last; ++it, ++i) {
7272 samples.push_back(Duration(*it));
7273 mean += Duration(*it);
7279 Estimate<Duration>{mean, mean, mean, 0.0},
7280 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7281 OutlierClassification{},
7292#include <functional>
7298 namespace Benchmark {
7300 Benchmark(std::string &&name)
7301 : name(std::move(name)) {}
7303 template <
class FUN>
7304 Benchmark(std::string &&name, FUN &&
func)
7305 : fun(std::move(
func)), name(std::move(name)) {}
7307 template <
typename Clock>
7308 ExecutionPlan<FloatDuration<Clock>> prepare(
const IConfig &cfg, Environment<FloatDuration<Clock>> env)
const {
7309 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7310 auto run_time = std::max(min_time, std::chrono::duration_cast<
decltype(min_time)>(cfg.benchmarkWarmupTime()));
7311 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7312 int new_iters =
static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7313 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7316 template <
typename Clock = default_clock>
7318 IConfigPtr cfg = getCurrentContext().getConfig();
7320 auto env = Detail::measure_environment<Clock>();
7322 getResultCapture().benchmarkPreparing(name);
7324 auto plan = user_code([&] {
7325 return prepare<Clock>(*cfg, env);
7328 BenchmarkInfo
info {
7330 plan.estimated_duration.count(),
7331 plan.iterations_per_sample,
7332 cfg->benchmarkSamples(),
7333 cfg->benchmarkResamples(),
7334 env.clock_resolution.mean.count(),
7335 env.clock_cost.mean.count()
7338 getResultCapture().benchmarkStarting(info);
7340 auto samples = user_code([&] {
7341 return plan.template run<Clock>(*cfg, env);
7344 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7345 BenchmarkStats<FloatDuration<Clock>> stats{
info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7346 getResultCapture().benchmarkEnded(stats);
7349 if (translateActiveException() != Detail::benchmarkErrorMsg)
7350 std::rethrow_exception(std::current_exception());
7355 template <
typename Fun,
7356 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value,
int>::type = 0>
7357 Benchmark & operator=(Fun
func) {
7358 fun = Detail::BenchmarkFunction(
func);
7363 explicit operator bool() {
7368 Detail::BenchmarkFunction fun;
7374#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7375#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7377#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7378 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7379 BenchmarkName = [&](int benchmarkIndex)
7381#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7382 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7391#include <type_traits>
7394 namespace Benchmark {
7396 template <
typename T,
bool Destruct>
7397 struct ObjectStorage
7399 ObjectStorage() : data() {}
7401 ObjectStorage(
const ObjectStorage& other)
7403 new(&data) T(other.stored_object());
7406 ObjectStorage(ObjectStorage&& other)
7408 new(&data) T(std::move(other.stored_object()));
7411 ~ObjectStorage() { destruct_on_exit<T>(); }
7413 template <
typename... Args>
7414 void construct(Args&&... args)
7416 new (&data) T(std::forward<Args>(args)...);
7419 template <
bool AllowManualDestruction = !Destruct>
7420 typename std::enable_if<AllowManualDestruction>::type destruct()
7422 stored_object().~T();
7427 template <
typename U>
7428 void destruct_on_exit(
typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7430 template <
typename U>
7431 void destruct_on_exit(
typename std::enable_if<!Destruct, U>::type* = 0) { }
7433 T& stored_object() {
7434 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7437 T
const& stored_object()
const {
7438 return *
static_cast<T*
>(
static_cast<void*
>(&data));
7441 struct {
alignas(T)
unsigned char data[
sizeof(T)]; } data;
7445 template <
typename T>
7446 using storage_for = Detail::ObjectStorage<T, true>;
7448 template <
typename T>
7449 using destructable_object = Detail::ObjectStorage<T, false>;
7463#pragma clang diagnostic push
7464#pragma clang diagnostic ignored "-Wweak-vtables"
7475namespace TestCaseTracking {
7477 struct NameAndLocation {
7479 SourceLineInfo location;
7481 NameAndLocation( std::string
const& _name, SourceLineInfo
const& _location );
7482 friend bool operator==(NameAndLocation
const& lhs, NameAndLocation
const& rhs) {
7483 return lhs.name == rhs.name
7484 && lhs.location == rhs.location;
7490 using ITrackerPtr = std::shared_ptr<ITracker>;
7493 NameAndLocation m_nameAndLocation;
7496 ITracker(NameAndLocation
const& nameAndLoc) :
7497 m_nameAndLocation(nameAndLoc)
7501 NameAndLocation
const& nameAndLocation()
const {
7502 return m_nameAndLocation;
7505 virtual ~ITracker();
7508 virtual bool isComplete()
const = 0;
7509 virtual bool isSuccessfullyCompleted()
const = 0;
7510 virtual bool isOpen()
const = 0;
7511 virtual bool hasChildren()
const = 0;
7512 virtual bool hasStarted()
const = 0;
7514 virtual ITracker& parent() = 0;
7517 virtual void close() = 0;
7518 virtual void fail() = 0;
7519 virtual void markAsNeedingAnotherRun() = 0;
7521 virtual void addChild( ITrackerPtr
const& child ) = 0;
7522 virtual ITrackerPtr findChild( NameAndLocation
const& nameAndLocation ) = 0;
7523 virtual void openChild() = 0;
7526 virtual bool isSectionTracker()
const = 0;
7527 virtual bool isGeneratorTracker()
const = 0;
7530 class TrackerContext {
7538 ITrackerPtr m_rootTracker;
7539 ITracker* m_currentTracker =
nullptr;
7540 RunState m_runState = NotStarted;
7544 ITracker& startRun();
7548 void completeCycle();
7550 bool completedCycle()
const;
7551 ITracker& currentTracker();
7552 void setCurrentTracker( ITracker* tracker );
7555 class TrackerBase :
public ITracker {
7562 CompletedSuccessfully,
7566 using Children = std::vector<ITrackerPtr>;
7567 TrackerContext& m_ctx;
7570 CycleState m_runState = NotStarted;
7573 TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7575 bool isComplete()
const override;
7576 bool isSuccessfullyCompleted()
const override;
7577 bool isOpen()
const override;
7578 bool hasChildren()
const override;
7579 bool hasStarted()
const override {
7580 return m_runState != NotStarted;
7583 void addChild( ITrackerPtr
const& child )
override;
7585 ITrackerPtr findChild( NameAndLocation
const& nameAndLocation )
override;
7586 ITracker& parent()
override;
7588 void openChild()
override;
7590 bool isSectionTracker()
const override;
7591 bool isGeneratorTracker()
const override;
7595 void close()
override;
7596 void fail()
override;
7597 void markAsNeedingAnotherRun()
override;
7600 void moveToParent();
7604 class SectionTracker :
public TrackerBase {
7605 std::vector<std::string> m_filters;
7606 std::string m_trimmed_name;
7608 SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7610 bool isSectionTracker()
const override;
7612 bool isComplete()
const override;
7614 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation );
7618 void addInitialFilters( std::vector<std::string>
const& filters );
7619 void addNextFilters( std::vector<std::string>
const& filters );
7621 std::vector<std::string>
const& getFilters()
const;
7623 std::string
const& trimmedName()
const;
7628using TestCaseTracking::ITracker;
7629using TestCaseTracking::TrackerContext;
7630using TestCaseTracking::SectionTracker;
7640 struct LeakDetector {
7652#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7657#if defined(CATCH_CONFIG_USE_ASYNC)
7662 double erf_inv(
double x) {
7666 w = -log((1.0 - x) * (1.0 + x));
7670 p = -3.6444120640178196996e-21;
7671 p = -1.685059138182016589e-19 + p * w;
7672 p = 1.2858480715256400167e-18 + p * w;
7673 p = 1.115787767802518096e-17 + p * w;
7674 p = -1.333171662854620906e-16 + p * w;
7675 p = 2.0972767875968561637e-17 + p * w;
7676 p = 6.6376381343583238325e-15 + p * w;
7677 p = -4.0545662729752068639e-14 + p * w;
7678 p = -8.1519341976054721522e-14 + p * w;
7679 p = 2.6335093153082322977e-12 + p * w;
7680 p = -1.2975133253453532498e-11 + p * w;
7681 p = -5.4154120542946279317e-11 + p * w;
7682 p = 1.051212273321532285e-09 + p * w;
7683 p = -4.1126339803469836976e-09 + p * w;
7684 p = -2.9070369957882005086e-08 + p * w;
7685 p = 4.2347877827932403518e-07 + p * w;
7686 p = -1.3654692000834678645e-06 + p * w;
7687 p = -1.3882523362786468719e-05 + p * w;
7688 p = 0.0001867342080340571352 + p * w;
7689 p = -0.00074070253416626697512 + p * w;
7690 p = -0.0060336708714301490533 + p * w;
7691 p = 0.24015818242558961693 + p * w;
7692 p = 1.6536545626831027356 + p * w;
7693 }
else if (w < 16.000000) {
7694 w = sqrt(w) - 3.250000;
7695 p = 2.2137376921775787049e-09;
7696 p = 9.0756561938885390979e-08 + p * w;
7697 p = -2.7517406297064545428e-07 + p * w;
7698 p = 1.8239629214389227755e-08 + p * w;
7699 p = 1.5027403968909827627e-06 + p * w;
7700 p = -4.013867526981545969e-06 + p * w;
7701 p = 2.9234449089955446044e-06 + p * w;
7702 p = 1.2475304481671778723e-05 + p * w;
7703 p = -4.7318229009055733981e-05 + p * w;
7704 p = 6.8284851459573175448e-05 + p * w;
7705 p = 2.4031110387097893999e-05 + p * w;
7706 p = -0.0003550375203628474796 + p * w;
7707 p = 0.00095328937973738049703 + p * w;
7708 p = -0.0016882755560235047313 + p * w;
7709 p = 0.0024914420961078508066 + p * w;
7710 p = -0.0037512085075692412107 + p * w;
7711 p = 0.005370914553590063617 + p * w;
7712 p = 1.0052589676941592334 + p * w;
7713 p = 3.0838856104922207635 + p * w;
7715 w = sqrt(w) - 5.000000;
7716 p = -2.7109920616438573243e-11;
7717 p = -2.5556418169965252055e-10 + p * w;
7718 p = 1.5076572693500548083e-09 + p * w;
7719 p = -3.7894654401267369937e-09 + p * w;
7720 p = 7.6157012080783393804e-09 + p * w;
7721 p = -1.4960026627149240478e-08 + p * w;
7722 p = 2.9147953450901080826e-08 + p * w;
7723 p = -6.7711997758452339498e-08 + p * w;
7724 p = 2.2900482228026654717e-07 + p * w;
7725 p = -9.9298272942317002539e-07 + p * w;
7726 p = 4.5260625972231537039e-06 + p * w;
7727 p = -1.9681778105531670567e-05 + p * w;
7728 p = 7.5995277030017761139e-05 + p * w;
7729 p = -0.00021503011930044477347 + p * w;
7730 p = -0.00013871931833623122026 + p * w;
7731 p = 1.0103004648645343977 + p * w;
7732 p = 4.8499064014085844221 + p * w;
7737 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7738 auto m = Catch::Benchmark::Detail::mean(first, last);
7739 double variance = std::accumulate(first, last, 0., [m](
double a,
double b) {
7740 double diff = b - m;
7741 return a + diff * diff;
7742 }) / (last - first);
7743 return std::sqrt(variance);
7749 namespace Benchmark {
7752 double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7753 auto count = last - first;
7754 double idx = (
count - 1) * k / static_cast<double>(q);
7755 int j =
static_cast<int>(idx);
7757 std::nth_element(first, first + j, last);
7759 if (g == 0)
return xj;
7761 auto xj1 = *std::min_element(first + (j + 1), last);
7762 return xj + g * (xj1 - xj);
7765 double erfc_inv(
double x) {
7766 return erf_inv(1.0 - x);
7769 double normal_quantile(
double p) {
7770 static const double ROOT_TWO = std::sqrt(2.0);
7772 double result = 0.0;
7773 assert(p >= 0 && p <= 1);
7774 if (p < 0 || p > 1) {
7778 result = -erfc_inv(2.0 * p);
7785 double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7786 double sb = stddev.point;
7787 double mn = mean.point / n;
7788 double mg_min = mn / 2.;
7789 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7790 double sg2 = sg * sg;
7791 double sb2 = sb * sb;
7793 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7797 double k0 = -n * nd;
7798 double k1 = sb2 - n * sg2 + nd;
7799 double det = k1 * k1 - 4 * sg2 * k0;
7800 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7803 auto var_out = [n, sb2, sg2](
double c) {
7805 return (nc / n) * (sb2 - nc * sg2);
7808 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7811 bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7812 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7813 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7814 static std::random_device entropy;
7815 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7817 auto n =
static_cast<int>(last - first);
7819 auto mean = &Detail::mean<std::vector<double>::iterator>;
7820 auto stddev = &standard_deviation;
7822#if defined(CATCH_CONFIG_USE_ASYNC)
7823 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7824 auto seed = entropy();
7825 return std::async(std::launch::async, [=] {
7826 std::mt19937 rng(seed);
7827 auto resampled = resample(rng, n_resamples, first, last, f);
7828 return bootstrap(confidence_level, first, last, resampled, f);
7832 auto mean_future = Estimate(mean);
7833 auto stddev_future = Estimate(stddev);
7835 auto mean_estimate = mean_future.get();
7836 auto stddev_estimate = stddev_future.get();
7838 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7839 auto seed = entropy();
7840 std::mt19937 rng(seed);
7841 auto resampled = resample(rng, n_resamples, first, last, f);
7842 return bootstrap(confidence_level, first, last, resampled, f);
7845 auto mean_estimate = Estimate(mean);
7846 auto stddev_estimate = Estimate(stddev);
7849 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7851 return { mean_estimate, stddev_estimate, outlier_variance };
7868bool marginComparison(
double lhs,
double rhs,
double margin) {
7869 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7877 Approx::Approx (
double value )
7878 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7884 Approx Approx::custom() {
7888 Approx Approx::operator-()
const {
7890 temp.m_value = -temp.m_value;
7894 std::string Approx::toString()
const {
7895 ReusableStringStream rss;
7896 rss <<
"Approx( " << ::Catch::Detail::stringify( m_value ) <<
" )";
7900 bool Approx::equalityComparisonImpl(
const double other)
const {
7903 return marginComparison(m_value, other, m_margin)
7904 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7907 void Approx::setMargin(
double newMargin) {
7908 CATCH_ENFORCE(newMargin >= 0,
7909 "Invalid Approx::margin: " << newMargin <<
'.'
7910 <<
" Approx::Margin has to be non-negative.");
7911 m_margin = newMargin;
7914 void Approx::setEpsilon(
double newEpsilon) {
7915 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7916 "Invalid Approx::epsilon: " << newEpsilon <<
'.'
7917 <<
" Approx::epsilon has to be in [0, 1]");
7918 m_epsilon = newEpsilon;
7924 Detail::Approx
operator "" _a(
long double val) {
7925 return Detail::Approx(val);
7927 Detail::Approx
operator "" _a(
unsigned long long val) {
7928 return Detail::Approx(val);
7933 return value.toString();
7943 bool isDebuggerActive();
7946#ifdef CATCH_PLATFORM_MAC
7948 #if defined(__i386__) || defined(__x86_64__)
7949 #define CATCH_TRAP() __asm__("int $3\n" : : )
7950 #elif defined(__aarch64__)
7951 #define CATCH_TRAP() __asm__(".inst 0xd43e0000")
7954#elif defined(CATCH_PLATFORM_IPHONE)
7957 #if defined(__i386__) || defined(__x86_64__)
7958 #define CATCH_TRAP() __asm__("int $3")
7959 #elif defined(__aarch64__)
7960 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7961 #elif defined(__arm__) && !defined(__thumb__)
7962 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7963 #elif defined(__arm__) && defined(__thumb__)
7964 #define CATCH_TRAP() __asm__(".inst 0xde01")
7967#elif defined(CATCH_PLATFORM_LINUX)
7971 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7972 #define CATCH_TRAP() asm volatile ("int $3")
7976 #define CATCH_TRAP() raise(SIGTRAP)
7978#elif defined(_MSC_VER)
7979 #define CATCH_TRAP() __debugbreak()
7980#elif defined(__MINGW32__)
7981 extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
7982 #define CATCH_TRAP() DebugBreak()
7985#ifndef CATCH_BREAK_INTO_DEBUGGER
7987 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7989 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
8010 class FatalConditionHandler {
8011 bool m_started =
false;
8016 void engage_platform();
8017 void disengage_platform();
8020 FatalConditionHandler();
8021 ~FatalConditionHandler();
8024 assert(!m_started &&
"Handler cannot be installed twice.");
8030 assert(m_started &&
"Handler cannot be uninstalled without being installed first");
8032 disengage_platform();
8037 class FatalConditionHandlerGuard {
8038 FatalConditionHandler* m_handler;
8040 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8041 m_handler(handler) {
8042 m_handler->engage();
8044 ~FatalConditionHandlerGuard() {
8045 m_handler->disengage();
8056 struct IMutableContext;
8060 class RunContext :
public IResultCapture,
public IRunner {
8063 RunContext( RunContext
const& ) =
delete;
8064 RunContext& operator =( RunContext
const& ) =
delete;
8066 explicit RunContext( IConfigPtr
const& _config, IStreamingReporterPtr&& reporter );
8068 ~RunContext()
override;
8070 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8071 void testGroupEnded( std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex, std::size_t groupsCount );
8073 Totals runTest(TestCase
const& testCase);
8075 IConfigPtr config()
const;
8076 IStreamingReporter& reporter()
const;
8082 ( AssertionInfo
const& info,
8083 ITransientExpression
const& expr,
8084 AssertionReaction& reaction )
override;
8086 ( AssertionInfo
const& info,
8087 ResultWas::OfType resultType,
8088 StringRef
const& message,
8089 AssertionReaction& reaction )
override;
8090 void handleUnexpectedExceptionNotThrown
8091 ( AssertionInfo
const& info,
8092 AssertionReaction& reaction )
override;
8093 void handleUnexpectedInflightException
8094 ( AssertionInfo
const& info,
8095 std::string
const& message,
8096 AssertionReaction& reaction )
override;
8097 void handleIncomplete
8098 ( AssertionInfo
const& info )
override;
8100 ( AssertionInfo
const &info,
8101 ResultWas::OfType resultType,
8102 AssertionReaction &reaction )
override;
8104 bool sectionStarted( SectionInfo
const& sectionInfo, Counts& assertions )
override;
8106 void sectionEnded( SectionEndInfo
const& endInfo )
override;
8107 void sectionEndedEarly( SectionEndInfo
const& endInfo )
override;
8109 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker&
override;
8111#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8112 void benchmarkPreparing( std::string
const& name )
override;
8113 void benchmarkStarting( BenchmarkInfo
const& info )
override;
8114 void benchmarkEnded( BenchmarkStats<>
const& stats )
override;
8115 void benchmarkFailed( std::string
const& error )
override;
8118 void pushScopedMessage( MessageInfo
const& message )
override;
8119 void popScopedMessage( MessageInfo
const& message )
override;
8121 void emplaceUnscopedMessage( MessageBuilder
const& builder )
override;
8123 std::string getCurrentTestName()
const override;
8125 const AssertionResult* getLastResult()
const override;
8127 void exceptionEarlyReported()
override;
8129 void handleFatalErrorCondition( StringRef message )
override;
8131 bool lastAssertionPassed()
override;
8133 void assertionPassed()
override;
8137 bool aborting() const final;
8141 void runCurrentTest( std::
string& redirectedCout, std::
string& redirectedCerr );
8142 void invokeActiveTestCase();
8144 void resetAssertionInfo();
8145 bool testForMissingAssertions( Counts& assertions );
8147 void assertionEnded( AssertionResult const& result );
8149 ( AssertionInfo const &info,
8150 ResultWas::OfType resultType,
8151 ITransientExpression const *expr,
8154 void populateReaction( AssertionReaction& reaction );
8158 void handleUnfinishedSections();
8160 TestRunInfo m_runInfo;
8161 IMutableContext& m_context;
8162 TestCase const* m_activeTestCase =
nullptr;
8163 ITracker* m_testCaseTracker =
nullptr;
8164 Option<AssertionResult> m_lastResult;
8166 IConfigPtr m_config;
8168 IStreamingReporterPtr m_reporter;
8169 std::vector<MessageInfo> m_messages;
8170 std::vector<ScopedMessage> m_messageScopes;
8171 AssertionInfo m_lastAssertionInfo;
8172 std::vector<SectionEndInfo> m_unfinishedSections;
8173 std::vector<ITracker*> m_activeSections;
8174 TrackerContext m_trackerContext;
8175 FatalConditionHandler m_fatalConditionhandler;
8176 bool m_lastAssertionPassed = false;
8177 bool m_shouldReportUnexpected = true;
8178 bool m_includeSuccessfulResults;
8181 void seedRng(IConfig const& config);
8182 unsigned int rngSeed();
8189 auto operator <<( std::ostream& os, ITransientExpression
const& expr ) -> std::ostream& {
8190 expr.streamReconstructedExpression( os );
8195 LazyExpression::LazyExpression(
bool isNegated )
8196 : m_isNegated( isNegated )
8199 LazyExpression::LazyExpression( LazyExpression
const& other ) : m_isNegated( other.m_isNegated ) {}
8201 LazyExpression::operator bool()
const {
8202 return m_transientExpression !=
nullptr;
8205 auto operator << ( std::ostream& os, LazyExpression
const& lazyExpr ) -> std::ostream& {
8206 if( lazyExpr.m_isNegated )
8210 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8211 os <<
"(" << *lazyExpr.m_transientExpression <<
")";
8213 os << *lazyExpr.m_transientExpression;
8216 os <<
"{** error - unchecked empty expression requested **}";
8221 AssertionHandler::AssertionHandler
8222 ( StringRef
const& macroName,
8223 SourceLineInfo
const& lineInfo,
8224 StringRef capturedExpression,
8225 ResultDisposition::Flags resultDisposition )
8226 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8227 m_resultCapture( getResultCapture() )
8230 void AssertionHandler::handleExpr( ITransientExpression
const& expr ) {
8231 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8233 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef
const& message) {
8234 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8237 auto AssertionHandler::allowThrows() const ->
bool {
8238 return getCurrentContext().getConfig()->allowThrows();
8241 void AssertionHandler::complete() {
8243 if( m_reaction.shouldDebugBreak ) {
8249 CATCH_BREAK_INTO_DEBUGGER();
8251 if (m_reaction.shouldThrow) {
8252#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8255 CATCH_ERROR(
"Test failure requires aborting test!" );
8259 void AssertionHandler::setCompleted() {
8263 void AssertionHandler::handleUnexpectedInflightException() {
8264 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8267 void AssertionHandler::handleExceptionThrownAsExpected() {
8268 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8270 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8271 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8274 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8275 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8278 void AssertionHandler::handleThrowingCallSkipped() {
8279 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8284 void handleExceptionMatchExpr( AssertionHandler& handler, std::string
const& str, StringRef
const& matcherString ) {
8285 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8293 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression
const & _lazyExpression):
8294 lazyExpression(_lazyExpression),
8295 resultType(_resultType) {}
8297 std::string AssertionResultData::reconstructExpression()
const {
8299 if( reconstructedExpression.empty() ) {
8300 if( lazyExpression ) {
8301 ReusableStringStream rss;
8302 rss << lazyExpression;
8303 reconstructedExpression = rss.str();
8306 return reconstructedExpression;
8309 AssertionResult::AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data )
8311 m_resultData( data )
8315 bool AssertionResult::succeeded()
const {
8316 return Catch::isOk( m_resultData.resultType );
8320 bool AssertionResult::isOk()
const {
8321 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8324 ResultWas::OfType AssertionResult::getResultType()
const {
8325 return m_resultData.resultType;
8328 bool AssertionResult::hasExpression()
const {
8329 return !m_info.capturedExpression.empty();
8332 bool AssertionResult::hasMessage()
const {
8333 return !m_resultData.message.empty();
8336 std::string AssertionResult::getExpression()
const {
8338 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8339 if (isFalseTest(m_info.resultDisposition)) {
8342 expr += m_info.capturedExpression;
8343 if (isFalseTest(m_info.resultDisposition)) {
8349 std::string AssertionResult::getExpressionInMacro()
const {
8351 if( m_info.macroName.empty() )
8352 expr =
static_cast<std::string
>(m_info.capturedExpression);
8354 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8355 expr += m_info.macroName;
8357 expr += m_info.capturedExpression;
8363 bool AssertionResult::hasExpandedExpression()
const {
8364 return hasExpression() && getExpandedExpression() != getExpression();
8367 std::string AssertionResult::getExpandedExpression()
const {
8368 std::string expr = m_resultData.reconstructExpression();
8374 std::string AssertionResult::getMessage()
const {
8375 return m_resultData.message;
8377 SourceLineInfo AssertionResult::getSourceInfo()
const {
8378 return m_info.lineInfo;
8381 StringRef AssertionResult::getTestMacroName()
const {
8382 return m_info.macroName;
8391 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8396 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher
const& matcher, StringRef
const& matcherString ) {
8397 std::string exceptionMessage = Catch::translateActiveException();
8398 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8399 handler.handleExpr( expr );
8411#ifdef CLARA_CONFIG_CONSOLE_WIDTH
8412#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8413#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8415#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8418#pragma clang diagnostic push
8419#pragma clang diagnostic ignored "-Wweak-vtables"
8420#pragma clang diagnostic ignored "-Wexit-time-destructors"
8421#pragma clang diagnostic ignored "-Wshadow"
8435#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8436#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8439#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8440#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8443#ifndef CLARA_CONFIG_OPTIONAL_TYPE
8445#if __has_include(<optional>) && __cplusplus >= 201703L
8447#define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8469#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8470#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8477inline auto isWhitespace(
char c) ->
bool {
8478 static std::string chars =
" \t\n\r";
8479 return chars.find(c) != std::string::npos;
8481inline auto isBreakableBefore(
char c) ->
bool {
8482 static std::string chars =
"[({<|";
8483 return chars.find(c) != std::string::npos;
8485inline auto isBreakableAfter(
char c) ->
bool {
8486 static std::string chars =
"])}>.,:;*+-=&/\\";
8487 return chars.find(c) != std::string::npos;
8493 std::vector<std::string> m_strings;
8494 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8495 size_t m_indent = 0;
8496 size_t m_initialIndent = std::string::npos;
8502 Column
const& m_column;
8503 size_t m_stringIndex = 0;
8508 bool m_suffix =
false;
8510 iterator(Column
const& column,
size_t stringIndex)
8512 m_stringIndex(stringIndex) {}
8514 auto line() const -> std::
string const& {
return m_column.m_strings[m_stringIndex]; }
8516 auto isBoundary(
size_t at)
const ->
bool {
8518 assert(at <= line().size());
8520 return at == line().size() ||
8521 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8522 isBreakableBefore(line()[at]) ||
8523 isBreakableAfter(line()[at - 1]);
8527 assert(m_stringIndex < m_column.m_strings.size());
8530 auto width = m_column.m_width - indent();
8532 if (line()[m_pos] ==
'\n') {
8535 while (m_end < line().size() && line()[m_end] !=
'\n')
8538 if (m_end < m_pos + width) {
8539 m_len = m_end - m_pos;
8542 while (len > 0 && !isBoundary(m_pos + len))
8544 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8556 auto indent() const ->
size_t {
8557 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8558 return initial == std::string::npos ? m_column.m_indent : initial;
8561 auto addIndentAndSuffix(std::string
const &plain)
const -> std::string {
8562 return std::string(indent(),
' ') + (m_suffix ? plain + "-" : plain);
8566 using difference_type = std::ptrdiff_t;
8567 using value_type = std::string;
8568 using pointer = value_type * ;
8569 using reference = value_type & ;
8570 using iterator_category = std::forward_iterator_tag;
8572 explicit iterator(Column
const& column) : m_column(column) {
8573 assert(m_column.m_width > m_column.m_indent);
8574 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8580 auto operator *() const -> std::
string {
8581 assert(m_stringIndex < m_column.m_strings.size());
8582 assert(m_pos <= m_end);
8583 return addIndentAndSuffix(line().substr(m_pos, m_len));
8586 auto operator ++() -> iterator& {
8588 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8591 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8594 if (m_pos == line().size()) {
8598 if (m_stringIndex < m_column.m_strings.size())
8602 auto operator ++(
int) -> iterator {
8603 iterator prev(*
this);
8608 auto operator ==(iterator
const& other)
const ->
bool {
8610 m_pos == other.m_pos &&
8611 m_stringIndex == other.m_stringIndex &&
8612 &m_column == &other.m_column;
8614 auto operator !=(iterator
const& other)
const ->
bool {
8615 return !operator==(other);
8618 using const_iterator = iterator;
8620 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8622 auto width(
size_t newWidth) -> Column& {
8623 assert(newWidth > 0);
8627 auto indent(
size_t newIndent) -> Column& {
8628 m_indent = newIndent;
8631 auto initialIndent(
size_t newIndent) -> Column& {
8632 m_initialIndent = newIndent;
8636 auto width() const ->
size_t {
return m_width; }
8637 auto begin() const -> iterator {
return iterator(*
this); }
8638 auto end() const -> iterator {
return { *
this, m_strings.size() }; }
8640 inline friend std::ostream&
operator << (std::ostream& os, Column
const& col) {
8642 for (
auto line : col) {
8652 auto operator + (Column
const& other)->Columns;
8654 auto toString() const -> std::
string {
8655 std::ostringstream oss;
8661class Spacer :
public Column {
8664 explicit Spacer(
size_t spaceWidth) : Column(
"") {
8670 std::vector<Column> m_columns;
8678 std::vector<Column>
const& m_columns;
8679 std::vector<Column::iterator> m_iterators;
8680 size_t m_activeIterators;
8682 iterator(Columns
const& columns, EndTag)
8683 : m_columns(columns.m_columns),
8684 m_activeIterators(0) {
8685 m_iterators.reserve(m_columns.size());
8687 for (
auto const& col : m_columns)
8688 m_iterators.push_back(col.end());
8692 using difference_type = std::ptrdiff_t;
8693 using value_type = std::string;
8694 using pointer = value_type * ;
8695 using reference = value_type & ;
8696 using iterator_category = std::forward_iterator_tag;
8698 explicit iterator(Columns
const& columns)
8699 : m_columns(columns.m_columns),
8700 m_activeIterators(m_columns.size()) {
8701 m_iterators.reserve(m_columns.size());
8703 for (
auto const& col : m_columns)
8704 m_iterators.push_back(col.begin());
8707 auto operator ==(iterator
const& other)
const ->
bool {
8708 return m_iterators == other.m_iterators;
8710 auto operator !=(iterator
const& other)
const ->
bool {
8711 return m_iterators != other.m_iterators;
8713 auto operator *() const -> std::
string {
8714 std::string row, padding;
8716 for (
size_t i = 0; i < m_columns.size(); ++i) {
8717 auto width = m_columns[i].width();
8718 if (m_iterators[i] != m_columns[i].end()) {
8719 std::string col = *m_iterators[i];
8720 row += padding + col;
8721 if (col.size() < width)
8722 padding = std::string(width - col.size(),
' ');
8726 padding += std::string(width, ' ');
8731 auto operator ++() -> iterator& {
8732 for (
size_t i = 0; i < m_columns.size(); ++i) {
8733 if (m_iterators[i] != m_columns[i].end())
8738 auto operator ++(
int) -> iterator {
8739 iterator prev(*
this);
8744 using const_iterator = iterator;
8746 auto begin() const -> iterator {
return iterator(*
this); }
8747 auto end() const -> iterator {
return { *
this, iterator::EndTag() }; }
8749 auto operator += (Column
const& col) -> Columns& {
8750 m_columns.push_back(col);
8753 auto operator + (Column
const& col) -> Columns {
8754 Columns combined = *
this;
8759 inline friend std::ostream&
operator << (std::ostream& os, Columns
const& cols) {
8762 for (
auto line : cols) {
8772 auto toString() const -> std::
string {
8773 std::ostringstream oss;
8779inline auto Column::operator + (Column
const& other) -> Columns {
8799#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8800#define CATCH_PLATFORM_WINDOWS
8803namespace Catch {
namespace clara {
8807 template<
typename L>
8808 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8810 template<
typename ClassT,
typename ReturnT,
typename... Args>
8811 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8812 static const bool isValid =
false;
8815 template<
typename ClassT,
typename ReturnT,
typename ArgT>
8816 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8817 static const bool isValid =
true;
8818 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8819 using ReturnType = ReturnT;
8827 std::string m_exeName;
8828 std::vector<std::string> m_args;
8831 Args(
int argc,
char const*
const* argv )
8832 : m_exeName(argv[0]),
8833 m_args(argv + 1, argv + argc) {}
8835 Args( std::initializer_list<std::string> args )
8836 : m_exeName( *args.begin() ),
8837 m_args( args.begin()+1, args.end() )
8840 auto exeName() const -> std::
string {
8847 enum class TokenType {
8855 inline auto isOptPrefix(
char c ) ->
bool {
8857#ifdef CATCH_PLATFORM_WINDOWS
8865 using Iterator = std::vector<std::string>::const_iterator;
8868 std::vector<Token> m_tokenBuffer;
8871 m_tokenBuffer.resize( 0 );
8874 while( it != itEnd && it->empty() )
8878 auto const &next = *it;
8879 if( isOptPrefix( next[0] ) ) {
8880 auto delimiterPos = next.find_first_of(
" :=" );
8881 if( delimiterPos != std::string::npos ) {
8882 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8883 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8885 if( next[1] !=
'-' && next.size() > 2 ) {
8886 std::string opt =
"- ";
8887 for(
size_t i = 1; i < next.size(); ++i ) {
8889 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8892 m_tokenBuffer.push_back( { TokenType::Option, next } );
8896 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8902 explicit TokenStream( Args
const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8904 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8908 explicit operator bool()
const {
8909 return !m_tokenBuffer.empty() || it != itEnd;
8912 auto count() const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8914 auto operator*() const -> Token {
8915 assert( !m_tokenBuffer.empty() );
8916 return m_tokenBuffer.front();
8919 auto operator->() const -> Token const * {
8920 assert( !m_tokenBuffer.empty() );
8921 return &m_tokenBuffer.front();
8924 auto operator++() -> TokenStream & {
8925 if( m_tokenBuffer.size() >= 2 ) {
8926 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8939 Ok, LogicError, RuntimeError
8943 ResultBase( Type type ) : m_type( type ) {}
8944 virtual ~ResultBase() =
default;
8946 virtual void enforceOk()
const = 0;
8951 template<
typename T>
8952 class ResultValueBase :
public ResultBase {
8954 auto value() const -> T const & {
8960 ResultValueBase( Type type ) : ResultBase( type ) {}
8962 ResultValueBase( ResultValueBase
const &other ) : ResultBase( other ) {
8963 if( m_type == ResultBase::Ok )
8964 new( &m_value ) T( other.m_value );
8967 ResultValueBase( Type, T
const &value ) : ResultBase( Ok ) {
8968 new( &m_value ) T( value );
8971 auto operator=( ResultValueBase
const &other ) -> ResultValueBase & {
8972 if( m_type == ResultBase::Ok )
8974 ResultBase::operator=(other);
8975 if( m_type == ResultBase::Ok )
8976 new( &m_value ) T( other.m_value );
8980 ~ResultValueBase()
override {
8991 class ResultValueBase<void> :
public ResultBase {
8993 using ResultBase::ResultBase;
8996 template<
typename T =
void>
8997 class BasicResult :
public ResultValueBase<T> {
8999 template<
typename U>
9000 explicit BasicResult( BasicResult<U>
const &other )
9001 : ResultValueBase<T>( other.type() ),
9002 m_errorMessage( other.errorMessage() )
9004 assert( type() != ResultBase::Ok );
9007 template<
typename U>
9008 static auto ok( U
const &value ) -> BasicResult {
return { ResultBase::Ok, value }; }
9009 static auto ok() -> BasicResult {
return { ResultBase::Ok }; }
9010 static auto logicError( std::string
const &message ) -> BasicResult {
return { ResultBase::LogicError, message }; }
9011 static auto runtimeError( std::string
const &message ) -> BasicResult {
return { ResultBase::RuntimeError, message }; }
9013 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9014 auto type() const -> ResultBase::Type {
return m_type; }
9015 auto errorMessage() const -> std::
string {
return m_errorMessage; }
9018 void enforceOk()
const override {
9022 assert( m_type != ResultBase::LogicError );
9023 assert( m_type != ResultBase::RuntimeError );
9024 if( m_type != ResultBase::Ok )
9028 std::string m_errorMessage;
9030 BasicResult( ResultBase::Type type, std::string
const &message )
9031 : ResultValueBase<T>(type),
9032 m_errorMessage(message)
9034 assert( m_type != ResultBase::Ok );
9037 using ResultValueBase<T>::ResultValueBase;
9038 using ResultBase::m_type;
9041 enum class ParseResultType {
9042 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9048 ParseState( ParseResultType type, TokenStream
const &remainingTokens )
9050 m_remainingTokens( remainingTokens )
9053 auto type() const -> ParseResultType {
return m_type; }
9054 auto remainingTokens() const -> TokenStream {
return m_remainingTokens; }
9057 ParseResultType m_type;
9058 TokenStream m_remainingTokens;
9061 using Result = BasicResult<void>;
9062 using ParserResult = BasicResult<ParseResultType>;
9063 using InternalParseResult = BasicResult<ParseState>;
9065 struct HelpColumns {
9070 template<
typename T>
9071 inline auto convertInto( std::string
const &source, T& target ) -> ParserResult {
9072 std::stringstream ss;
9076 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type" );
9078 return ParserResult::ok( ParseResultType::Matched );
9080 inline auto convertInto( std::string
const &source, std::string& target ) -> ParserResult {
9082 return ParserResult::ok( ParseResultType::Matched );
9084 inline auto convertInto( std::string
const &source,
bool &target ) -> ParserResult {
9085 std::string srcLC = source;
9086 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), [](
unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9087 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9089 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9092 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" + source +
"'" );
9093 return ParserResult::ok( ParseResultType::Matched );
9095#ifdef CLARA_CONFIG_OPTIONAL_TYPE
9096 template<
typename T>
9097 inline auto convertInto( std::string
const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9099 auto result = convertInto( source, temp );
9101 target = std::move(temp);
9106 struct NonCopyable {
9107 NonCopyable() =
default;
9108 NonCopyable( NonCopyable
const & ) =
delete;
9109 NonCopyable( NonCopyable && ) =
delete;
9110 NonCopyable &operator=( NonCopyable
const & ) =
delete;
9111 NonCopyable &operator=( NonCopyable && ) =
delete;
9114 struct BoundRef : NonCopyable {
9115 virtual ~BoundRef() =
default;
9116 virtual auto isContainer() const ->
bool {
return false; }
9117 virtual auto isFlag() const ->
bool {
return false; }
9119 struct BoundValueRefBase : BoundRef {
9120 virtual auto setValue( std::string
const &arg ) -> ParserResult = 0;
9122 struct BoundFlagRefBase : BoundRef {
9123 virtual auto setFlag(
bool flag ) -> ParserResult = 0;
9124 virtual auto isFlag() const ->
bool {
return true; }
9127 template<
typename T>
9128 struct BoundValueRef : BoundValueRefBase {
9131 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9133 auto setValue( std::string
const &arg ) -> ParserResult
override {
9134 return convertInto( arg, m_ref );
9138 template<
typename T>
9139 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9140 std::vector<T> &m_ref;
9142 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9144 auto isContainer() const ->
bool override {
return true; }
9146 auto setValue( std::string
const &arg ) -> ParserResult
override {
9148 auto result = convertInto( arg, temp );
9150 m_ref.push_back( temp );
9155 struct BoundFlagRef : BoundFlagRefBase {
9158 explicit BoundFlagRef(
bool &ref ) : m_ref( ref ) {}
9160 auto setFlag(
bool flag ) -> ParserResult
override {
9162 return ParserResult::ok( ParseResultType::Matched );
9166 template<
typename ReturnType>
9167 struct LambdaInvoker {
9168 static_assert( std::is_same<ReturnType, ParserResult>::value,
"Lambda must return void or clara::ParserResult" );
9170 template<
typename L,
typename ArgType>
9171 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9172 return lambda( arg );
9177 struct LambdaInvoker<void> {
9178 template<
typename L,
typename ArgType>
9179 static auto invoke( L
const &lambda, ArgType
const &arg ) -> ParserResult {
9181 return ParserResult::ok( ParseResultType::Matched );
9185 template<
typename ArgType,
typename L>
9186 inline auto invokeLambda( L
const &lambda, std::string
const &arg ) -> ParserResult {
9188 auto result = convertInto( arg, temp );
9191 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9194 template<
typename L>
9195 struct BoundLambda : BoundValueRefBase {
9198 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9199 explicit BoundLambda( L
const &lambda ) : m_lambda( lambda ) {}
9201 auto setValue( std::string
const &arg ) -> ParserResult
override {
9202 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9206 template<
typename L>
9207 struct BoundFlagLambda : BoundFlagRefBase {
9210 static_assert( UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument" );
9211 static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType,
bool>::value,
"flags must be boolean" );
9213 explicit BoundFlagLambda( L
const &lambda ) : m_lambda( lambda ) {}
9215 auto setFlag(
bool flag ) -> ParserResult
override {
9216 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9220 enum class Optionality { Optional, Required };
9226 virtual ~ParserBase() =
default;
9227 virtual auto validate() const -> Result {
return Result::ok(); }
9228 virtual auto parse( std::string
const& exeName, TokenStream
const &tokens)
const -> InternalParseResult = 0;
9229 virtual auto cardinality() const ->
size_t {
return 1; }
9231 auto parse( Args
const &args )
const -> InternalParseResult {
9232 return parse( args.exeName(), TokenStream( args ) );
9236 template<
typename DerivedT>
9237 class ComposableParserImpl :
public ParserBase {
9239 template<
typename T>
9240 auto operator|( T
const &other )
const -> Parser;
9242 template<
typename T>
9243 auto operator+( T
const &other )
const -> Parser;
9247 template<
typename DerivedT>
9248 class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9250 Optionality m_optionality = Optionality::Optional;
9251 std::shared_ptr<BoundRef> m_ref;
9253 std::string m_description;
9255 explicit ParserRefImpl( std::shared_ptr<BoundRef>
const &ref ) : m_ref( ref ) {}
9258 template<
typename T>
9259 ParserRefImpl( T &ref, std::string
const &hint )
9260 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9264 template<
typename LambdaT>
9265 ParserRefImpl( LambdaT
const &ref, std::string
const &hint )
9266 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9270 auto operator()( std::string
const &description ) -> DerivedT & {
9271 m_description = description;
9272 return static_cast<DerivedT &
>( *this );
9275 auto optional() -> DerivedT & {
9276 m_optionality = Optionality::Optional;
9277 return static_cast<DerivedT &
>( *this );
9280 auto required() -> DerivedT & {
9281 m_optionality = Optionality::Required;
9282 return static_cast<DerivedT &
>( *this );
9285 auto isOptional() const ->
bool {
9286 return m_optionality == Optionality::Optional;
9289 auto cardinality() const ->
size_t override {
9290 if( m_ref->isContainer() )
9296 auto hint() const -> std::
string {
return m_hint; }
9299 class ExeName :
public ComposableParserImpl<ExeName> {
9300 std::shared_ptr<std::string> m_name;
9301 std::shared_ptr<BoundValueRefBase> m_ref;
9303 template<
typename LambdaT>
9304 static auto makeRef(LambdaT
const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9305 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9309 ExeName() : m_name( std::make_shared<std::
string>(
"<executable>" ) ) {}
9311 explicit ExeName( std::string &ref ) : ExeName() {
9312 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9315 template<
typename LambdaT>
9316 explicit ExeName( LambdaT
const& lambda ) : ExeName() {
9317 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9321 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9322 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9325 auto name() const -> std::
string {
return *m_name; }
9326 auto set( std::string
const& newName ) -> ParserResult {
9328 auto lastSlash = newName.find_last_of(
"\\/" );
9329 auto filename = ( lastSlash == std::string::npos )
9331 : newName.substr( lastSlash+1 );
9335 return m_ref->setValue( filename );
9337 return ParserResult::ok( ParseResultType::Matched );
9341 class Arg :
public ParserRefImpl<Arg> {
9343 using ParserRefImpl::ParserRefImpl;
9345 auto parse( std::string
const &, TokenStream
const &tokens )
const -> InternalParseResult
override {
9346 auto validationResult = validate();
9347 if( !validationResult )
9348 return InternalParseResult( validationResult );
9350 auto remainingTokens = tokens;
9351 auto const &token = *remainingTokens;
9352 if( token.type != TokenType::Argument )
9353 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9355 assert( !m_ref->isFlag() );
9356 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9358 auto result = valueRef->setValue( remainingTokens->token );
9360 return InternalParseResult( result );
9362 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9366 inline auto normaliseOpt( std::string
const &optName ) -> std::string {
9367#ifdef CATCH_PLATFORM_WINDOWS
9368 if( optName[0] ==
'/' )
9369 return "-" + optName.substr( 1 );
9375 class Opt :
public ParserRefImpl<Opt> {
9377 std::vector<std::string> m_optNames;
9380 template<
typename LambdaT>
9381 explicit Opt( LambdaT
const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9383 explicit Opt(
bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9385 template<
typename LambdaT>
9386 Opt( LambdaT
const &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9388 template<
typename T>
9389 Opt( T &ref, std::string
const &hint ) : ParserRefImpl( ref, hint ) {}
9391 auto operator[]( std::string
const &optName ) -> Opt & {
9392 m_optNames.push_back( optName );
9396 auto getHelpColumns() const -> std::vector<HelpColumns> {
9397 std::ostringstream oss;
9399 for(
auto const &opt : m_optNames ) {
9406 if( !m_hint.empty() )
9407 oss <<
" <" << m_hint <<
">";
9408 return { { oss.str(), m_description } };
9411 auto isMatch( std::string
const &optToken )
const ->
bool {
9412 auto normalisedToken = normaliseOpt( optToken );
9413 for(
auto const &name : m_optNames ) {
9414 if( normaliseOpt( name ) == normalisedToken )
9420 using ParserBase::parse;
9422 auto parse( std::string
const&, TokenStream
const &tokens )
const -> InternalParseResult
override {
9423 auto validationResult = validate();
9424 if( !validationResult )
9425 return InternalParseResult( validationResult );
9427 auto remainingTokens = tokens;
9428 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9429 auto const &token = *remainingTokens;
9430 if( isMatch(token.token ) ) {
9431 if( m_ref->isFlag() ) {
9432 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>( m_ref.get() );
9433 auto result = flagRef->setFlag(
true );
9435 return InternalParseResult( result );
9436 if( result.value() == ParseResultType::ShortCircuitAll )
9437 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9439 auto valueRef =
static_cast<detail::BoundValueRefBase*
>( m_ref.get() );
9441 if( !remainingTokens )
9442 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9443 auto const &argToken = *remainingTokens;
9444 if( argToken.type != TokenType::Argument )
9445 return InternalParseResult::runtimeError(
"Expected argument following " + token.token );
9446 auto result = valueRef->setValue( argToken.token );
9448 return InternalParseResult( result );
9449 if( result.value() == ParseResultType::ShortCircuitAll )
9450 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9452 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9455 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9458 auto validate() const -> Result
override {
9459 if( m_optNames.empty() )
9460 return Result::logicError(
"No options supplied to Opt" );
9461 for(
auto const &name : m_optNames ) {
9463 return Result::logicError(
"Option name cannot be empty" );
9464#ifdef CATCH_PLATFORM_WINDOWS
9465 if( name[0] !=
'-' && name[0] !=
'/' )
9466 return Result::logicError(
"Option name must begin with '-' or '/'" );
9468 if( name[0] !=
'-' )
9469 return Result::logicError(
"Option name must begin with '-'" );
9472 return ParserRefImpl::validate();
9477 Help(
bool &showHelpFlag )
9478 : Opt([&]( bool flag ) {
9479 showHelpFlag = flag;
9480 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9483 static_cast<Opt &
>( *this )
9484 (
"display usage information")
9485 [
"-?"][
"-h"][
"--help"]
9490 struct Parser : ParserBase {
9492 mutable ExeName m_exeName;
9493 std::vector<Opt> m_options;
9494 std::vector<Arg> m_args;
9496 auto operator|=( ExeName
const &exeName ) -> Parser & {
9497 m_exeName = exeName;
9501 auto operator|=( Arg
const &arg ) -> Parser & {
9502 m_args.push_back(arg);
9506 auto operator|=( Opt
const &opt ) -> Parser & {
9507 m_options.push_back(opt);
9511 auto operator|=( Parser
const &other ) -> Parser & {
9512 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9513 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9517 template<
typename T>
9518 auto operator|( T
const &other )
const -> Parser {
9519 return Parser( *
this ) |= other;
9523 template<
typename T>
9524 auto operator+=( T
const &other ) -> Parser & {
return operator|=( other ); }
9525 template<
typename T>
9526 auto operator+( T
const &other )
const -> Parser {
return operator|( other ); }
9528 auto getHelpColumns() const -> std::vector<HelpColumns> {
9529 std::vector<HelpColumns> cols;
9530 for (
auto const &o : m_options) {
9531 auto childCols = o.getHelpColumns();
9532 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9537 void writeToStream( std::ostream &os )
const {
9538 if (!m_exeName.name().empty()) {
9539 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9540 bool required =
true, first =
true;
9541 for(
auto const &arg : m_args ) {
9546 if( arg.isOptional() && required ) {
9550 os <<
"<" << arg.hint() <<
">";
9551 if( arg.cardinality() == 0 )
9556 if( !m_options.empty() )
9558 os <<
"\n\nwhere options are:" << std::endl;
9561 auto rows = getHelpColumns();
9562 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9563 size_t optWidth = 0;
9564 for(
auto const &cols : rows )
9565 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9567 optWidth = (std::min)(optWidth, consoleWidth/2);
9569 for(
auto const &cols : rows ) {
9571 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9572 TextFlow::Spacer(4) +
9573 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9574 os << row << std::endl;
9578 friend auto operator<<( std::ostream &os, Parser
const &parser ) -> std::ostream& {
9579 parser.writeToStream( os );
9583 auto validate() const -> Result
override {
9584 for(
auto const &opt : m_options ) {
9585 auto result = opt.validate();
9589 for(
auto const &arg : m_args ) {
9590 auto result = arg.validate();
9594 return Result::ok();
9597 using ParserBase::parse;
9599 auto parse( std::string
const& exeName, TokenStream
const &tokens )
const -> InternalParseResult
override {
9602 ParserBase
const* parser =
nullptr;
9605 const size_t totalParsers = m_options.size() + m_args.size();
9606 assert( totalParsers < 512 );
9608 ParserInfo parseInfos[512];
9612 for (
auto const &opt : m_options) parseInfos[i++].parser = &opt;
9613 for (
auto const &arg : m_args) parseInfos[i++].parser = &arg;
9616 m_exeName.set( exeName );
9618 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9619 while( result.value().remainingTokens() ) {
9620 bool tokenParsed =
false;
9622 for(
size_t i = 0; i < totalParsers; ++i ) {
9623 auto& parseInfo = parseInfos[i];
9624 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9625 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9628 if (result.value().type() != ParseResultType::NoMatch) {
9636 if( result.value().type() == ParseResultType::ShortCircuitAll )
9639 return InternalParseResult::runtimeError(
"Unrecognised token: " + result.value().remainingTokens()->token );
9646 template<
typename DerivedT>
9647 template<
typename T>
9648 auto ComposableParserImpl<DerivedT>::operator|( T
const &other )
const -> Parser {
9649 return Parser() |
static_cast<DerivedT
const &
>( *this ) | other;
9654using detail::Parser;
9666using detail::ExeName;
9672using detail::ParseResultType;
9675using detail::ParserResult;
9681#pragma clang diagnostic pop
9685#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9686#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9687#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9693 clara::Parser makeCommandLineParser( ConfigData& config );
9703 clara::Parser makeCommandLineParser( ConfigData& config ) {
9705 using namespace clara;
9707 auto const setWarning = [&]( std::string
const&
warning ) {
9708 auto warningSet = [&]() {
9709 if( warning ==
"NoAssertions" )
9710 return WarnAbout::NoAssertions;
9712 if ( warning ==
"NoTests" )
9713 return WarnAbout::NoTests;
9715 return WarnAbout::Nothing;
9718 if (warningSet == WarnAbout::Nothing)
9719 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'" );
9720 config.warnings =
static_cast<WarnAbout::What
>( config.warnings | warningSet );
9721 return ParserResult::ok( ParseResultType::Matched );
9723 auto const loadTestNamesFromFile = [&]( std::string
const& filename ) {
9724 std::ifstream f( filename.c_str() );
9726 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'" );
9729 while( std::getline( f, line ) ) {
9731 if( !line.empty() && !startsWith( line,
'#' ) ) {
9732 if( !startsWith( line,
'"' ) )
9733 line =
'"' + line + '"';
9734 config.testsOrTags.push_back( line );
9735 config.testsOrTags.emplace_back(
"," );
9739 if(!config.testsOrTags.empty())
9740 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9742 return ParserResult::ok( ParseResultType::Matched );
9744 auto const setTestOrder = [&]( std::string
const& order ) {
9745 if( startsWith(
"declared", order ) )
9746 config.runOrder = RunTests::InDeclarationOrder;
9747 else if( startsWith(
"lexical", order ) )
9748 config.runOrder = RunTests::InLexicographicalOrder;
9749 else if( startsWith(
"random", order ) )
9750 config.runOrder = RunTests::InRandomOrder;
9752 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'" );
9753 return ParserResult::ok( ParseResultType::Matched );
9755 auto const setRngSeed = [&]( std::string
const& seed ) {
9756 if( seed !=
"time" )
9757 return clara::detail::convertInto( seed, config.rngSeed );
9758 config.rngSeed =
static_cast<unsigned int>( std::time(
nullptr) );
9759 return ParserResult::ok( ParseResultType::Matched );
9761 auto const setColourUsage = [&]( std::string
const& useColour ) {
9762 auto mode = toLower( useColour );
9765 config.useColour = UseColour::Yes;
9766 else if( mode ==
"no" )
9767 config.useColour = UseColour::No;
9768 else if( mode ==
"auto" )
9769 config.useColour = UseColour::Auto;
9771 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" + useColour +
"' not recognised" );
9772 return ParserResult::ok( ParseResultType::Matched );
9774 auto const setWaitForKeypress = [&]( std::string
const& keypress ) {
9775 auto keypressLc = toLower( keypress );
9776 if (keypressLc ==
"never")
9777 config.waitForKeypress = WaitForKeypress::Never;
9778 else if( keypressLc ==
"start" )
9779 config.waitForKeypress = WaitForKeypress::BeforeStart;
9780 else if( keypressLc ==
"exit" )
9781 config.waitForKeypress = WaitForKeypress::BeforeExit;
9782 else if( keypressLc ==
"both" )
9783 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9785 return ParserResult::runtimeError(
"keypress argument must be one of: never, start, exit or both. '" + keypress +
"' not recognised" );
9786 return ParserResult::ok( ParseResultType::Matched );
9788 auto const setVerbosity = [&]( std::string
const& verbosity ) {
9789 auto lcVerbosity = toLower( verbosity );
9790 if( lcVerbosity ==
"quiet" )
9791 config.verbosity = Verbosity::Quiet;
9792 else if( lcVerbosity ==
"normal" )
9793 config.verbosity = Verbosity::Normal;
9794 else if( lcVerbosity ==
"high" )
9795 config.verbosity = Verbosity::High;
9797 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'" );
9798 return ParserResult::ok( ParseResultType::Matched );
9800 auto const setReporter = [&]( std::string
const& reporter ) {
9801 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
9803 auto lcReporter = toLower( reporter );
9804 auto result = factories.find( lcReporter );
9806 if( factories.end() != result )
9807 config.reporterName = lcReporter;
9809 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
"'. Check available with --list-reporters" );
9810 return ParserResult::ok( ParseResultType::Matched );
9814 = ExeName( config.processName )
9815 |
Help( config.showHelp )
9816 | Opt( config.listTests )
9817 ["-l"]["--list-tests"]
9818 (
"list all/matching test cases" )
9819 | Opt( config.listTags )
9820 ["-t"]["--list-tags"]
9821 (
"list all/matching tags" )
9822 | Opt( config.showSuccessfulTests )
9824 (
"include successful tests in output" )
9825 | Opt( config.shouldDebugBreak )
9827 (
"break into debugger on failure" )
9828 | Opt( config.noThrow )
9830 (
"skip exception tests" )
9831 | Opt( config.showInvisibles )
9832 ["-i"]["--invisibles"]
9833 (
"show invisibles (tabs, newlines)" )
9834 | Opt( config.outputFilename,
"filename" )
9836 (
"output filename" )
9837 | Opt( setReporter,
"name" )
9838 ["-r"]["--reporter"]
9839 (
"reporter to use (defaults to console)" )
9840 | Opt( config.name,
"name" )
9843 | Opt( [&](
bool ){ config.abortAfter = 1; } )
9845 (
"abort at first failure" )
9846 | Opt( [&](
int x ){ config.abortAfter = x; },
"no. failures" )
9848 (
"abort after x failures" )
9849 | Opt( setWarning,
"warning name" )
9851 (
"enable warnings" )
9852 | Opt( [&](
bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; },
"yes|no" )
9853 [
"-d"][
"--durations"]
9854 (
"show test durations" )
9855 | Opt( config.minDuration,
"seconds" )
9856 ["-D"]["--min-duration"]
9857 (
"show test durations for tests taking at least the given number of seconds" )
9858 | Opt( loadTestNamesFromFile,
"filename" )
9859 ["-f"]["--input-file"]
9860 (
"load test names to run from a file" )
9861 | Opt( config.filenamesAsTags )
9862 ["-#"]["--filenames-as-tags"]
9863 (
"adds a tag for the filename" )
9864 | Opt( config.sectionsToRun,
"section name" )
9866 (
"specify section to run" )
9867 | Opt( setVerbosity,
"quiet|normal|high" )
9868 ["-v"]["--verbosity"]
9869 (
"set output verbosity" )
9870 | Opt( config.listTestNamesOnly )
9871 ["--list-test-names-only"]
9872 (
"list all/matching test cases names only" )
9873 | Opt( config.listReporters )
9874 ["--list-reporters"]
9875 (
"list all reporters" )
9876 | Opt( setTestOrder,
"decl|lex|rand" )
9878 (
"test case order (defaults to decl)" )
9879 | Opt( setRngSeed,
"'time'|number" )
9881 (
"set a specific seed for random numbers" )
9882 | Opt( setColourUsage,
"yes|no" )
9884 (
"should output be colourised" )
9885 | Opt( config.libIdentify )
9887 (
"report name and version according to libidentify standard" )
9888 | Opt( setWaitForKeypress,
"never|start|exit|both" )
9889 ["--wait-for-keypress"]
9890 (
"waits for a keypress before exiting" )
9891 | Opt( config.benchmarkSamples,
"samples" )
9892 ["--benchmark-samples"]
9893 (
"number of samples to collect (default: 100)" )
9894 | Opt( config.benchmarkResamples,
"resamples" )
9895 ["--benchmark-resamples"]
9896 (
"number of resamples for the bootstrap (default: 100000)" )
9897 | Opt( config.benchmarkConfidenceInterval,
"confidence interval" )
9898 ["--benchmark-confidence-interval"]
9899 (
"confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9900 | Opt( config.benchmarkNoAnalysis )
9901 ["--benchmark-no-analysis"]
9902 (
"perform only measurements; do not perform any analysis" )
9903 | Opt( config.benchmarkWarmupTime,
"benchmarkWarmupTime" )
9904 ["--benchmark-warmup-time"]
9905 (
"amount of time in milliseconds spent on warming up each test (default: 100)" )
9906 | Arg( config.testsOrTags,
"test name|pattern|tags" )
9907 (
"which test or tests to use" );
9921 bool SourceLineInfo::operator == ( SourceLineInfo
const& other )
const noexcept {
9922 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9924 bool SourceLineInfo::operator < ( SourceLineInfo
const& other )
const noexcept {
9927 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9930 std::ostream& operator << ( std::ostream& os, SourceLineInfo
const& info ) {
9932 os <<
info.file <<
'(' <<
info.line <<
')';
9934 os <<
info.file <<
':' <<
info.line;
9939 std::string StreamEndStop::operator+()
const {
9940 return std::string();
9943 NonCopyable::NonCopyable() =
default;
9944 NonCopyable::~NonCopyable() =
default;
9952 Config::Config( ConfigData
const& data )
9954 m_stream( openStream() )
9960 for (
auto& elem : m_data.testsOrTags) {
9963 for (
auto& elem : m_data.sectionsToRun) {
9967 TestSpecParser parser(ITagAliasRegistry::get());
9968 if (!m_data.testsOrTags.empty()) {
9969 m_hasTestFilters =
true;
9970 for (
auto const& testOrTags : m_data.testsOrTags) {
9971 parser.parse(testOrTags);
9974 m_testSpec = parser.testSpec();
9977 std::string
const& Config::getFilename()
const {
9978 return m_data.outputFilename ;
9981 bool Config::listTests()
const {
return m_data.listTests; }
9982 bool Config::listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
9983 bool Config::listTags()
const {
return m_data.listTags; }
9984 bool Config::listReporters()
const {
return m_data.listReporters; }
9986 std::string Config::getProcessName()
const {
return m_data.processName; }
9987 std::string
const& Config::getReporterName()
const {
return m_data.reporterName; }
9989 std::vector<std::string>
const& Config::getTestsOrTags()
const {
return m_data.testsOrTags; }
9990 std::vector<std::string>
const& Config::getSectionsToRun()
const {
return m_data.sectionsToRun; }
9992 TestSpec
const& Config::testSpec()
const {
return m_testSpec; }
9993 bool Config::hasTestFilters()
const {
return m_hasTestFilters; }
9995 bool Config::showHelp()
const {
return m_data.showHelp; }
9998 bool Config::allowThrows()
const {
return !m_data.noThrow; }
9999 std::ostream& Config::stream()
const {
return m_stream->stream(); }
10000 std::string Config::name()
const {
return m_data.name.empty() ? m_data.processName : m_data.name; }
10001 bool Config::includeSuccessfulResults()
const {
return m_data.showSuccessfulTests; }
10002 bool Config::warnAboutMissingAssertions()
const {
return !!(m_data.warnings & WarnAbout::NoAssertions); }
10003 bool Config::warnAboutNoTests()
const {
return !!(m_data.warnings & WarnAbout::NoTests); }
10004 ShowDurations::OrNot Config::showDurations()
const {
return m_data.showDurations; }
10005 double Config::minDuration()
const {
return m_data.minDuration; }
10006 RunTests::InWhatOrder Config::runOrder()
const {
return m_data.runOrder; }
10007 unsigned int Config::rngSeed()
const {
return m_data.rngSeed; }
10008 UseColour::YesOrNo Config::useColour()
const {
return m_data.useColour; }
10009 bool Config::shouldDebugBreak()
const {
return m_data.shouldDebugBreak; }
10010 int Config::abortAfter()
const {
return m_data.abortAfter; }
10011 bool Config::showInvisibles()
const {
return m_data.showInvisibles; }
10012 Verbosity Config::verbosity()
const {
return m_data.verbosity; }
10014 bool Config::benchmarkNoAnalysis()
const {
return m_data.benchmarkNoAnalysis; }
10015 int Config::benchmarkSamples()
const {
return m_data.benchmarkSamples; }
10016 double Config::benchmarkConfidenceInterval()
const {
return m_data.benchmarkConfidenceInterval; }
10017 unsigned int Config::benchmarkResamples()
const {
return m_data.benchmarkResamples; }
10018 std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10020 IStream
const* Config::openStream() {
10021 return Catch::makeStream(m_data.outputFilename);
10028#if defined(__clang__)
10029# pragma clang diagnostic push
10030# pragma clang diagnostic ignored "-Wexit-time-destructors"
10051#if defined(CATCH_PLATFORM_WINDOWS)
10053#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10054# define CATCH_DEFINED_NOMINMAX
10057#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10058# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10059# define WIN32_LEAN_AND_MEAN
10065#include <windows.h>
10068#ifdef CATCH_DEFINED_NOMINMAX
10071#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10072# undef WIN32_LEAN_AND_MEAN
10083 struct IColourImpl {
10084 virtual ~IColourImpl() =
default;
10085 virtual void use( Colour::Code _colourCode ) = 0;
10088 struct NoColourImpl : IColourImpl {
10089 void use( Colour::Code )
override {}
10091 static IColourImpl* instance() {
10092 static NoColourImpl s_instance;
10093 return &s_instance;
10100#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10101# ifdef CATCH_PLATFORM_WINDOWS
10102# define CATCH_CONFIG_COLOUR_WINDOWS
10104# define CATCH_CONFIG_COLOUR_ANSI
10108#if defined ( CATCH_CONFIG_COLOUR_WINDOWS )
10113 class Win32ColourImpl :
public IColourImpl {
10115 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10117 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10118 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10119 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10120 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10123 void use( Colour::Code _colourCode )
override {
10124 switch( _colourCode ) {
10125 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
10126 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10127 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
10128 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
10129 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
10130 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10131 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10132 case Colour::Grey:
return setTextAttribute( 0 );
10134 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
10135 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10136 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10137 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10138 case Colour::BrightYellow:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10140 case Colour::Bright: CATCH_INTERNAL_ERROR(
"not a colour" );
10143 CATCH_ERROR(
"Unknown colour requested" );
10148 void setTextAttribute( WORD _textAttribute ) {
10149 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10151 HANDLE stdoutHandle;
10152 WORD originalForegroundAttributes;
10153 WORD originalBackgroundAttributes;
10156 IColourImpl* platformColourInstance() {
10157 static Win32ColourImpl s_instance;
10159 IConfigPtr config = getCurrentContext().getConfig();
10160 UseColour::YesOrNo colourMode = config
10161 ? config->useColour()
10163 if( colourMode == UseColour::Auto )
10164 colourMode = UseColour::Yes;
10165 return colourMode == UseColour::Yes
10167 : NoColourImpl::instance();
10173#elif defined( CATCH_CONFIG_COLOUR_ANSI )
10184 class PosixColourImpl :
public IColourImpl {
10186 void use( Colour::Code _colourCode )
override {
10187 switch( _colourCode ) {
10189 case Colour::White:
return setColour(
"[0m" );
10190 case Colour::Red:
return setColour(
"[0;31m" );
10191 case Colour::Green:
return setColour(
"[0;32m" );
10192 case Colour::Blue:
return setColour(
"[0;34m" );
10193 case Colour::Cyan:
return setColour(
"[0;36m" );
10194 case Colour::Yellow:
return setColour(
"[0;33m" );
10195 case Colour::Grey:
return setColour(
"[1;30m" );
10197 case Colour::LightGrey:
return setColour(
"[0;37m" );
10198 case Colour::BrightRed:
return setColour(
"[1;31m" );
10199 case Colour::BrightGreen:
return setColour(
"[1;32m" );
10200 case Colour::BrightWhite:
return setColour(
"[1;37m" );
10201 case Colour::BrightYellow:
return setColour(
"[1;33m" );
10203 case Colour::Bright: CATCH_INTERNAL_ERROR(
"not a colour" );
10204 default: CATCH_INTERNAL_ERROR(
"Unknown colour requested" );
10207 static IColourImpl* instance() {
10208 static PosixColourImpl s_instance;
10209 return &s_instance;
10213 void setColour(
const char* _escapeCode ) {
10214 getCurrentContext().getConfig()->stream()
10215 <<
'\033' << _escapeCode;
10219 bool useColourOnPlatform() {
10221#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10222 !isDebuggerActive() &&
10224#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10225 isatty(STDOUT_FILENO)
10231 IColourImpl* platformColourInstance() {
10233 IConfigPtr config = getCurrentContext().getConfig();
10234 UseColour::YesOrNo colourMode = config
10235 ? config->useColour()
10237 if( colourMode == UseColour::Auto )
10238 colourMode = useColourOnPlatform()
10241 return colourMode == UseColour::Yes
10242 ? PosixColourImpl::instance()
10243 : NoColourImpl::instance();
10253 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
10261 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10262 Colour::Colour( Colour&& other )
noexcept {
10263 m_moved = other.m_moved;
10264 other.m_moved =
true;
10266 Colour& Colour::operator=( Colour&& other )
noexcept {
10267 m_moved = other.m_moved;
10268 other.m_moved =
true;
10272 Colour::~Colour(){
if( !m_moved ) use( None ); }
10274 void Colour::use( Code _colourCode ) {
10275 static IColourImpl* impl = platformColourInstance();
10280 if (impl !=
nullptr) {
10281 impl->use( _colourCode );
10285 std::ostream& operator << ( std::ostream& os, Colour
const& ) {
10291#if defined(__clang__)
10292# pragma clang diagnostic pop
10300 class Context :
public IMutableContext, NonCopyable {
10303 IResultCapture* getResultCapture()
override {
10304 return m_resultCapture;
10306 IRunner* getRunner()
override {
10310 IConfigPtr
const& getConfig()
const override {
10314 ~Context()
override;
10317 void setResultCapture( IResultCapture* resultCapture )
override {
10318 m_resultCapture = resultCapture;
10320 void setRunner( IRunner* runner )
override {
10323 void setConfig( IConfigPtr
const& config )
override {
10327 friend IMutableContext& getCurrentMutableContext();
10330 IConfigPtr m_config;
10331 IRunner* m_runner =
nullptr;
10332 IResultCapture* m_resultCapture =
nullptr;
10335 IMutableContext *IMutableContext::currentContext =
nullptr;
10337 void IMutableContext::createContext()
10339 currentContext =
new Context();
10342 void cleanUpContext() {
10343 delete IMutableContext::currentContext;
10344 IMutableContext::currentContext =
nullptr;
10346 IContext::~IContext() =
default;
10347 IMutableContext::~IMutableContext() =
default;
10348 Context::~Context() =
default;
10350 SimplePcg32& rng() {
10351 static SimplePcg32 s_rng;
10364 void writeToDebugConsole( std::string
const& text );
10368#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10369#include <android/log.h>
10372 void writeToDebugConsole( std::string
const& text ) {
10373 __android_log_write( ANDROID_LOG_DEBUG,
"Catch", text.c_str() );
10377#elif defined(CATCH_PLATFORM_WINDOWS)
10380 void writeToDebugConsole( std::string
const& text ) {
10381 ::OutputDebugStringA( text.c_str() );
10388 void writeToDebugConsole( std::string
const& text ) {
10390 Catch::cout() << text;
10398#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10401# include <sys/types.h>
10402# include <unistd.h>
10406#ifdef __apple_build_version__
10409# include <sys/sysctl.h>
10413 #ifdef __apple_build_version__
10419 bool isDebuggerActive(){
10421 struct kinfo_proc
info;
10427 info.kp_proc.p_flag = 0;
10433 mib[1] = KERN_PROC;
10434 mib[2] = KERN_PROC_PID;
10439 size =
sizeof(
info);
10440 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0 ) {
10441 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10447 return ( (
info.kp_proc.p_flag & P_TRACED) != 0 );
10450 bool isDebuggerActive() {
10457#elif defined(CATCH_PLATFORM_LINUX)
10469 bool isDebuggerActive(){
10473 std::ifstream in(
"/proc/self/status");
10474 for( std::string line; std::getline(in, line); ) {
10475 static const int PREFIX_LEN = 11;
10476 if( line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
10480 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
10487#elif defined(_MSC_VER)
10488 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10490 bool isDebuggerActive() {
10491 return IsDebuggerPresent() != 0;
10494#elif defined(__MINGW32__)
10495 extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10497 bool isDebuggerActive() {
10498 return IsDebuggerPresent() != 0;
10503 bool isDebuggerActive() {
return false; }
10511 ITransientExpression::~ITransientExpression() =
default;
10513 void formatReconstructedExpression( std::ostream &os, std::string
const& lhs, StringRef op, std::string
const& rhs ) {
10514 if( lhs.size() + rhs.size() < 40 &&
10515 lhs.find(
'\n') == std::string::npos &&
10516 rhs.find(
'\n') == std::string::npos )
10517 os << lhs <<
" " << op <<
" " << rhs;
10519 os << lhs <<
"\n" << op <<
"\n" << rhs;
10525#include <stdexcept>
10528#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10530 void throw_exception(std::exception
const& e) {
10531 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n"
10532 <<
"The message was: " << e.what() <<
'\n';
10538 void throw_logic_error(std::string
const& msg) {
10539 throw_exception(std::logic_error(msg));
10543 void throw_domain_error(std::string
const& msg) {
10544 throw_exception(std::domain_error(msg));
10548 void throw_runtime_error(std::string
const& msg) {
10549 throw_exception(std::runtime_error(msg));
10564 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int>
const& values );
10566 class EnumValuesRegistry :
public IMutableEnumValuesRegistry {
10568 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10570 EnumInfo
const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int>
const& values)
override;
10573 std::vector<StringRef> parseEnums( StringRef enums );
10586 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10593 StringRef extractInstanceName(StringRef enumInstance) {
10595 size_t name_start = enumInstance.size();
10596 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10599 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10603 std::vector<StringRef> parseEnums( StringRef enums ) {
10604 auto enumValues = splitStringRef( enums,
',' );
10605 std::vector<StringRef> parsed;
10606 parsed.reserve( enumValues.size() );
10607 for(
auto const& enumValue : enumValues ) {
10608 parsed.push_back(trim(extractInstanceName(enumValue)));
10613 EnumInfo::~EnumInfo() {}
10615 StringRef EnumInfo::lookup(
int value )
const {
10616 for(
auto const& valueToName : m_values ) {
10617 if( valueToName.first == value )
10618 return valueToName.second;
10620 return "{** unexpected enum value **}"_sr;
10623 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int>
const& values ) {
10624 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo );
10625 enumInfo->m_name = enumName;
10626 enumInfo->m_values.reserve( values.size() );
10628 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10629 assert( valueNames.size() == values.size() );
10631 for(
auto value : values )
10632 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10637 EnumInfo
const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int>
const& values ) {
10638 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10639 return *m_enumInfos.back();
10651 ErrnoGuard::ErrnoGuard():m_oldErrno(
errno){}
10652 ErrnoGuard::~ErrnoGuard() {
errno = m_oldErrno; }
10665 class ExceptionTranslatorRegistry :
public IExceptionTranslatorRegistry {
10667 ~ExceptionTranslatorRegistry();
10668 virtual void registerTranslator(
const IExceptionTranslator* translator );
10669 std::string translateActiveException()
const override;
10670 std::string tryTranslators()
const;
10673 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10679#import "Foundation/Foundation.h"
10684 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10687 void ExceptionTranslatorRegistry::registerTranslator(
const IExceptionTranslator* translator ) {
10688 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10691#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10692 std::string ExceptionTranslatorRegistry::translateActiveException()
const {
10697 return tryTranslators();
10699 @catch (NSException *exception) {
10700 return Catch::Detail::stringify( [exception description] );
10711 if (std::current_exception() ==
nullptr) {
10712 return "Non C++ exception. Possibly a CLR exception.";
10714 return tryTranslators();
10717 catch( TestFailureException& ) {
10718 std::rethrow_exception(std::current_exception());
10720 catch( std::exception& ex ) {
10723 catch( std::string& msg ) {
10726 catch(
const char* msg ) {
10730 return "Unknown exception";
10734 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10735 if (m_translators.empty()) {
10736 std::rethrow_exception(std::current_exception());
10738 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10743 std::string ExceptionTranslatorRegistry::translateActiveException()
const {
10744 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10747 std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10748 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10756#include <algorithm>
10758#if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
10764 void FatalConditionHandler::engage_platform() {}
10765 void FatalConditionHandler::disengage_platform() {}
10766 FatalConditionHandler::FatalConditionHandler() =
default;
10767 FatalConditionHandler::~FatalConditionHandler() =
default;
10773#if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
10774#error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10777#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10781 void reportFatal(
char const *
const message ) {
10782 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10788 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10793#if defined( CATCH_CONFIG_WINDOWS_SEH )
10797 struct SignalDefs { DWORD id;
const char* name; };
10802 static SignalDefs signalDefs[] = {
10803 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal" },
10804 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow" },
10805 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal" },
10806 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error" },
10809 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10810 for (
auto const& def : signalDefs) {
10811 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10812 reportFatal(def.name);
10817 return EXCEPTION_CONTINUE_SEARCH;
10823 static PVOID exceptionHandlerHandle =
nullptr;
10827 FatalConditionHandler::FatalConditionHandler() {
10828 ULONG guaranteeSize =
static_cast<ULONG
>(minStackSizeForErrors);
10829 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10833 <<
"Failed to reserve piece of stack."
10834 <<
" Stack overflows will not be reported successfully.";
10840 FatalConditionHandler::~FatalConditionHandler() =
default;
10842 void FatalConditionHandler::engage_platform() {
10844 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10845 if (!exceptionHandlerHandle) {
10846 CATCH_RUNTIME_ERROR(
"Could not register vectored exception handler");
10850 void FatalConditionHandler::disengage_platform() {
10851 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10852 CATCH_RUNTIME_ERROR(
"Could not unregister vectored exception handler");
10854 exceptionHandlerHandle =
nullptr;
10861#if defined( CATCH_CONFIG_POSIX_SIGNALS )
10867 struct SignalDefs {
10872 static SignalDefs signalDefs[] = {
10873 { SIGINT,
"SIGINT - Terminal interrupt signal" },
10874 { SIGILL,
"SIGILL - Illegal instruction signal" },
10875 { SIGFPE,
"SIGFPE - Floating point error signal" },
10876 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
10877 { SIGTERM,
"SIGTERM - Termination request signal" },
10878 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
10884#if defined(__GNUC__)
10885# pragma GCC diagnostic push
10886# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10889 static char* altStackMem =
nullptr;
10890 static std::size_t altStackSize = 0;
10891 static stack_t oldSigStack{};
10892 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10894 static void restorePreviousSignalHandlers() {
10899 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
10900 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10903 sigaltstack(&oldSigStack,
nullptr);
10906 static void handleSignal(
int sig ) {
10907 char const * name =
"<unknown signal>";
10908 for (
auto const& def : signalDefs) {
10909 if (sig == def.id) {
10917 restorePreviousSignalHandlers();
10918 reportFatal( name );
10922 FatalConditionHandler::FatalConditionHandler() {
10923 assert(!altStackMem &&
"Cannot initialize POSIX signal handler when one already exists");
10924 if (altStackSize == 0) {
10925 altStackSize = std::max(
static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10927 altStackMem =
new char[altStackSize]();
10930 FatalConditionHandler::~FatalConditionHandler() {
10931 delete[] altStackMem;
10934 altStackMem =
nullptr;
10937 void FatalConditionHandler::engage_platform() {
10939 sigStack.ss_sp = altStackMem;
10940 sigStack.ss_size = altStackSize;
10941 sigStack.ss_flags = 0;
10942 sigaltstack(&sigStack, &oldSigStack);
10943 struct sigaction sa = { };
10945 sa.sa_handler = handleSignal;
10946 sa.sa_flags = SA_ONSTACK;
10947 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
10948 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
10952#if defined(__GNUC__)
10953# pragma GCC diagnostic pop
10956 void FatalConditionHandler::disengage_platform() {
10957 restorePreviousSignalHandlers();
10971IGeneratorTracker::~IGeneratorTracker() {}
10973const char* GeneratorException::what() const noexcept {
10977namespace Generators {
10979 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10981 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker& {
10982 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10991 IResultCapture::~IResultCapture() =
default;
10997 IConfig::~IConfig() =
default;
11003 IExceptionTranslator::~IExceptionTranslator() =
default;
11004 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() =
default;
11010 IRegistryHub::~IRegistryHub() =
default;
11011 IMutableRegistryHub::~IMutableRegistryHub() =
default;
11020 class ListeningReporter :
public IStreamingReporter {
11021 using Reporters = std::vector<IStreamingReporterPtr>;
11022 Reporters m_listeners;
11023 IStreamingReporterPtr m_reporter =
nullptr;
11024 ReporterPreferences m_preferences;
11027 ListeningReporter();
11029 void addListener( IStreamingReporterPtr&& listener );
11030 void addReporter( IStreamingReporterPtr&& reporter );
11034 ReporterPreferences getPreferences()
const override;
11036 void noMatchingTestCases( std::string
const& spec )
override;
11038 void reportInvalidArguments(std::string
const&arg)
override;
11040 static std::set<Verbosity> getSupportedVerbosities();
11042#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11043 void benchmarkPreparing(std::string
const& name)
override;
11044 void benchmarkStarting( BenchmarkInfo
const& benchmarkInfo )
override;
11045 void benchmarkEnded( BenchmarkStats<>
const& benchmarkStats )
override;
11046 void benchmarkFailed(std::string
const&)
override;
11049 void testRunStarting( TestRunInfo
const& testRunInfo )
override;
11050 void testGroupStarting( GroupInfo
const& groupInfo )
override;
11051 void testCaseStarting( TestCaseInfo
const& testInfo )
override;
11052 void sectionStarting( SectionInfo
const& sectionInfo )
override;
11053 void assertionStarting( AssertionInfo
const& assertionInfo )
override;
11056 bool assertionEnded( AssertionStats
const& assertionStats )
override;
11057 void sectionEnded( SectionStats
const& sectionStats )
override;
11058 void testCaseEnded( TestCaseStats
const& testCaseStats )
override;
11059 void testGroupEnded( TestGroupStats
const& testGroupStats )
override;
11060 void testRunEnded( TestRunStats
const& testRunStats )
override;
11062 void skipTest( TestCaseInfo
const& testInfo )
override;
11063 bool isMulti()
const override;
11072 ReporterConfig::ReporterConfig( IConfigPtr
const& _fullConfig )
11073 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11075 ReporterConfig::ReporterConfig( IConfigPtr
const& _fullConfig, std::ostream& _stream )
11076 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11078 std::ostream& ReporterConfig::stream()
const {
return *m_stream; }
11079 IConfigPtr ReporterConfig::fullConfig()
const {
return m_fullConfig; }
11081 TestRunInfo::TestRunInfo( std::string
const& _name ) : name( _name ) {}
11083 GroupInfo::GroupInfo( std::string
const& _name,
11084 std::size_t _groupIndex,
11085 std::size_t _groupsCount )
11087 groupIndex( _groupIndex ),
11088 groupsCounts( _groupsCount )
11091 AssertionStats::AssertionStats( AssertionResult
const& _assertionResult,
11092 std::vector<MessageInfo>
const& _infoMessages,
11093 Totals
const& _totals )
11094 : assertionResult( _assertionResult ),
11095 infoMessages( _infoMessages ),
11098 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11100 if( assertionResult.hasMessage() ) {
11103 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11104 builder << assertionResult.getMessage();
11105 builder.m_info.message = builder.m_stream.str();
11107 infoMessages.push_back( builder.m_info );
11111 AssertionStats::~AssertionStats() =
default;
11113 SectionStats::SectionStats( SectionInfo
const& _sectionInfo,
11114 Counts
const& _assertions,
11115 double _durationInSeconds,
11116 bool _missingAssertions )
11117 : sectionInfo( _sectionInfo ),
11118 assertions( _assertions ),
11119 durationInSeconds( _durationInSeconds ),
11120 missingAssertions( _missingAssertions )
11123 SectionStats::~SectionStats() =
default;
11125 TestCaseStats::TestCaseStats( TestCaseInfo
const& _testInfo,
11126 Totals
const& _totals,
11127 std::string
const& _stdOut,
11128 std::string
const& _stdErr,
11130 : testInfo( _testInfo ),
11134 aborting( _aborting )
11137 TestCaseStats::~TestCaseStats() =
default;
11139 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo,
11140 Totals
const& _totals,
11142 : groupInfo( _groupInfo ),
11144 aborting( _aborting )
11147 TestGroupStats::TestGroupStats( GroupInfo
const& _groupInfo )
11148 : groupInfo( _groupInfo ),
11152 TestGroupStats::~TestGroupStats() =
default;
11154 TestRunStats::TestRunStats( TestRunInfo
const& _runInfo,
11155 Totals
const& _totals,
11157 : runInfo( _runInfo ),
11159 aborting( _aborting )
11162 TestRunStats::~TestRunStats() =
default;
11164 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
11165 bool IStreamingReporter::isMulti()
const {
return false; }
11167 IReporterFactory::~IReporterFactory() =
default;
11168 IReporterRegistry::~IReporterRegistry() =
default;
11175 IRunner::~IRunner() =
default;
11181 ITestInvoker::~ITestInvoker() =
default;
11182 ITestCaseRegistry::~ITestCaseRegistry() =
default;
11187#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11192 LeakDetector::LeakDetector() {
11193 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11194 flag |= _CRTDBG_LEAK_CHECK_DF;
11195 flag |= _CRTDBG_ALLOC_MEM_DF;
11196 _CrtSetDbgFlag(flag);
11197 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11198 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11200 _CrtSetBreakAlloc(-1);
11206 Catch::LeakDetector::LeakDetector() {}
11210Catch::LeakDetector::~LeakDetector() {
11222 std::size_t listTests( Config
const& config );
11224 std::size_t listTestsNamesOnly( Config
const& config );
11227 void add( std::string
const& spelling );
11228 std::string all()
const;
11230 std::set<std::string> spellings;
11231 std::size_t
count = 0;
11234 std::size_t listTags( Config
const& config );
11236 std::size_t listReporters();
11238 Option<std::size_t> list( std::shared_ptr<Config>
const& config );
11246 using namespace clara::TextFlow;
11251#include <algorithm>
11256 std::size_t listTests( Config
const& config ) {
11257 TestSpec
const& testSpec = config.testSpec();
11258 if( config.hasTestFilters() )
11259 Catch::cout() <<
"Matching test cases:\n";
11261 Catch::cout() <<
"All available test cases:\n";
11264 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11265 for(
auto const& testCaseInfo : matchedTestCases ) {
11266 Colour::Code colour = testCaseInfo.isHidden()
11267 ? Colour::SecondaryText
11269 Colour colourGuard( colour );
11271 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) <<
"\n";
11272 if( config.verbosity() >= Verbosity::High ) {
11273 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11274 std::string description = testCaseInfo.description;
11275 if( description.empty() )
11276 description =
"(NO DESCRIPTION)";
11277 Catch::cout() << Column( description ).indent(4) << std::endl;
11279 if( !testCaseInfo.tags.empty() )
11280 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) <<
"\n";
11283 if( !config.hasTestFilters() )
11284 Catch::cout() << pluralise( matchedTestCases.size(),
"test case" ) <<
'\n' << std::endl;
11286 Catch::cout() << pluralise( matchedTestCases.size(),
"matching test case" ) <<
'\n' << std::endl;
11287 return matchedTestCases.size();
11290 std::size_t listTestsNamesOnly( Config
const& config ) {
11291 TestSpec
const& testSpec = config.testSpec();
11292 std::size_t matchedTests = 0;
11293 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11294 for(
auto const& testCaseInfo : matchedTestCases ) {
11296 if( startsWith( testCaseInfo.name,
'#' ) )
11297 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11299 Catch::cout() << testCaseInfo.name;
11300 if ( config.verbosity() >= Verbosity::High )
11301 Catch::cout() <<
"\t@" << testCaseInfo.lineInfo;
11302 Catch::cout() << std::endl;
11304 return matchedTests;
11307 void TagInfo::add( std::string
const& spelling ) {
11309 spellings.insert( spelling );
11312 std::string TagInfo::all()
const {
11314 for (
auto const& spelling : spellings) {
11316 size += spelling.size() + 2;
11319 std::string out; out.reserve(size);
11320 for (
auto const& spelling : spellings) {
11328 std::size_t listTags( Config
const& config ) {
11329 TestSpec
const& testSpec = config.testSpec();
11330 if( config.hasTestFilters() )
11331 Catch::cout() <<
"Tags for matching test cases:\n";
11333 Catch::cout() <<
"All available tags:\n";
11336 std::map<std::string, TagInfo> tagCounts;
11338 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11339 for(
auto const& testCase : matchedTestCases ) {
11340 for(
auto const& tagName : testCase.getTestCaseInfo().tags ) {
11341 std::string lcaseTagName = toLower( tagName );
11342 auto countIt = tagCounts.find( lcaseTagName );
11343 if( countIt == tagCounts.end() )
11344 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11345 countIt->second.add( tagName );
11349 for(
auto const& tagCount : tagCounts ) {
11350 ReusableStringStream rss;
11351 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11352 auto str = rss.str();
11353 auto wrapper = Column( tagCount.second.all() )
11354 .initialIndent( 0 )
11355 .indent( str.size() )
11356 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11357 Catch::cout() << str << wrapper <<
'\n';
11359 Catch::cout() << pluralise( tagCounts.size(),
"tag" ) <<
'\n' << std::endl;
11360 return tagCounts.size();
11363 std::size_t listReporters() {
11364 Catch::cout() <<
"Available reporters:\n";
11365 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
11366 std::size_t maxNameLen = 0;
11367 for(
auto const& factoryKvp : factories )
11368 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11370 for(
auto const& factoryKvp : factories ) {
11372 << Column( factoryKvp.first +
":" )
11374 .width( 5+maxNameLen )
11375 + Column( factoryKvp.second->getDescription() )
11378 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11381 Catch::cout() << std::endl;
11382 return factories.size();
11385 Option<std::size_t> list( std::shared_ptr<Config>
const& config ) {
11386 Option<std::size_t> listedCount;
11387 getCurrentMutableContext().setConfig( config );
11388 if( config->listTests() )
11389 listedCount = listedCount.valueOr(0) + listTests( *config );
11390 if( config->listTestNamesOnly() )
11391 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11392 if( config->listTags() )
11393 listedCount = listedCount.valueOr(0) + listTags( *config );
11394 if( config->listReporters() )
11395 listedCount = listedCount.valueOr(0) + listReporters();
11396 return listedCount;
11404namespace Matchers {
11407 std::string MatcherUntypedBase::toString()
const {
11408 if( m_cachedToString.empty() )
11409 m_cachedToString = describe();
11410 return m_cachedToString;
11413 MatcherUntypedBase::~MatcherUntypedBase() =
default;
11418using namespace Matchers;
11419using Matchers::Impl::MatcherBase;
11426namespace Matchers {
11427namespace Exception {
11429bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11430 return ex.what() == m_message;
11433std::string ExceptionMessageMatcher::describe()
const {
11434 return "exception message matches \"" + m_message + "\"";
11438Exception::ExceptionMessageMatcher Message(std::string
const& message) {
11439 return Exception::ExceptionMessageMatcher(message);
11451 bool isnan(
float f);
11452 bool isnan(
double d);
11461 template <
typename T>
11462 std::string to_string(T
const& t) {
11463#if defined(CATCH_CONFIG_CPP11_TO_STRING)
11464 return std::to_string(t);
11466 ReusableStringStream rss;
11474#include <algorithm>
11480#include <type_traits>
11487 int32_t convert(
float f) {
11488 static_assert(
sizeof(float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11490 std::memcpy(&i, &f,
sizeof(f));
11494 int64_t convert(
double d) {
11495 static_assert(
sizeof(double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11497 std::memcpy(&i, &d,
sizeof(d));
11501 template <
typename FP>
11502 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11505 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11509 auto lc = convert(lhs);
11510 auto rc = convert(rhs);
11512 if ((lc < 0) != (rc < 0)) {
11518 auto ulpDiff = std::abs(
static_cast<FP
>(lc - rc));
11519 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11522#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11524 float nextafter(
float x,
float y) {
11525 return ::nextafterf(x, y);
11528 double nextafter(
double x,
double y) {
11529 return ::nextafter(x, y);
11534template <
typename FP>
11535FP step(FP start, FP direction, uint64_t steps) {
11536 for (uint64_t i = 0; i < steps; ++i) {
11537#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11538 start = Catch::nextafter(start, direction);
11540 start = std::nextafter(start, direction);
11548bool marginComparison(
double lhs,
double rhs,
double margin) {
11549 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11552template <
typename FloatingPo
int>
11553void write(std::ostream& out, FloatingPoint num) {
11554 out << std::scientific
11555 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11561namespace Matchers {
11562namespace Floating {
11564 enum class FloatingPointKind : uint8_t {
11569 WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11570 :m_target{ target }, m_margin{ margin } {
11571 CATCH_ENFORCE(margin >= 0,
"Invalid margin: " << margin <<
'.'
11572 <<
" Margin has to be non-negative.");
11577 bool WithinAbsMatcher::match(
double const& matchee)
const {
11578 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11581 std::string WithinAbsMatcher::describe()
const {
11582 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11585 WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11586 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11587 CATCH_ENFORCE(m_type == FloatingPointKind::Double
11588 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11589 "Provided ULP is impossibly large for a float comparison.");
11592#if defined(__clang__)
11593#pragma clang diagnostic push
11595#pragma clang diagnostic ignored "-Wunreachable-code"
11598 bool WithinUlpsMatcher::match(
double const& matchee)
const {
11600 case FloatingPointKind::Float:
11601 return almostEqualUlps<float>(
static_cast<float>(matchee),
static_cast<float>(m_target), m_ulps);
11602 case FloatingPointKind::Double:
11603 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11605 CATCH_INTERNAL_ERROR(
"Unknown FloatingPointKind value" );
11609#if defined(__clang__)
11610#pragma clang diagnostic pop
11613 std::string WithinUlpsMatcher::describe()
const {
11614 std::stringstream ret;
11616 ret <<
"is within " << m_ulps <<
" ULPs of ";
11618 if (m_type == FloatingPointKind::Float) {
11619 write(ret,
static_cast<float>(m_target));
11622 write(ret, m_target);
11626 if (m_type == FloatingPointKind::Double) {
11627 write(ret, step(m_target,
static_cast<double>(-INFINITY), m_ulps));
11629 write(ret, step(m_target,
static_cast<double>( INFINITY), m_ulps));
11632 write(ret, step(
static_cast<float>(m_target),
static_cast<float>(-INFINITY), m_ulps));
11634 write(ret, step(
static_cast<float>(m_target),
static_cast<float>( INFINITY), m_ulps));
11641 WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon):
11643 m_epsilon(epsilon){
11644 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11645 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
");
11648 bool WithinRelMatcher::match(double const& matchee) const {
11649 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11650 return marginComparison(matchee, m_target,
11651 std::isinf(relMargin)? 0 : relMargin);
11654 std::string WithinRelMatcher::describe() const {
11655 Catch::ReusableStringStream sstr;
11656 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
";
11660}// namespace Floating
11662Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11663 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11666Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11667 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11670Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11671 return Floating::WithinAbsMatcher(target, margin);
11674Floating::WithinRelMatcher WithinRel(double target, double eps) {
11675 return Floating::WithinRelMatcher(target, eps);
11678Floating::WithinRelMatcher WithinRel(double target) {
11679 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11682Floating::WithinRelMatcher WithinRel(float target, float eps) {
11683 return Floating::WithinRelMatcher(target, eps);
11686Floating::WithinRelMatcher WithinRel(float target) {
11687 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11690} // namespace Matchers
11691} // namespace Catch
11692// end catch_matchers_floating.cpp
11693// start catch_matchers_generic.cpp
11695std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11696 if (desc.empty()) {
11697 return "matches undescribed predicate
";
11699 return "matches predicate: \
"" + desc +
'"';
11708namespace Matchers {
11710 namespace StdString {
11712 CasedString::CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity )
11713 : m_caseSensitivity( caseSensitivity ),
11714 m_str( adjustString( str ) )
11716 std::string CasedString::adjustString( std::string
const& str )
const {
11717 return m_caseSensitivity == CaseSensitive::No
11721 std::string CasedString::caseSensitivitySuffix()
const {
11722 return m_caseSensitivity == CaseSensitive::No
11723 ?
" (case insensitive)"
11727 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
11728 : m_comparator( comparator ),
11729 m_operation( operation ) {
11732 std::string StringMatcherBase::describe()
const {
11733 std::string description;
11734 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11735 m_comparator.caseSensitivitySuffix().size());
11736 description += m_operation;
11737 description += ": \"";
11738 description += m_comparator.m_str;
11739 description += "\"";
11740 description += m_comparator.caseSensitivitySuffix();
11741 return description;
11744 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
11746 bool EqualsMatcher::match( std::string
const& source )
const {
11747 return m_comparator.adjustString( source ) == m_comparator.m_str;
11750 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
11752 bool ContainsMatcher::match( std::string
const& source )
const {
11753 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11756 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
11758 bool StartsWithMatcher::match( std::string
const& source )
const {
11759 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11762 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
11764 bool EndsWithMatcher::match( std::string
const& source )
const {
11765 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11768 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11770 bool RegexMatcher::match(std::string
const& matchee)
const {
11771 auto flags = std::regex::ECMAScript;
11772 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11773 flags |= std::regex::icase;
11775 auto reg = std::regex(m_regex, flags);
11776 return std::regex_match(matchee, reg);
11779 std::string RegexMatcher::describe()
const {
11780 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11785 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11786 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11788 StdString::ContainsMatcher Contains( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11789 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11791 StdString::EndsWithMatcher EndsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11792 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11794 StdString::StartsWithMatcher StartsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
11795 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11798 StdString::RegexMatcher Matches(std::string
const& regex, CaseSensitive::Choice caseSensitivity) {
11799 return StdString::RegexMatcher(regex, caseSensitivity);
11810 bool uncaught_exceptions();
11819 MessageInfo::MessageInfo( StringRef
const& _macroName,
11820 SourceLineInfo
const& _lineInfo,
11821 ResultWas::OfType _type )
11822 : macroName( _macroName ),
11823 lineInfo( _lineInfo ),
11825 sequence( ++globalCount )
11828 bool MessageInfo::operator==( MessageInfo
const& other )
const {
11829 return sequence == other.sequence;
11832 bool MessageInfo::operator<( MessageInfo
const& other )
const {
11833 return sequence < other.sequence;
11837 unsigned int MessageInfo::globalCount = 0;
11841 Catch::MessageBuilder::MessageBuilder( StringRef
const& macroName,
11842 SourceLineInfo
const& lineInfo,
11843 ResultWas::OfType type )
11844 :m_info(macroName, lineInfo, type) {}
11848 ScopedMessage::ScopedMessage( MessageBuilder
const& builder )
11849 : m_info( builder.m_info ), m_moved()
11851 m_info.message = builder.m_stream.str();
11852 getResultCapture().pushScopedMessage( m_info );
11855 ScopedMessage::ScopedMessage( ScopedMessage&& old )
11856 : m_info( old.m_info ), m_moved()
11858 old.m_moved =
true;
11861 ScopedMessage::~ScopedMessage() {
11862 if ( !uncaught_exceptions() && !m_moved ){
11863 getResultCapture().popScopedMessage(m_info);
11867 Capturer::Capturer( StringRef macroName, SourceLineInfo
const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11868 auto trimmed = [&] (
size_t start,
size_t end) {
11869 while (names[start] ==
',' || isspace(
static_cast<unsigned char>(names[start]))) {
11872 while (names[end] ==
',' || isspace(
static_cast<unsigned char>(names[end]))) {
11875 return names.substr(start, end - start + 1);
11877 auto skipq = [&] (
size_t start,
char quote) {
11878 for (
auto i = start + 1; i < names.size() ; ++i) {
11879 if (names[i] == quote)
11881 if (names[i] ==
'\\')
11884 CATCH_INTERNAL_ERROR(
"CAPTURE parsing encountered unmatched quote");
11888 std::stack<char> openings;
11889 for (
size_t pos = 0; pos < names.size(); ++pos) {
11890 char c = names[pos];
11908 pos = skipq(pos, c);
11911 if (start != pos && openings.empty()) {
11912 m_messages.emplace_back(macroName, lineInfo, resultType);
11913 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11914 m_messages.back().message += " := ";
11919 assert(openings.empty() &&
"Mismatched openings");
11920 m_messages.emplace_back(macroName, lineInfo, resultType);
11921 m_messages.back().message =
static_cast<std::string
>(trimmed(start, names.size() - 1));
11922 m_messages.back().message += " := ";
11924 Capturer::~Capturer() {
11925 if ( !uncaught_exceptions() ){
11926 assert( m_captured == m_messages.size() );
11927 for(
size_t i = 0; i < m_captured; ++i )
11928 m_resultCapture.popScopedMessage( m_messages[i] );
11932 void Capturer::captureValue(
size_t index, std::string
const& value ) {
11933 assert( index < m_messages.size() );
11934 m_messages[index].message += value;
11935 m_resultCapture.pushScopedMessage( m_messages[index] );
11944#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11945#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11953 class RedirectedStream {
11954 std::ostream& m_originalStream;
11955 std::ostream& m_redirectionStream;
11956 std::streambuf* m_prevBuf;
11959 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11960 ~RedirectedStream();
11963 class RedirectedStdOut {
11964 ReusableStringStream m_rss;
11965 RedirectedStream m_cout;
11967 RedirectedStdOut();
11968 auto str() const -> std::
string;
11974 class RedirectedStdErr {
11975 ReusableStringStream m_rss;
11976 RedirectedStream m_cerr;
11977 RedirectedStream m_clog;
11979 RedirectedStdErr();
11980 auto str() const -> std::
string;
11983 class RedirectedStreams {
11985 RedirectedStreams(RedirectedStreams
const&) =
delete;
11986 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
11987 RedirectedStreams(RedirectedStreams&&) =
delete;
11988 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
11990 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11991 ~RedirectedStreams();
11993 std::string& m_redirectedCout;
11994 std::string& m_redirectedCerr;
11995 RedirectedStdOut m_redirectedStdOut;
11996 RedirectedStdErr m_redirectedStdErr;
11999#if defined(CATCH_CONFIG_NEW_CAPTURE)
12007 TempFile(TempFile
const&) =
delete;
12008 TempFile& operator=(TempFile
const&) =
delete;
12009 TempFile(TempFile&&) =
delete;
12010 TempFile& operator=(TempFile&&) =
delete;
12015 std::FILE* getFile();
12016 std::string getContents();
12019 std::FILE* m_file =
nullptr;
12020 #if defined(_MSC_VER)
12021 char m_buffer[L_tmpnam] = { 0 };
12025 class OutputRedirect {
12027 OutputRedirect(OutputRedirect
const&) =
delete;
12028 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
12029 OutputRedirect(OutputRedirect&&) =
delete;
12030 OutputRedirect& operator=(OutputRedirect&&) =
delete;
12032 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12036 int m_originalStdout = -1;
12037 int m_originalStderr = -1;
12038 TempFile m_stdoutFile;
12039 TempFile m_stderrFile;
12040 std::string& m_stdoutDest;
12041 std::string& m_stderrDest;
12054#include <stdexcept>
12056#if defined(CATCH_CONFIG_NEW_CAPTURE)
12057 #if defined(_MSC_VER)
12061 #define fileno _fileno
12063 #include <unistd.h>
12069 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12070 : m_originalStream( originalStream ),
12071 m_redirectionStream( redirectionStream ),
12072 m_prevBuf( m_originalStream.rdbuf() )
12074 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12077 RedirectedStream::~RedirectedStream() {
12078 m_originalStream.rdbuf( m_prevBuf );
12081 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
12082 auto RedirectedStdOut::str() const -> std::
string {
return m_rss.str(); }
12084 RedirectedStdErr::RedirectedStdErr()
12085 : m_cerr( Catch::cerr(), m_rss.get() ),
12086 m_clog( Catch::clog(), m_rss.get() )
12088 auto RedirectedStdErr::str() const -> std::
string {
return m_rss.str(); }
12090 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12091 : m_redirectedCout(redirectedCout),
12092 m_redirectedCerr(redirectedCerr)
12095 RedirectedStreams::~RedirectedStreams() {
12096 m_redirectedCout += m_redirectedStdOut.str();
12097 m_redirectedCerr += m_redirectedStdErr.str();
12100#if defined(CATCH_CONFIG_NEW_CAPTURE)
12102#if defined(_MSC_VER)
12103 TempFile::TempFile() {
12104 if (tmpnam_s(m_buffer)) {
12105 CATCH_RUNTIME_ERROR(
"Could not get a temp filename");
12107 if (fopen_s(&m_file, m_buffer,
"w+")) {
12109 if (strerror_s(buffer,
errno)) {
12110 CATCH_RUNTIME_ERROR(
"Could not translate errno to a string");
12112 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer <<
"' because: " << buffer);
12116 TempFile::TempFile() {
12117 m_file = std::tmpfile();
12119 CATCH_RUNTIME_ERROR(
"Could not create a temp file.");
12125 TempFile::~TempFile() {
12127 std::fclose(m_file);
12130#if defined(_MSC_VER)
12131 std::remove(m_buffer);
12135 FILE* TempFile::getFile() {
12139 std::string TempFile::getContents() {
12140 std::stringstream sstr;
12141 char buffer[100] = {};
12142 std::rewind(m_file);
12143 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12149 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12150 m_originalStdout(dup(1)),
12151 m_originalStderr(dup(2)),
12152 m_stdoutDest(stdout_dest),
12153 m_stderrDest(stderr_dest) {
12154 dup2(fileno(m_stdoutFile.getFile()), 1);
12155 dup2(fileno(m_stderrFile.getFile()), 2);
12158 OutputRedirect::~OutputRedirect() {
12159 Catch::cout() << std::flush;
12163 Catch::cerr() << std::flush;
12164 Catch::clog() << std::flush;
12167 dup2(m_originalStdout, 1);
12168 dup2(m_originalStderr, 2);
12170 m_stdoutDest += m_stdoutFile.getContents();
12171 m_stderrDest += m_stderrFile.getContents();
12178#if defined(CATCH_CONFIG_NEW_CAPTURE)
12179 #if defined(_MSC_VER)
12192#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12193 bool isnan(
float f) {
12194 return std::isnan(f);
12196 bool isnan(
double d) {
12197 return std::isnan(d);
12201 bool isnan(
float f) {
12202 return std::_isnan(f);
12204 bool isnan(
double d) {
12205 return std::_isnan(d);
12217#if defined(_MSC_VER)
12218#pragma warning(push)
12219#pragma warning(disable:4146)
12222 uint32_t rotate_right(uint32_t val, uint32_t count) {
12223 const uint32_t mask = 31;
12225 return (val >> count) | (val << (-
count & mask));
12228#if defined(_MSC_VER)
12229#pragma warning(pop)
12234 SimplePcg32::SimplePcg32(result_type seed_) {
12238 void SimplePcg32::seed(result_type seed_) {
12245 void SimplePcg32::discard(uint64_t skip) {
12248 for (uint64_t s = 0; s < skip; ++s) {
12249 static_cast<void>((*this)());
12253 SimplePcg32::result_type SimplePcg32::operator()() {
12255 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12256 const auto output = rotate_right(xorshifted, m_state >> 59u);
12259 m_state = m_state * 6364136223846793005ULL + s_inc;
12264 bool operator==(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12265 return lhs.m_state == rhs.m_state;
12268 bool operator!=(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12269 return lhs.m_state != rhs.m_state;
12279#include <algorithm>
12287 std::vector<TestCase> sortTests( IConfig
const& config, std::vector<TestCase>
const& unsortedTestCases );
12289 bool isThrowSafe( TestCase
const& testCase, IConfig
const& config );
12290 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config );
12292 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions );
12294 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config );
12295 std::vector<TestCase>
const& getAllTestCasesSorted( IConfig
const& config );
12297 class TestRegistry :
public ITestCaseRegistry {
12299 virtual ~TestRegistry() =
default;
12301 virtual void registerTest( TestCase
const& testCase );
12303 std::vector<TestCase>
const& getAllTests()
const override;
12304 std::vector<TestCase>
const& getAllTestsSorted( IConfig
const& config )
const override;
12307 std::vector<TestCase> m_functions;
12308 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12309 mutable std::vector<TestCase> m_sortedFunctions;
12310 std::size_t m_unnamedCount = 0;
12311 std::ios_base::Init m_ostreamInit;
12316 class TestInvokerAsFunction :
public ITestInvoker {
12317 void(*m_testAsFunction)();
12319 TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept;
12321 void invoke() const override;
12324 std::
string extractClassName( StringRef const& classOrQualifiedMethodName );
12337 class ReporterRegistry :
public IReporterRegistry {
12341 ~ReporterRegistry()
override;
12343 IStreamingReporterPtr create( std::string
const& name, IConfigPtr
const& config )
const override;
12345 void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory );
12346 void registerListener( IReporterFactoryPtr
const& factory );
12348 FactoryMap
const& getFactories()
const override;
12349 Listeners
const& getListeners()
const override;
12352 FactoryMap m_factories;
12353 Listeners m_listeners;
12367 TagAlias(std::string
const& _tag, SourceLineInfo _lineInfo);
12370 SourceLineInfo lineInfo;
12380 class TagAliasRegistry :
public ITagAliasRegistry {
12382 ~TagAliasRegistry()
override;
12383 TagAlias
const* find( std::string
const& alias )
const override;
12384 std::string expandAliases( std::string
const& unexpandedTestSpec )
const override;
12385 void add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo );
12388 std::map<std::string, TagAlias> m_registry;
12397#include <exception>
12401 class StartupExceptionRegistry {
12402#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12404 void add(std::exception_ptr
const& exception)
noexcept;
12405 std::vector<std::exception_ptr>
const& getExceptions() const noexcept;
12407 std::vector<std::exception_ptr> m_exceptions;
12418 struct ISingleton {
12419 virtual ~ISingleton();
12422 void addSingleton( ISingleton* singleton );
12423 void cleanupSingletons();
12425 template<
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
typename MutableInterfaceT = InterfaceT>
12426 class Singleton : SingletonImplT,
public ISingleton {
12428 static auto getInternal() -> Singleton* {
12429 static Singleton* s_instance =
nullptr;
12430 if( !s_instance ) {
12431 s_instance =
new Singleton;
12432 addSingleton( s_instance );
12438 static auto get() -> InterfaceT
const& {
12439 return *getInternal();
12441 static auto getMutable() -> MutableInterfaceT& {
12442 return *getInternal();
12453 class RegistryHub :
public IRegistryHub,
public IMutableRegistryHub,
12454 private NonCopyable {
12457 RegistryHub() =
default;
12458 IReporterRegistry
const& getReporterRegistry()
const override {
12459 return m_reporterRegistry;
12461 ITestCaseRegistry
const& getTestCaseRegistry()
const override {
12462 return m_testCaseRegistry;
12464 IExceptionTranslatorRegistry
const& getExceptionTranslatorRegistry()
const override {
12465 return m_exceptionTranslatorRegistry;
12467 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
12468 return m_tagAliasRegistry;
12470 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12471 return m_exceptionRegistry;
12475 void registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory )
override {
12476 m_reporterRegistry.registerReporter( name, factory );
12478 void registerListener( IReporterFactoryPtr
const& factory )
override {
12479 m_reporterRegistry.registerListener( factory );
12481 void registerTest( TestCase
const& testInfo )
override {
12482 m_testCaseRegistry.registerTest( testInfo );
12484 void registerTranslator(
const IExceptionTranslator* translator )
override {
12485 m_exceptionTranslatorRegistry.registerTranslator( translator );
12487 void registerTagAlias( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo )
override {
12488 m_tagAliasRegistry.add( alias, tag, lineInfo );
12490 void registerStartupException() noexcept
override {
12491#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12492 m_exceptionRegistry.add(std::current_exception());
12494 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12497 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry()
override {
12498 return m_enumValuesRegistry;
12502 TestRegistry m_testCaseRegistry;
12503 ReporterRegistry m_reporterRegistry;
12504 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12505 TagAliasRegistry m_tagAliasRegistry;
12506 StartupExceptionRegistry m_exceptionRegistry;
12507 Detail::EnumValuesRegistry m_enumValuesRegistry;
12511 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12513 IRegistryHub
const& getRegistryHub() {
12514 return RegistryHubSingleton::get();
12516 IMutableRegistryHub& getMutableRegistryHub() {
12517 return RegistryHubSingleton::getMutable();
12520 cleanupSingletons();
12523 std::string translateActiveException() {
12524 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12533 ReporterRegistry::~ReporterRegistry() =
default;
12535 IStreamingReporterPtr ReporterRegistry::create( std::string
const& name, IConfigPtr
const& config )
const {
12536 auto it = m_factories.find( name );
12537 if( it == m_factories.end() )
12539 return it->second->create( ReporterConfig( config ) );
12542 void ReporterRegistry::registerReporter( std::string
const& name, IReporterFactoryPtr
const& factory ) {
12543 m_factories.emplace(name, factory);
12545 void ReporterRegistry::registerListener( IReporterFactoryPtr
const& factory ) {
12546 m_listeners.push_back( factory );
12549 IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12550 return m_factories;
12552 IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12553 return m_listeners;
12562 bool isOk( ResultWas::OfType resultType ) {
12563 return ( resultType & ResultWas::FailureBit ) == 0;
12565 bool isJustInfo(
int flags ) {
12566 return flags == ResultWas::Info;
12569 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12570 return static_cast<ResultDisposition::Flags
>(
static_cast<int>( lhs ) |
static_cast<int>( rhs ) );
12573 bool shouldContinueOnFailure(
int flags ) {
return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
12574 bool shouldSuppressFailure(
int flags ) {
return ( flags & ResultDisposition::SuppressFail ) != 0; }
12581#include <algorithm>
12586 namespace Generators {
12587 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12588 GeneratorBasePtr m_generator;
12590 GeneratorTracker( TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12591 : TrackerBase( nameAndLocation, ctx, parent )
12593 ~GeneratorTracker();
12595 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation
const& nameAndLocation ) {
12596 std::shared_ptr<GeneratorTracker> tracker;
12598 ITracker& currentTracker = ctx.currentTracker();
12610 if (currentTracker.nameAndLocation() == nameAndLocation) {
12611 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12612 assert(thisTracker);
12613 assert(thisTracker->isGeneratorTracker());
12614 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12615 }
else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12616 assert( childTracker );
12617 assert( childTracker->isGeneratorTracker() );
12618 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12620 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12621 currentTracker.addChild( tracker );
12624 if( !tracker->isComplete() ) {
12632 bool isGeneratorTracker()
const override {
return true; }
12633 auto hasGenerator() const ->
bool override {
12634 return !!m_generator;
12636 void close()
override {
12637 TrackerBase::close();
12645 const bool should_wait_for_child = [&]() {
12647 if ( m_children.empty() ) {
12652 m_children.begin(),
12654 []( TestCaseTracking::ITrackerPtr tracker ) {
12655 return tracker->hasStarted();
12656 } ) != m_children.end() ) {
12663 auto* parent = m_parent;
12666 while ( !parent->isSectionTracker() ) {
12667 parent = &( parent->parent() );
12670 "Missing root (test case) level section" );
12672 auto const& parentSection =
12673 static_cast<SectionTracker&
>( *parent );
12674 auto const& filters = parentSection.getFilters();
12676 if ( filters.empty() ) {
12680 for (
auto const& child : m_children ) {
12681 if ( child->isSectionTracker() &&
12682 std::find( filters.begin(),
12684 static_cast<SectionTracker&
>( *child )
12685 .trimmedName() ) !=
12697 if ( should_wait_for_child ||
12698 ( m_runState == CompletedSuccessfully &&
12699 m_generator->next() ) ) {
12700 m_children.clear();
12701 m_runState = Executing;
12706 auto getGenerator() const -> GeneratorBasePtr const&
override {
12707 return m_generator;
12709 void setGenerator( GeneratorBasePtr&& generator )
override {
12710 m_generator = std::move( generator );
12713 GeneratorTracker::~GeneratorTracker() {}
12716 RunContext::RunContext(IConfigPtr
const& _config, IStreamingReporterPtr&& reporter)
12717 : m_runInfo(_config->name()),
12718 m_context(getCurrentMutableContext()),
12720 m_reporter(std::move(reporter)),
12721 m_lastAssertionInfo{ StringRef(), SourceLineInfo(
"",0), StringRef(), ResultDisposition::Normal },
12722 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12724 m_context.setRunner(
this);
12725 m_context.setConfig(m_config);
12726 m_context.setResultCapture(
this);
12727 m_reporter->testRunStarting(m_runInfo);
12730 RunContext::~RunContext() {
12731 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12734 void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12735 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12738 void RunContext::testGroupEnded(std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12739 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12742 Totals RunContext::runTest(TestCase
const& testCase) {
12743 Totals prevTotals = m_totals;
12745 std::string redirectedCout;
12746 std::string redirectedCerr;
12748 auto const& testInfo = testCase.getTestCaseInfo();
12750 m_reporter->testCaseStarting(testInfo);
12752 m_activeTestCase = &testCase;
12754 ITracker& rootTracker = m_trackerContext.startRun();
12755 assert(rootTracker.isSectionTracker());
12756 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12758 m_trackerContext.startCycle();
12759 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12760 runCurrentTest(redirectedCout, redirectedCerr);
12761 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12763 Totals deltaTotals = m_totals.delta(prevTotals);
12764 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12765 deltaTotals.assertions.failed++;
12766 deltaTotals.testCases.passed--;
12767 deltaTotals.testCases.failed++;
12769 m_totals.testCases += deltaTotals.testCases;
12770 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12776 m_activeTestCase =
nullptr;
12777 m_testCaseTracker =
nullptr;
12779 return deltaTotals;
12782 IConfigPtr RunContext::config()
const {
12786 IStreamingReporter& RunContext::reporter()
const {
12787 return *m_reporter;
12790 void RunContext::assertionEnded(AssertionResult
const & result) {
12791 if (result.getResultType() == ResultWas::Ok) {
12792 m_totals.assertions.passed++;
12793 m_lastAssertionPassed =
true;
12794 }
else if (!result.isOk()) {
12795 m_lastAssertionPassed =
false;
12796 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12797 m_totals.assertions.failedButOk++;
12799 m_totals.assertions.failed++;
12802 m_lastAssertionPassed =
true;
12807 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12809 if (result.getResultType() != ResultWas::Warning)
12810 m_messageScopes.clear();
12813 resetAssertionInfo();
12814 m_lastResult = result;
12816 void RunContext::resetAssertionInfo() {
12817 m_lastAssertionInfo.macroName = StringRef();
12818 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12821 bool RunContext::sectionStarted(SectionInfo
const & sectionInfo, Counts & assertions) {
12822 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12823 if (!sectionTracker.isOpen())
12825 m_activeSections.push_back(§ionTracker);
12827 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12829 m_reporter->sectionStarting(sectionInfo);
12831 assertions = m_totals.assertions;
12835 auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo
const& lineInfo ) -> IGeneratorTracker& {
12836 using namespace Generators;
12837 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12838 TestCaseTracking::NameAndLocation(
static_cast<std::string
>(generatorName), lineInfo ) );
12839 m_lastAssertionInfo.lineInfo = lineInfo;
12843 bool RunContext::testForMissingAssertions(Counts& assertions) {
12844 if (assertions.total() != 0)
12846 if (!m_config->warnAboutMissingAssertions())
12848 if (m_trackerContext.currentTracker().hasChildren())
12850 m_totals.assertions.failed++;
12851 assertions.failed++;
12855 void RunContext::sectionEnded(SectionEndInfo
const & endInfo) {
12856 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12857 bool missingAssertions = testForMissingAssertions(assertions);
12859 if (!m_activeSections.empty()) {
12860 m_activeSections.back()->close();
12861 m_activeSections.pop_back();
12864 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12865 m_messages.clear();
12866 m_messageScopes.clear();
12869 void RunContext::sectionEndedEarly(SectionEndInfo
const & endInfo) {
12870 if (m_unfinishedSections.empty())
12871 m_activeSections.back()->fail();
12873 m_activeSections.back()->close();
12874 m_activeSections.pop_back();
12876 m_unfinishedSections.push_back(endInfo);
12879#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12880 void RunContext::benchmarkPreparing(std::string
const& name) {
12881 m_reporter->benchmarkPreparing(name);
12883 void RunContext::benchmarkStarting( BenchmarkInfo
const& info ) {
12884 m_reporter->benchmarkStarting( info );
12886 void RunContext::benchmarkEnded( BenchmarkStats<>
const& stats ) {
12887 m_reporter->benchmarkEnded( stats );
12889 void RunContext::benchmarkFailed(std::string
const & error) {
12890 m_reporter->benchmarkFailed(error);
12894 void RunContext::pushScopedMessage(MessageInfo
const & message) {
12895 m_messages.push_back(message);
12898 void RunContext::popScopedMessage(MessageInfo
const & message) {
12899 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12902 void RunContext::emplaceUnscopedMessage( MessageBuilder
const& builder ) {
12903 m_messageScopes.emplace_back( builder );
12906 std::string RunContext::getCurrentTestName()
const {
12907 return m_activeTestCase
12908 ? m_activeTestCase->getTestCaseInfo().name
12912 const AssertionResult * RunContext::getLastResult()
const {
12913 return &(*m_lastResult);
12916 void RunContext::exceptionEarlyReported() {
12917 m_shouldReportUnexpected =
false;
12920 void RunContext::handleFatalErrorCondition( StringRef message ) {
12922 m_reporter->fatalErrorEncountered(message);
12926 AssertionResultData tempResult( ResultWas::FatalErrorCondition, {
false } );
12927 tempResult.message =
static_cast<std::string
>(message);
12928 AssertionResult result(m_lastAssertionInfo, tempResult);
12930 assertionEnded(result);
12932 handleUnfinishedSections();
12935 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12936 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12939 assertions.failed = 1;
12940 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12941 m_reporter->sectionEnded(testCaseSectionStats);
12943 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12945 Totals deltaTotals;
12946 deltaTotals.testCases.failed = 1;
12947 deltaTotals.assertions.failed = 1;
12948 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12953 m_totals.testCases.failed++;
12954 testGroupEnded(std::string(), m_totals, 1, 1);
12955 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12958 bool RunContext::lastAssertionPassed() {
12959 return m_lastAssertionPassed;
12962 void RunContext::assertionPassed() {
12963 m_lastAssertionPassed =
true;
12964 ++m_totals.assertions.passed;
12965 resetAssertionInfo();
12966 m_messageScopes.clear();
12969 bool RunContext::aborting()
const {
12970 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
12973 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12974 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12975 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12976 m_reporter->sectionStarting(testCaseSection);
12977 Counts prevAssertions = m_totals.assertions;
12978 double duration = 0;
12979 m_shouldReportUnexpected =
true;
12980 m_lastAssertionInfo = {
"TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12982 seedRng(*m_config);
12986 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12987#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12988 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12991 invokeActiveTestCase();
12993 OutputRedirect r(redirectedCout, redirectedCerr);
12995 invokeActiveTestCase();
12999 invokeActiveTestCase();
13001 duration = timer.getElapsedSeconds();
13002 } CATCH_CATCH_ANON (TestFailureException&) {
13004 } CATCH_CATCH_ALL {
13007 if( m_shouldReportUnexpected ) {
13008 AssertionReaction dummyReaction;
13009 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
13012 Counts assertions = m_totals.assertions - prevAssertions;
13013 bool missingAssertions = testForMissingAssertions(assertions);
13015 m_testCaseTracker->close();
13016 handleUnfinishedSections();
13017 m_messages.clear();
13018 m_messageScopes.clear();
13020 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13021 m_reporter->sectionEnded(testCaseSectionStats);
13024 void RunContext::invokeActiveTestCase() {
13025 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13026 m_activeTestCase->invoke();
13029 void RunContext::handleUnfinishedSections() {
13032 for (
auto it = m_unfinishedSections.rbegin(),
13033 itEnd = m_unfinishedSections.rend();
13037 m_unfinishedSections.clear();
13040 void RunContext::handleExpr(
13041 AssertionInfo
const& info,
13042 ITransientExpression
const& expr,
13043 AssertionReaction& reaction
13045 m_reporter->assertionStarting( info );
13047 bool negated = isFalseTest(
info.resultDisposition );
13048 bool result = expr.getResult() != negated;
13051 if (!m_includeSuccessfulResults) {
13055 reportExpr(info, ResultWas::Ok, &expr, negated);
13059 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
13060 populateReaction( reaction );
13063 void RunContext::reportExpr(
13064 AssertionInfo
const &info,
13065 ResultWas::OfType resultType,
13066 ITransientExpression
const *expr,
13069 m_lastAssertionInfo =
info;
13070 AssertionResultData data( resultType, LazyExpression( negated ) );
13072 AssertionResult assertionResult{
info, data };
13073 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13075 assertionEnded( assertionResult );
13078 void RunContext::handleMessage(
13079 AssertionInfo
const& info,
13080 ResultWas::OfType resultType,
13081 StringRef
const& message,
13082 AssertionReaction& reaction
13084 m_reporter->assertionStarting( info );
13086 m_lastAssertionInfo =
info;
13088 AssertionResultData data( resultType, LazyExpression(
false ) );
13089 data.message =
static_cast<std::string
>(message);
13090 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13091 assertionEnded( assertionResult );
13092 if( !assertionResult.isOk() )
13093 populateReaction( reaction );
13095 void RunContext::handleUnexpectedExceptionNotThrown(
13096 AssertionInfo
const& info,
13097 AssertionReaction& reaction
13099 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13102 void RunContext::handleUnexpectedInflightException(
13103 AssertionInfo
const& info,
13104 std::string
const& message,
13105 AssertionReaction& reaction
13107 m_lastAssertionInfo =
info;
13109 AssertionResultData data( ResultWas::ThrewException, LazyExpression(
false ) );
13110 data.message = message;
13111 AssertionResult assertionResult{
info, data };
13112 assertionEnded( assertionResult );
13113 populateReaction( reaction );
13116 void RunContext::populateReaction( AssertionReaction& reaction ) {
13117 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13118 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13121 void RunContext::handleIncomplete(
13122 AssertionInfo
const& info
13124 m_lastAssertionInfo =
info;
13126 AssertionResultData data( ResultWas::ThrewException, LazyExpression(
false ) );
13127 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13128 AssertionResult assertionResult{
info, data };
13129 assertionEnded( assertionResult );
13131 void RunContext::handleNonExpr(
13132 AssertionInfo
const &info,
13133 ResultWas::OfType resultType,
13134 AssertionReaction &reaction
13136 m_lastAssertionInfo =
info;
13138 AssertionResultData data( resultType, LazyExpression(
false ) );
13139 AssertionResult assertionResult{
info, data };
13140 assertionEnded( assertionResult );
13142 if( !assertionResult.isOk() )
13143 populateReaction( reaction );
13146 IResultCapture& getResultCapture() {
13147 if (
auto* capture = getCurrentContext().getResultCapture())
13150 CATCH_INTERNAL_ERROR(
"No result capture instance");
13153 void seedRng(IConfig
const& config) {
13154 if (config.rngSeed() != 0) {
13155 std::srand(config.rngSeed());
13156 rng().seed(config.rngSeed());
13160 unsigned int rngSeed() {
13161 return getCurrentContext().getConfig()->rngSeed();
13170 Section::Section( SectionInfo
const& info )
13172 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13177 Section::~Section() {
13178 if( m_sectionIncluded ) {
13179 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13180 if( uncaught_exceptions() )
13181 getResultCapture().sectionEndedEarly( endInfo );
13183 getResultCapture().sectionEnded( endInfo );
13188 Section::operator bool()
const {
13189 return m_sectionIncluded;
13198 SectionInfo::SectionInfo
13199 ( SourceLineInfo
const& _lineInfo,
13200 std::string
const& _name )
13202 lineInfo( _lineInfo )
13215 class Session : NonCopyable {
13219 ~Session()
override;
13221 void showHelp()
const;
13222 void libIdentify();
13224 int applyCommandLine(
int argc,
char const *
const * argv );
13225 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13226 int applyCommandLine(
int argc,
wchar_t const *
const * argv );
13229 void useConfigData( ConfigData
const& configData );
13231 template<
typename CharT>
13232 int run(
int argc, CharT
const *
const argv[]) {
13233 if (m_startupExceptions)
13235 int returnCode = applyCommandLine(argc, argv);
13236 if (returnCode == 0)
13237 returnCode = run();
13243 clara::Parser
const& cli()
const;
13244 void cli( clara::Parser
const& newParser );
13245 ConfigData& configData();
13250 clara::Parser m_cli;
13251 ConfigData m_configData;
13252 std::shared_ptr<Config> m_config;
13253 bool m_startupExceptions =
false;
13267 Version( Version
const& ) =
delete;
13268 Version& operator=( Version
const& ) =
delete;
13269 Version(
unsigned int _majorVersion,
13270 unsigned int _minorVersion,
13271 unsigned int _patchNumber,
13272 char const *
const _branchName,
13273 unsigned int _buildNumber );
13275 unsigned int const majorVersion;
13276 unsigned int const minorVersion;
13277 unsigned int const patchNumber;
13280 char const *
const branchName;
13281 unsigned int const buildNumber;
13283 friend std::ostream&
operator << ( std::ostream& os, Version
const& version );
13286 Version
const& libraryVersion();
13298 const int MaxExitCode = 255;
13300 IStreamingReporterPtr createReporter(std::string
const& reporterName, IConfigPtr
const& config) {
13301 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13302 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13307 IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13308 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13309 return createReporter(config->getReporterName(), config);
13317 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13318 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13319 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13320 for (
auto const& listener : listeners) {
13321 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13323 multi.addReporter(createReporter(config->getReporterName(), config));
13329 explicit TestGroup(std::shared_ptr<Config>
const& config)
13331 , m_context{config, makeReporter(config)}
13333 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13334 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13335 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13337 if (m_matches.empty() && invalidArgs.empty()) {
13338 for (
auto const& test : allTestCases)
13339 if (!test.isHidden())
13340 m_tests.emplace(&test);
13342 for (
auto const& match : m_matches)
13343 m_tests.insert(match.tests.begin(), match.tests.end());
13348 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13350 m_context.testGroupStarting(m_config->name(), 1, 1);
13351 for (
auto const& testCase : m_tests) {
13352 if (!m_context.aborting())
13353 totals += m_context.runTest(*testCase);
13355 m_context.reporter().skipTest(*testCase);
13358 for (
auto const& match : m_matches) {
13359 if (match.tests.empty()) {
13360 m_context.reporter().noMatchingTestCases(match.name);
13365 if (!invalidArgs.empty()) {
13366 for (
auto const& invalidArg: invalidArgs)
13367 m_context.reporter().reportInvalidArguments(invalidArg);
13370 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13375 using Tests = std::set<TestCase const*>;
13377 std::shared_ptr<Config> m_config;
13378 RunContext m_context;
13380 TestSpec::Matches m_matches;
13384 auto& tests =
const_cast<std::vector<TestCase>&
>(getAllTestCasesSorted(config));
13385 for (
auto& testCase : tests) {
13386 auto tags = testCase.tags;
13388 std::string filename = testCase.lineInfo.file;
13389 auto lastSlash = filename.find_last_of(
"\\/");
13390 if (lastSlash != std::string::npos) {
13391 filename.erase(0, lastSlash);
13396 filename.insert(0,
"#");
13399 auto lastDot = filename.find_last_of(
'.');
13400 if (lastDot != std::string::npos) {
13401 filename.erase(lastDot);
13404 tags.push_back(std::move(filename));
13405 setTags(testCase, tags);
13411 Session::Session() {
13412 static bool alreadyInstantiated =
false;
13413 if( alreadyInstantiated ) {
13414 CATCH_TRY { CATCH_INTERNAL_ERROR(
"Only one instance of Catch::Session can ever be used" ); }
13415 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13419#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13420 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13421 if ( !exceptions.empty() ) {
13423 getCurrentMutableContext().setConfig(m_config);
13425 m_startupExceptions =
true;
13426 Colour colourGuard( Colour::Red );
13427 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13429 for (
const auto& ex_ptr : exceptions ) {
13431 std::rethrow_exception(ex_ptr);
13432 }
catch ( std::exception
const& ex ) {
13433 Catch::cerr() << Column( ex.what() ).indent(2) <<
'\n';
13439 alreadyInstantiated =
true;
13440 m_cli = makeCommandLineParser( m_configData );
13442 Session::~Session() {
13446 void Session::showHelp()
const {
13448 <<
"\nCatch v" << libraryVersion() <<
"\n"
13449 << m_cli << std::endl
13450 <<
"For more detailed usage please see the project docs\n" << std::endl;
13452 void Session::libIdentify() {
13454 << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n"
13455 << std::left << std::setw(16) <<
"category: " <<
"testframework\n"
13456 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n"
13457 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13460 int Session::applyCommandLine(
int argc,
char const *
const * argv ) {
13461 if( m_startupExceptions )
13464 auto result = m_cli.parse( clara::Args( argc, argv ) );
13467 getCurrentMutableContext().setConfig(m_config);
13469 << Colour( Colour::Red )
13470 <<
"\nError(s) in input:\n"
13471 << Column( result.errorMessage() ).indent( 2 )
13473 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13474 return MaxExitCode;
13477 if( m_configData.showHelp )
13479 if( m_configData.libIdentify )
13485#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13486 int Session::applyCommandLine(
int argc,
wchar_t const *
const * argv ) {
13488 char **utf8Argv =
new char *[ argc ];
13490 for (
int i = 0; i < argc; ++i ) {
13491 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr );
13493 utf8Argv[ i ] =
new char[ bufSize ];
13495 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr );
13498 int returnCode = applyCommandLine( argc, utf8Argv );
13500 for (
int i = 0; i < argc; ++i )
13501 delete [] utf8Argv[ i ];
13503 delete [] utf8Argv;
13509 void Session::useConfigData( ConfigData
const& configData ) {
13510 m_configData = configData;
13514 int Session::run() {
13515 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13516 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13517 static_cast<void>(std::getchar());
13519 int exitCode = runInternal();
13520 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13521 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13522 static_cast<void>(std::getchar());
13527 clara::Parser
const& Session::cli()
const {
13530 void Session::cli( clara::Parser
const& newParser ) {
13533 ConfigData& Session::configData() {
13534 return m_configData;
13536 Config& Session::config() {
13538 m_config = std::make_shared<Config>( m_configData );
13542 int Session::runInternal() {
13543 if( m_startupExceptions )
13546 if (m_configData.showHelp || m_configData.libIdentify) {
13553 seedRng( *m_config );
13555 if( m_configData.filenamesAsTags )
13556 applyFilenamesAsTags( *m_config );
13559 if( Option<std::size_t> listed = list( m_config ) )
13560 return (std::min) (MaxExitCode,
static_cast<int>(*listed));
13562 TestGroup tests { m_config };
13563 auto const totals = tests.execute();
13565 if( m_config->warnAboutNoTests() && totals.error == -1 )
13571 return (std::min) (MaxExitCode, (std::max) (totals.error,
static_cast<int>(totals.assertions.failed)));
13573#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13574 catch( std::exception& ex ) {
13575 Catch::cerr() << ex.what() << std::endl;
13576 return MaxExitCode;
13590 static auto getSingletons() -> std::vector<ISingleton*>*& {
13591 static std::vector<ISingleton*>* g_singletons =
nullptr;
13592 if( !g_singletons )
13593 g_singletons =
new std::vector<ISingleton*>();
13594 return g_singletons;
13598 ISingleton::~ISingleton() {}
13600 void addSingleton(ISingleton* singleton ) {
13601 getSingletons()->push_back( singleton );
13603 void cleanupSingletons() {
13604 auto& singletons = getSingletons();
13605 for(
auto singleton : *singletons )
13608 singletons =
nullptr;
13615#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13617void StartupExceptionRegistry::add( std::exception_ptr
const& exception )
noexcept {
13619 m_exceptions.push_back(exception);
13620 } CATCH_CATCH_ALL {
13626 std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions() const noexcept {
13627 return m_exceptions;
13644 Catch::IStream::~IStream() =
default;
13646 namespace Detail {
namespace {
13647 template<
typename WriterF, std::
size_t bufferSize=256>
13648 class StreamBufImpl :
public std::streambuf {
13649 char data[bufferSize];
13654 setp( data, data +
sizeof(data) );
13657 ~StreamBufImpl() noexcept {
13658 StreamBufImpl::sync();
13662 int overflow(
int c )
override {
13666 if( pbase() == epptr() )
13667 m_writer( std::string( 1,
static_cast<char>( c ) ) );
13669 sputc(
static_cast<char>( c ) );
13674 int sync()
override {
13675 if( pbase() != pptr() ) {
13676 m_writer( std::string( pbase(),
static_cast<std::string::size_type
>( pptr() - pbase() ) ) );
13677 setp( pbase(), epptr() );
13685 struct OutputDebugWriter {
13687 void operator()( std::string
const&str ) {
13688 writeToDebugConsole( str );
13694 class FileStream :
public IStream {
13695 mutable std::ofstream m_ofs;
13697 FileStream( StringRef filename ) {
13698 m_ofs.open( filename.c_str() );
13699 CATCH_ENFORCE( !m_ofs.fail(),
"Unable to open file: '" << filename <<
"'" );
13701 ~FileStream()
override =
default;
13703 std::ostream& stream()
const override {
13710 class CoutStream :
public IStream {
13711 mutable std::ostream m_os;
13715 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13716 ~CoutStream()
override =
default;
13719 std::ostream& stream()
const override {
return m_os; }
13724 class DebugOutStream :
public IStream {
13725 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13726 mutable std::ostream m_os;
13729 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13730 m_os( m_streamBuf.get() )
13733 ~DebugOutStream()
override =
default;
13736 std::ostream& stream()
const override {
return m_os; }
13743 auto makeStream( StringRef
const &filename ) -> IStream
const* {
13744 if( filename.empty() )
13745 return new Detail::CoutStream();
13746 else if( filename[0] ==
'%' ) {
13747 if( filename ==
"%debug" )
13748 return new Detail::DebugOutStream();
13750 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'" );
13753 return new Detail::FileStream( filename );
13757 struct StringStreams {
13758 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13759 std::vector<std::size_t> m_unused;
13760 std::ostringstream m_referenceStream;
13762 auto add() -> std::size_t {
13763 if( m_unused.empty() ) {
13764 m_streams.push_back( std::unique_ptr<std::ostringstream>(
new std::ostringstream ) );
13765 return m_streams.size()-1;
13768 auto index = m_unused.back();
13769 m_unused.pop_back();
13774 void release( std::size_t index ) {
13775 m_streams[index]->copyfmt( m_referenceStream );
13776 m_unused.push_back(index);
13780 ReusableStringStream::ReusableStringStream()
13781 : m_index( Singleton<StringStreams>::getMutable().
add() ),
13782 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13785 ReusableStringStream::~ReusableStringStream() {
13786 static_cast<std::ostringstream*
>( m_oss )->str(
"");
13788 Singleton<StringStreams>::getMutable().release( m_index );
13791 auto ReusableStringStream::str() const -> std::
string {
13792 return static_cast<std::ostringstream*
>( m_oss )->str();
13797#ifndef CATCH_CONFIG_NOSTDOUT
13798 std::ostream& cout() {
return std::cout; }
13799 std::ostream& cerr() {
return std::cerr; }
13800 std::ostream& clog() {
return std::clog; }
13806#include <algorithm>
13815 char toLowerCh(
char c) {
13816 return static_cast<char>( std::tolower(
static_cast<unsigned char>(c) ) );
13820 bool startsWith( std::string
const& s, std::string
const& prefix ) {
13821 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13823 bool startsWith( std::string
const& s,
char prefix ) {
13824 return !s.empty() && s[0] == prefix;
13826 bool endsWith( std::string
const& s, std::string
const& suffix ) {
13827 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13829 bool endsWith( std::string
const& s,
char suffix ) {
13830 return !s.empty() && s[s.size()-1] == suffix;
13832 bool contains( std::string
const& s, std::string
const& infix ) {
13833 return s.find( infix ) != std::string::npos;
13835 void toLowerInPlace( std::string& s ) {
13836 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13838 std::string toLower( std::string
const& s ) {
13839 std::string lc = s;
13840 toLowerInPlace( lc );
13843 std::string trim( std::string
const& str ) {
13844 static char const* whitespaceChars =
"\n\r\t ";
13845 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13846 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13848 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13851 StringRef trim(StringRef ref) {
13852 const auto is_ws = [](
char c) {
13853 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r';
13855 size_t real_begin = 0;
13856 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13857 size_t real_end = ref.size();
13858 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13860 return ref.substr(real_begin, real_end - real_begin);
13863 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
13864 bool replaced =
false;
13865 std::size_t i = str.find( replaceThis );
13866 while( i != std::string::npos ) {
13868 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13869 if( i < str.size()-withThis.size() )
13870 i = str.find( replaceThis, i+withThis.size() );
13872 i = std::string::npos;
13877 std::vector<StringRef> splitStringRef( StringRef str,
char delimiter ) {
13878 std::vector<StringRef> subStrings;
13879 std::size_t start = 0;
13880 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13881 if( str[pos] == delimiter ) {
13882 if( pos - start > 1 )
13883 subStrings.push_back( str.substr( start, pos-start ) );
13887 if( start < str.size() )
13888 subStrings.push_back( str.substr( start, str.size()-start ) );
13892 pluralise::pluralise( std::size_t count, std::string
const& label )
13893 : m_count(
count ),
13897 std::ostream& operator << ( std::ostream& os, pluralise
const& pluraliser ) {
13898 os << pluraliser.m_count <<
' ' << pluraliser.m_label;
13899 if( pluraliser.m_count != 1 )
13908#include <algorithm>
13914 StringRef::StringRef(
char const* rawChars ) noexcept
13915 : StringRef( rawChars,
static_cast<StringRef::size_type
>(std::strlen(rawChars) ) )
13918 auto StringRef::c_str() const ->
char const* {
13919 CATCH_ENFORCE(isNullTerminated(),
"Called StringRef::c_str() on a non-null-terminated instance");
13922 auto StringRef::data() const noexcept ->
char const* {
13926 auto StringRef::substr( size_type start, size_type size )
const noexcept -> StringRef {
13927 if (start < m_size) {
13928 return StringRef(m_start + start, (std::min)(m_size - start, size));
13930 return StringRef();
13933 auto StringRef::operator == ( StringRef
const& other )
const noexcept ->
bool {
13934 return m_size == other.m_size
13935 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13938 auto operator << ( std::ostream& os, StringRef
const& str ) -> std::ostream& {
13939 return os.write(str.data(), str.size());
13942 auto operator+=( std::string& lhs, StringRef
const& rhs ) -> std::string& {
13943 lhs.append(rhs.data(), rhs.size());
13952 TagAlias::TagAlias(std::string
const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13959 RegistrarForTagAliases::RegistrarForTagAliases(
char const* alias,
char const* tag, SourceLineInfo
const& lineInfo) {
13961 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13962 } CATCH_CATCH_ALL {
13964 getMutableRegistryHub().registerStartupException();
13976 TagAliasRegistry::~TagAliasRegistry() {}
13978 TagAlias
const* TagAliasRegistry::find( std::string
const& alias )
const {
13979 auto it = m_registry.find( alias );
13980 if( it != m_registry.end() )
13981 return &(it->second);
13986 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
13987 std::string expandedTestSpec = unexpandedTestSpec;
13988 for(
auto const& registryKvp : m_registry ) {
13989 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13990 if( pos != std::string::npos ) {
13991 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13992 registryKvp.second.tag +
13993 expandedTestSpec.substr( pos + registryKvp.first.size() );
13996 return expandedTestSpec;
13999 void TagAliasRegistry::add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo ) {
14000 CATCH_ENFORCE( startsWith(alias,
"[@") && endsWith(alias,
']'),
14001 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n" << lineInfo );
14003 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14004 "error: tag alias, '" << alias <<
"' already registered.\n"
14005 <<
"\tFirst seen at: " << find(alias)->lineInfo <<
"\n"
14006 <<
"\tRedefined at: " << lineInfo );
14009 ITagAliasRegistry::~ITagAliasRegistry() {}
14011 ITagAliasRegistry
const& ITagAliasRegistry::get() {
14012 return getRegistryHub().getTagAliasRegistry();
14020#include <exception>
14021#include <algorithm>
14027 TestCaseInfo::SpecialProperties parseSpecialTag( std::string
const& tag ) {
14028 if( startsWith( tag,
'.' ) ||
14030 return TestCaseInfo::IsHidden;
14031 else if( tag ==
"!throws" )
14032 return TestCaseInfo::Throws;
14033 else if( tag ==
"!shouldfail" )
14034 return TestCaseInfo::ShouldFail;
14035 else if( tag ==
"!mayfail" )
14036 return TestCaseInfo::MayFail;
14037 else if( tag ==
"!nonportable" )
14038 return TestCaseInfo::NonPortable;
14039 else if( tag ==
"!benchmark" )
14040 return static_cast<TestCaseInfo::SpecialProperties
>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
14042 return TestCaseInfo::None;
14044 bool isReservedTag( std::string
const& tag ) {
14045 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum(
static_cast<unsigned char>(tag[0]) );
14047 void enforceNotReservedTag( std::string
const& tag, SourceLineInfo
const& _lineInfo ) {
14048 CATCH_ENFORCE( !isReservedTag(tag),
14049 "Tag name: [" << tag <<
"] is not allowed.\n"
14050 <<
"Tag names starting with non alphanumeric characters are reserved\n"
14055 TestCase makeTestCase( ITestInvoker* _testCase,
14056 std::string
const& _className,
14057 NameAndTags
const& nameAndTags,
14058 SourceLineInfo
const& _lineInfo )
14060 bool isHidden =
false;
14063 std::vector<std::string> tags;
14064 std::string desc, tag;
14065 bool inTag =
false;
14066 for (
char c : nameAndTags.tags) {
14075 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14076 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14078 else if( prop == TestCaseInfo::None )
14079 enforceNotReservedTag( tag, _lineInfo );
14084 if (startsWith(tag,
'.') && tag.size() > 1) {
14087 tags.push_back( tag );
14097 tags.insert( tags.end(), {
".",
"!hide" } );
14100 TestCaseInfo
info(
static_cast<std::string
>(nameAndTags.name), _className, desc, tags, _lineInfo );
14101 return TestCase( _testCase, std::move(info) );
14104 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14105 std::sort(begin(tags), end(tags));
14106 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14107 testCaseInfo.lcaseTags.clear();
14109 for(
auto const& tag : tags ) {
14110 std::string lcaseTag = toLower( tag );
14111 testCaseInfo.properties =
static_cast<TestCaseInfo::SpecialProperties
>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14112 testCaseInfo.lcaseTags.push_back( lcaseTag );
14114 testCaseInfo.tags = std::move(tags);
14117 TestCaseInfo::TestCaseInfo( std::string
const& _name,
14118 std::string
const& _className,
14119 std::string
const& _description,
14120 std::vector<std::string>
const& _tags,
14121 SourceLineInfo
const& _lineInfo )
14123 className( _className ),
14124 description( _description ),
14125 lineInfo( _lineInfo ),
14128 setTags( *
this, _tags );
14131 bool TestCaseInfo::isHidden()
const {
14132 return ( properties & IsHidden ) != 0;
14134 bool TestCaseInfo::throws()
const {
14135 return ( properties & Throws ) != 0;
14137 bool TestCaseInfo::okToFail()
const {
14138 return ( properties & (ShouldFail | MayFail ) ) != 0;
14140 bool TestCaseInfo::expectedToFail()
const {
14141 return ( properties & (ShouldFail ) ) != 0;
14144 std::string TestCaseInfo::tagsAsString()
const {
14147 std::size_t full_size = 2 * tags.size();
14148 for (
const auto& tag : tags) {
14149 full_size += tag.size();
14151 ret.reserve(full_size);
14152 for (
const auto& tag : tags) {
14153 ret.push_back(
'[');
14155 ret.push_back(
']');
14161 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(
info) ), test( testCase ) {}
14163 TestCase TestCase::withName( std::string
const& _newName )
const {
14164 TestCase other( *
this );
14165 other.name = _newName;
14169 void TestCase::invoke()
const {
14173 bool TestCase::operator == ( TestCase
const& other )
const {
14174 return test.get() == other.test.get() &&
14175 name == other.name &&
14176 className == other.className;
14179 bool TestCase::operator < ( TestCase
const& other )
const {
14180 return name < other.name;
14183 TestCaseInfo
const& TestCase::getTestCaseInfo()
const
14192#include <algorithm>
14198 struct TestHasher {
14199 using hash_t = uint64_t;
14201 explicit TestHasher( hash_t hashSuffix ):
14202 m_hashSuffix{ hashSuffix } {}
14204 uint32_t operator()( TestCase
const& t )
const {
14206 const hash_t prime = 1099511628211u;
14207 hash_t
hash = 14695981039346656037u;
14208 for (
const char c : t.name ) {
14212 hash ^= m_hashSuffix;
14214 const uint32_t low{
static_cast<uint32_t
>(
hash ) };
14215 const uint32_t high{
static_cast<uint32_t
>(
hash >> 32 ) };
14220 hash_t m_hashSuffix;
14224 std::vector<TestCase> sortTests( IConfig
const& config, std::vector<TestCase>
const& unsortedTestCases ) {
14225 switch( config.runOrder() ) {
14226 case RunTests::InDeclarationOrder:
14230 case RunTests::InLexicographicalOrder: {
14231 std::vector<TestCase> sorted = unsortedTestCases;
14232 std::sort( sorted.begin(), sorted.end() );
14236 case RunTests::InRandomOrder: {
14238 TestHasher h{ config.rngSeed() };
14240 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14241 std::vector<hashedTest> indexed_tests;
14242 indexed_tests.reserve( unsortedTestCases.size() );
14244 for (
auto const& testCase : unsortedTestCases) {
14245 indexed_tests.emplace_back(h(testCase), &testCase);
14248 std::sort(indexed_tests.begin(), indexed_tests.end(),
14249 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14250 if (lhs.first == rhs.first) {
14251 return lhs.second->name < rhs.second->name;
14253 return lhs.first < rhs.first;
14256 std::vector<TestCase> sorted;
14257 sorted.reserve( indexed_tests.size() );
14259 for (
auto const& hashed : indexed_tests) {
14260 sorted.emplace_back(*hashed.second);
14266 return unsortedTestCases;
14269 bool isThrowSafe( TestCase
const& testCase, IConfig
const& config ) {
14270 return !testCase.throws() || config.allowThrows();
14273 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config ) {
14274 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14277 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
14278 std::set<TestCase> seenFunctions;
14279 for(
auto const& function : functions ) {
14280 auto prev = seenFunctions.insert( function );
14281 CATCH_ENFORCE( prev.second,
14282 "error: TEST_CASE( \"" << function.name <<
"\" ) already defined.\n"
14283 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
"\n"
14284 <<
"\tRedefined at " << function.getTestCaseInfo().lineInfo );
14288 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config ) {
14289 std::vector<TestCase> filtered;
14290 filtered.reserve( testCases.size() );
14291 for (
auto const& testCase : testCases) {
14292 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14293 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14294 filtered.push_back(testCase);
14299 std::vector<TestCase>
const& getAllTestCasesSorted( IConfig
const& config ) {
14300 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14303 void TestRegistry::registerTest( TestCase
const& testCase ) {
14304 std::string name = testCase.getTestCaseInfo().name;
14305 if( name.empty() ) {
14306 ReusableStringStream rss;
14307 rss <<
"Anonymous test case " << ++m_unnamedCount;
14308 return registerTest( testCase.withName( rss.str() ) );
14310 m_functions.push_back( testCase );
14313 std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14314 return m_functions;
14316 std::vector<TestCase>
const& TestRegistry::getAllTestsSorted( IConfig
const& config )
const {
14317 if( m_sortedFunctions.empty() )
14318 enforceNoDuplicateTestCases( m_functions );
14320 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14321 m_sortedFunctions = sortTests( config, m_functions );
14322 m_currentSortOrder = config.runOrder();
14324 return m_sortedFunctions;
14328 TestInvokerAsFunction::TestInvokerAsFunction(
void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14330 void TestInvokerAsFunction::invoke()
const {
14331 m_testAsFunction();
14334 std::string extractClassName( StringRef
const& classOrQualifiedMethodName ) {
14335 std::string className(classOrQualifiedMethodName);
14336 if( startsWith( className,
'&' ) )
14338 std::size_t lastColons = className.rfind(
"::" );
14339 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
14340 if( penultimateColons == std::string::npos )
14341 penultimateColons = 1;
14342 className = className.substr( penultimateColons, lastColons-penultimateColons );
14351#include <algorithm>
14353#include <stdexcept>
14357#if defined(__clang__)
14358# pragma clang diagnostic push
14359# pragma clang diagnostic ignored "-Wexit-time-destructors"
14363namespace TestCaseTracking {
14365 NameAndLocation::NameAndLocation( std::string
const& _name, SourceLineInfo
const& _location )
14367 location( _location )
14370 ITracker::~ITracker() =
default;
14372 ITracker& TrackerContext::startRun() {
14373 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation(
"{root}", CATCH_INTERNAL_LINEINFO ), *
this,
nullptr );
14374 m_currentTracker =
nullptr;
14375 m_runState = Executing;
14376 return *m_rootTracker;
14379 void TrackerContext::endRun() {
14380 m_rootTracker.reset();
14381 m_currentTracker =
nullptr;
14382 m_runState = NotStarted;
14385 void TrackerContext::startCycle() {
14386 m_currentTracker = m_rootTracker.get();
14387 m_runState = Executing;
14389 void TrackerContext::completeCycle() {
14390 m_runState = CompletedCycle;
14393 bool TrackerContext::completedCycle()
const {
14394 return m_runState == CompletedCycle;
14396 ITracker& TrackerContext::currentTracker() {
14397 return *m_currentTracker;
14399 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14400 m_currentTracker = tracker;
14403 TrackerBase::TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14404 ITracker(nameAndLocation),
14409 bool TrackerBase::isComplete()
const {
14410 return m_runState == CompletedSuccessfully || m_runState == Failed;
14412 bool TrackerBase::isSuccessfullyCompleted()
const {
14413 return m_runState == CompletedSuccessfully;
14415 bool TrackerBase::isOpen()
const {
14416 return m_runState != NotStarted && !isComplete();
14418 bool TrackerBase::hasChildren()
const {
14419 return !m_children.empty();
14422 void TrackerBase::addChild( ITrackerPtr
const& child ) {
14423 m_children.push_back( child );
14426 ITrackerPtr TrackerBase::findChild( NameAndLocation
const& nameAndLocation ) {
14427 auto it = std::find_if( m_children.begin(), m_children.end(),
14428 [&nameAndLocation]( ITrackerPtr
const& tracker ){
14430 tracker->nameAndLocation().location == nameAndLocation.location &&
14431 tracker->nameAndLocation().name == nameAndLocation.name;
14433 return( it != m_children.end() )
14437 ITracker& TrackerBase::parent() {
14438 assert( m_parent );
14442 void TrackerBase::openChild() {
14443 if( m_runState != ExecutingChildren ) {
14444 m_runState = ExecutingChildren;
14446 m_parent->openChild();
14450 bool TrackerBase::isSectionTracker()
const {
return false; }
14451 bool TrackerBase::isGeneratorTracker()
const {
return false; }
14453 void TrackerBase::open() {
14454 m_runState = Executing;
14457 m_parent->openChild();
14460 void TrackerBase::close() {
14463 while( &m_ctx.currentTracker() !=
this )
14464 m_ctx.currentTracker().close();
14466 switch( m_runState ) {
14467 case NeedsAnotherRun:
14471 m_runState = CompletedSuccessfully;
14473 case ExecutingChildren:
14474 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr
const& t){ return t->isComplete(); }) )
14475 m_runState = CompletedSuccessfully;
14479 case CompletedSuccessfully:
14481 CATCH_INTERNAL_ERROR(
"Illogical state: " << m_runState );
14484 CATCH_INTERNAL_ERROR(
"Unknown state: " << m_runState );
14487 m_ctx.completeCycle();
14489 void TrackerBase::fail() {
14490 m_runState = Failed;
14492 m_parent->markAsNeedingAnotherRun();
14494 m_ctx.completeCycle();
14496 void TrackerBase::markAsNeedingAnotherRun() {
14497 m_runState = NeedsAnotherRun;
14500 void TrackerBase::moveToParent() {
14501 assert( m_parent );
14502 m_ctx.setCurrentTracker( m_parent );
14504 void TrackerBase::moveToThis() {
14505 m_ctx.setCurrentTracker(
this );
14508 SectionTracker::SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14509 : TrackerBase( nameAndLocation, ctx, parent ),
14510 m_trimmed_name(trim(nameAndLocation.name))
14513 while( !parent->isSectionTracker() )
14514 parent = &parent->parent();
14516 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
14517 addNextFilters( parentSection.m_filters );
14521 bool SectionTracker::isComplete()
const {
14522 bool complete =
true;
14524 if (m_filters.empty()
14525 || m_filters[0] ==
""
14526 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14527 complete = TrackerBase::isComplete();
14532 bool SectionTracker::isSectionTracker()
const {
return true; }
14534 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
14535 std::shared_ptr<SectionTracker> section;
14537 ITracker& currentTracker = ctx.currentTracker();
14538 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14539 assert( childTracker );
14540 assert( childTracker->isSectionTracker() );
14541 section = std::static_pointer_cast<SectionTracker>( childTracker );
14544 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14545 currentTracker.addChild( section );
14547 if( !ctx.completedCycle() )
14548 section->tryOpen();
14552 void SectionTracker::tryOpen() {
14553 if( !isComplete() )
14557 void SectionTracker::addInitialFilters( std::vector<std::string>
const& filters ) {
14558 if( !filters.empty() ) {
14559 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14560 m_filters.emplace_back(
"");
14561 m_filters.emplace_back(
"");
14562 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14565 void SectionTracker::addNextFilters( std::vector<std::string>
const& filters ) {
14566 if( filters.size() > 1 )
14567 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14570 std::vector<std::string>
const& SectionTracker::getFilters()
const {
14574 std::string
const& SectionTracker::trimmedName()
const {
14575 return m_trimmed_name;
14580using TestCaseTracking::ITracker;
14581using TestCaseTracking::TrackerContext;
14582using TestCaseTracking::SectionTracker;
14586#if defined(__clang__)
14587# pragma clang diagnostic pop
14594 auto makeTestInvoker(
void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14595 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14598 NameAndTags::NameAndTags( StringRef
const& name_ , StringRef
const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14600 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo
const& lineInfo, StringRef
const& classOrMethod, NameAndTags
const& nameAndTags )
noexcept {
14602 getMutableRegistryHub()
14606 extractClassName( classOrMethod ),
14609 } CATCH_CATCH_ALL {
14611 getMutableRegistryHub().registerStartupException();
14615 AutoReg::~AutoReg() =
default;
14620#include <algorithm>
14627 TestSpec::Pattern::Pattern( std::string
const& name )
14631 TestSpec::Pattern::~Pattern() =
default;
14633 std::string
const& TestSpec::Pattern::name()
const {
14637 TestSpec::NamePattern::NamePattern( std::string
const& name, std::string
const& filterString )
14638 : Pattern( filterString )
14639 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14642 bool TestSpec::NamePattern::matches( TestCaseInfo
const& testCase )
const {
14643 return m_wildcardPattern.matches( testCase.name );
14646 TestSpec::TagPattern::TagPattern( std::string
const& tag, std::string
const& filterString )
14647 : Pattern( filterString )
14648 , m_tag( toLower( tag ) )
14651 bool TestSpec::TagPattern::matches( TestCaseInfo
const& testCase )
const {
14652 return std::find(begin(testCase.lcaseTags),
14653 end(testCase.lcaseTags),
14654 m_tag) != end(testCase.lcaseTags);
14657 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr
const& underlyingPattern )
14658 : Pattern( underlyingPattern->name() )
14659 , m_underlyingPattern( underlyingPattern )
14662 bool TestSpec::ExcludedPattern::matches( TestCaseInfo
const& testCase )
const {
14663 return !m_underlyingPattern->matches( testCase );
14666 bool TestSpec::Filter::matches( TestCaseInfo
const& testCase )
const {
14667 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr
const& p ){ return p->matches( testCase ); } );
14670 std::string TestSpec::Filter::name()
const {
14672 for(
auto const& p : m_patterns )
14677 bool TestSpec::hasFilters()
const {
14678 return !m_filters.empty();
14681 bool TestSpec::matches( TestCaseInfo
const& testCase )
const {
14682 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter
const& f ){ return f.matches( testCase ); } );
14685 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase>
const& testCases, IConfig
const& config )
const
14687 Matches matches( m_filters.size() );
14688 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter
const& filter ){
14689 std::vector<TestCase const*> currentMatches;
14690 for( auto const& test : testCases )
14691 if( isThrowSafe( test, config ) && filter.matches( test ) )
14692 currentMatches.emplace_back( &test );
14693 return FilterMatch{ filter.name(), currentMatches };
14698 const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const{
14699 return (m_invalidArgs);
14708 TestSpecParser::TestSpecParser( ITagAliasRegistry
const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14710 TestSpecParser& TestSpecParser::parse( std::string
const& arg ) {
14712 m_exclusion =
false;
14713 m_arg = m_tagAliases->expandAliases( arg );
14714 m_escapeChars.clear();
14715 m_substring.reserve(m_arg.size());
14716 m_patternName.reserve(m_arg.size());
14717 m_realPatternPos = 0;
14719 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14721 if( !visitChar( m_arg[m_pos] ) ){
14722 m_testSpec.m_invalidArgs.push_back(arg);
14728 TestSpec TestSpecParser::testSpec() {
14732 bool TestSpecParser::visitChar(
char c ) {
14733 if( (m_mode != EscapedName) && (c ==
'\\') ) {
14735 addCharToPattern(c);
14737 }
else if((m_mode != EscapedName) && (c ==
',') ) {
14743 if( processNoneChar( c ) )
14747 processNameChar( c );
14751 addCharToPattern(c);
14756 if( processOtherChar( c ) )
14762 if( !isControlChar( c ) ) {
14763 m_patternName += c;
14764 m_realPatternPos++;
14770 bool TestSpecParser::processNoneChar(
char c ) {
14775 m_exclusion =
true;
14778 startNewMode(
Tag );
14781 startNewMode( QuotedName );
14784 startNewMode( Name );
14788 void TestSpecParser::processNameChar(
char c ) {
14790 if( m_substring ==
"exclude:" )
14791 m_exclusion =
true;
14794 startNewMode(
Tag );
14797 bool TestSpecParser::processOtherChar(
char c ) {
14798 if( !isControlChar( c ) )
14804 void TestSpecParser::startNewMode( Mode mode ) {
14807 void TestSpecParser::endMode() {
14811 return addNamePattern();
14813 return addTagPattern();
14815 revertBackToLastMode();
14819 return startNewMode( None );
14822 void TestSpecParser::escape() {
14824 m_mode = EscapedName;
14825 m_escapeChars.push_back(m_realPatternPos);
14827 bool TestSpecParser::isControlChar(
char c )
const {
14840 return c ==
'[' || c ==
']';
14844 void TestSpecParser::addFilter() {
14845 if( !m_currentFilter.m_patterns.empty() ) {
14846 m_testSpec.m_filters.push_back( m_currentFilter );
14847 m_currentFilter = TestSpec::Filter();
14851 void TestSpecParser::saveLastMode() {
14855 void TestSpecParser::revertBackToLastMode() {
14859 bool TestSpecParser::separate() {
14860 if( (m_mode==QuotedName) || (m_mode==
Tag) ){
14863 m_pos = m_arg.size();
14864 m_substring.clear();
14865 m_patternName.clear();
14866 m_realPatternPos = 0;
14874 std::string TestSpecParser::preprocessPattern() {
14875 std::string token = m_patternName;
14876 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14877 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14878 m_escapeChars.clear();
14879 if (startsWith(token,
"exclude:")) {
14880 m_exclusion =
true;
14881 token = token.substr(8);
14884 m_patternName.clear();
14885 m_realPatternPos = 0;
14890 void TestSpecParser::addNamePattern() {
14891 auto token = preprocessPattern();
14893 if (!token.empty()) {
14894 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14896 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14897 m_currentFilter.m_patterns.push_back(pattern);
14899 m_substring.clear();
14900 m_exclusion =
false;
14904 void TestSpecParser::addTagPattern() {
14905 auto token = preprocessPattern();
14907 if (!token.empty()) {
14910 if (token.size() > 1 && token[0] ==
'.') {
14911 token.erase(token.begin());
14912 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14914 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14916 m_currentFilter.m_patterns.push_back(pattern);
14919 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14922 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14924 m_currentFilter.m_patterns.push_back(pattern);
14926 m_substring.clear();
14927 m_exclusion =
false;
14931 TestSpec parseTestSpec( std::string
const& arg ) {
14932 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14941static const uint64_t nanosecondsInSecond = 1000000000;
14945 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14946 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14950 auto estimateClockResolution() -> uint64_t {
14952 static const uint64_t iterations = 1000000;
14954 auto startTime = getCurrentNanosecondsSinceEpoch();
14956 for( std::size_t i = 0; i < iterations; ++i ) {
14959 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14961 ticks = getCurrentNanosecondsSinceEpoch();
14962 }
while( ticks == baseTicks );
14964 auto delta = ticks - baseTicks;
14970 if (ticks > startTime + 3 * nanosecondsInSecond) {
14971 return sum / ( i + 1u );
14977 return sum/iterations;
14980 auto getEstimatedClockResolution() -> uint64_t {
14981 static auto s_resolution = estimateClockResolution();
14982 return s_resolution;
14985 void Timer::start() {
14986 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14988 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14989 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14991 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14992 return getElapsedNanoseconds()/1000;
14994 auto Timer::getElapsedMilliseconds() const ->
unsigned int {
14995 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14997 auto Timer::getElapsedSeconds() const ->
double {
14998 return getElapsedMicroseconds()/1000000.0;
15005#if defined(__clang__)
15006# pragma clang diagnostic push
15007# pragma clang diagnostic ignored "-Wexit-time-destructors"
15008# pragma clang diagnostic ignored "-Wglobal-constructors"
15012#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15013#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15023 const std::string unprintableString =
"{?}";
15026 const int hexThreshold = 255;
15028 struct Endianness {
15029 enum Arch { Big, Little };
15031 static Arch which() {
15035 auto value = *
reinterpret_cast<char*
>(&one);
15036 return value ? Little : Big;
15041 std::string rawMemoryToString(
const void *
object, std::size_t size ) {
15043 int i = 0, end =
static_cast<int>( size ), inc = 1;
15044 if( Endianness::which() == Endianness::Little ) {
15049 unsigned char const *bytes =
static_cast<unsigned char const *
>(
object);
15050 ReusableStringStream rss;
15051 rss <<
"0x" << std::setfill(
'0') << std::hex;
15052 for( ; i != end; i += inc )
15053 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15058template<
typename T>
15059std::string fpToString( T value,
int precision ) {
15060 if (Catch::isnan(value)) {
15064 ReusableStringStream rss;
15065 rss << std::setprecision( precision )
15068 std::string d = rss.str();
15069 std::size_t i = d.find_last_not_of(
'0' );
15070 if( i != std::string::npos && i != d.size()-1 ) {
15073 d = d.substr( 0, i+1 );
15084std::string StringMaker<std::string>::convert(
const std::string& str) {
15085 if (!getCurrentContext().getConfig()->showInvisibles()) {
15086 return '"' + str + '"';
15089 std::string s(
"\"");
15090 for (
char c : str) {
15107#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15108std::string StringMaker<std::string_view>::convert(std::string_view str) {
15109 return ::Catch::Detail::stringify(std::string{ str });
15113std::string StringMaker<char const*>::convert(
char const* str) {
15115 return ::Catch::Detail::stringify(std::string{ str });
15117 return{
"{null string}" };
15120std::string StringMaker<char*>::convert(
char* str) {
15122 return ::Catch::Detail::stringify(std::string{ str });
15124 return{
"{null string}" };
15128#ifdef CATCH_CONFIG_WCHAR
15129std::string StringMaker<std::wstring>::convert(
const std::wstring& wstr) {
15131 s.reserve(wstr.size());
15132 for (
auto c : wstr) {
15133 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15135 return ::Catch::Detail::stringify(s);
15138# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15139std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15140 return StringMaker<std::wstring>::convert(std::wstring(str));
15144std::string StringMaker<wchar_t const*>::convert(
wchar_t const * str) {
15146 return ::Catch::Detail::stringify(std::wstring{ str });
15148 return{
"{null string}" };
15151std::string StringMaker<wchar_t *>::convert(
wchar_t * str) {
15153 return ::Catch::Detail::stringify(std::wstring{ str });
15155 return{
"{null string}" };
15160#if defined(CATCH_CONFIG_CPP17_BYTE)
15162std::string StringMaker<std::byte>::convert(std::byte value) {
15163 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15167std::string StringMaker<int>::convert(
int value) {
15168 return ::Catch::Detail::stringify(
static_cast<long long>(value));
15170std::string StringMaker<long>::convert(
long value) {
15171 return ::Catch::Detail::stringify(
static_cast<long long>(value));
15173std::string StringMaker<long long>::convert(
long long value) {
15174 ReusableStringStream rss;
15176 if (value > Detail::hexThreshold) {
15177 rss <<
" (0x" << std::hex << value <<
')';
15182std::string StringMaker<unsigned int>::convert(
unsigned int value) {
15183 return ::Catch::Detail::stringify(
static_cast<unsigned long long>(value));
15185std::string StringMaker<unsigned long>::convert(
unsigned long value) {
15186 return ::Catch::Detail::stringify(
static_cast<unsigned long long>(value));
15188std::string StringMaker<unsigned long long>::convert(
unsigned long long value) {
15189 ReusableStringStream rss;
15191 if (value > Detail::hexThreshold) {
15192 rss <<
" (0x" << std::hex << value <<
')';
15197std::string StringMaker<bool>::convert(
bool b) {
15198 return b ?
"true" :
"false";
15201std::string StringMaker<signed char>::convert(
signed char value) {
15202 if (value ==
'\r') {
15204 }
else if (value ==
'\f') {
15206 }
else if (value ==
'\n') {
15208 }
else if (value ==
'\t') {
15210 }
else if (
'\0' <= value && value <
' ') {
15211 return ::Catch::Detail::stringify(
static_cast<unsigned int>(value));
15213 char chstr[] =
"' '";
15218std::string StringMaker<char>::convert(
char c) {
15219 return ::Catch::Detail::stringify(
static_cast<signed char>(c));
15221std::string StringMaker<unsigned char>::convert(
unsigned char c) {
15222 return ::Catch::Detail::stringify(
static_cast<char>(c));
15225std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15229int StringMaker<float>::precision = 5;
15231std::string StringMaker<float>::convert(
float value) {
15232 return fpToString(value, precision) + 'f';
15235int StringMaker<double>::precision = 10;
15237std::string StringMaker<double>::convert(
double value) {
15238 return fpToString(value, precision);
15241std::string ratio_string<std::atto>::symbol() {
return "a"; }
15242std::string ratio_string<std::femto>::symbol() {
return "f"; }
15243std::string ratio_string<std::pico>::symbol() {
return "p"; }
15244std::string ratio_string<std::nano>::symbol() {
return "n"; }
15245std::string ratio_string<std::micro>::symbol() {
return "u"; }
15246std::string ratio_string<std::milli>::symbol() {
return "m"; }
15250#if defined(__clang__)
15251# pragma clang diagnostic pop
15259 Counts Counts::operator - ( Counts
const& other )
const {
15261 diff.passed = passed - other.passed;
15262 diff.failed = failed - other.failed;
15263 diff.failedButOk = failedButOk - other.failedButOk;
15267 Counts& Counts::operator += ( Counts
const& other ) {
15268 passed += other.passed;
15269 failed += other.failed;
15270 failedButOk += other.failedButOk;
15274 std::size_t Counts::total()
const {
15275 return passed + failed + failedButOk;
15277 bool Counts::allPassed()
const {
15278 return failed == 0 && failedButOk == 0;
15280 bool Counts::allOk()
const {
15281 return failed == 0;
15284 Totals Totals::operator - ( Totals
const& other )
const {
15286 diff.assertions = assertions - other.assertions;
15287 diff.testCases = testCases - other.testCases;
15291 Totals& Totals::operator += ( Totals
const& other ) {
15292 assertions += other.assertions;
15293 testCases += other.testCases;
15297 Totals Totals::delta( Totals
const& prevTotals )
const {
15298 Totals diff = *
this - prevTotals;
15299 if( diff.assertions.failed > 0 )
15300 ++diff.testCases.
failed;
15301 else if( diff.assertions.failedButOk > 0 )
15302 ++diff.testCases.failedButOk;
15304 ++diff.testCases.passed;
15321#ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15322#define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15324#if defined(_MSC_VER)
15325# if _MSC_VER >= 1900
15326# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15330#include <exception>
15332#if defined(__cpp_lib_uncaught_exceptions) \
15333 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15335# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15338#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15339 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15340 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15342# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15347#include <exception>
15350 bool uncaught_exceptions() {
15351#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15353#elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15354 return std::uncaught_exceptions() > 0;
15356 return std::uncaught_exception();
15368 (
unsigned int _majorVersion,
15369 unsigned int _minorVersion,
15370 unsigned int _patchNumber,
15371 char const *
const _branchName,
15372 unsigned int _buildNumber )
15373 : majorVersion( _majorVersion ),
15374 minorVersion( _minorVersion ),
15375 patchNumber( _patchNumber ),
15376 branchName( _branchName ),
15377 buildNumber( _buildNumber )
15380 std::ostream& operator << ( std::ostream& os, Version
const& version ) {
15381 os << version.majorVersion <<
'.'
15382 << version.minorVersion <<
'.'
15383 << version.patchNumber;
15385 if (version.branchName[0]) {
15386 os <<
'-' << version.branchName
15387 <<
'.' << version.buildNumber;
15392 Version
const& libraryVersion() {
15393 static Version version( 2, 13, 10,
"", 0 );
15403 WildcardPattern::WildcardPattern( std::string
const& pattern,
15404 CaseSensitive::Choice caseSensitivity )
15405 : m_caseSensitivity( caseSensitivity ),
15406 m_pattern( normaliseString( pattern ) )
15408 if( startsWith( m_pattern,
'*' ) ) {
15409 m_pattern = m_pattern.substr( 1 );
15410 m_wildcard = WildcardAtStart;
15412 if( endsWith( m_pattern,
'*' ) ) {
15413 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15414 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
15418 bool WildcardPattern::matches( std::string
const& str )
const {
15419 switch( m_wildcard ) {
15421 return m_pattern == normaliseString( str );
15422 case WildcardAtStart:
15423 return endsWith( normaliseString( str ), m_pattern );
15424 case WildcardAtEnd:
15425 return startsWith( normaliseString( str ), m_pattern );
15426 case WildcardAtBothEnds:
15427 return contains( normaliseString( str ), m_pattern );
15429 CATCH_INTERNAL_ERROR(
"Unknown enum" );
15433 std::string WildcardPattern::normaliseString( std::string
const& str )
const {
15434 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15441#include <type_traits>
15447 size_t trailingBytes(
unsigned char c) {
15448 if ((c & 0xE0) == 0xC0) {
15451 if ((c & 0xF0) == 0xE0) {
15454 if ((c & 0xF8) == 0xF0) {
15457 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15460 uint32_t headerValue(
unsigned char c) {
15461 if ((c & 0xE0) == 0xC0) {
15464 if ((c & 0xF0) == 0xE0) {
15467 if ((c & 0xF8) == 0xF0) {
15470 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15473 void hexEscapeChar(std::ostream& os,
unsigned char c) {
15474 std::ios_base::fmtflags f(os.flags());
15476 << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15477 <<
static_cast<int>(c);
15481 bool shouldNewline(XmlFormatting fmt) {
15482 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15485 bool shouldIndent(XmlFormatting fmt) {
15486 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15491 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15492 return static_cast<XmlFormatting
>(
15493 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15494 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15498 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15499 return static_cast<XmlFormatting
>(
15500 static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15501 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs)
15505 XmlEncode::XmlEncode( std::string
const& str, ForWhat forWhat )
15507 m_forWhat( forWhat )
15510 void XmlEncode::encodeTo( std::ostream& os )
const {
15514 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15515 unsigned char c = m_str[idx];
15517 case '<': os <<
"<";
break;
15518 case '&': os <<
"&";
break;
15522 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15529 if (m_forWhat == ForAttributes)
15540 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15541 hexEscapeChar(os, c);
15559 hexEscapeChar(os, c);
15563 auto encBytes = trailingBytes(c);
15565 if (idx + encBytes - 1 >= m_str.size()) {
15566 hexEscapeChar(os, c);
15573 uint32_t value = headerValue(c);
15574 for (std::size_t n = 1; n < encBytes; ++n) {
15575 unsigned char nc = m_str[idx + n];
15576 valid &= ((nc & 0xC0) == 0x80);
15577 value = (value << 6) | (nc & 0x3F);
15585 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15586 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15588 (value >= 0x110000)
15590 hexEscapeChar(os, c);
15595 for (std::size_t n = 0; n < encBytes; ++n) {
15596 os << m_str[idx + n];
15598 idx += encBytes - 1;
15604 std::ostream& operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
15605 xmlEncode.encodeTo( os );
15609 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15610 : m_writer( writer ),
15614 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15615 : m_writer( other.m_writer ),
15618 other.m_writer =
nullptr;
15619 other.m_fmt = XmlFormatting::None;
15621 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other )
noexcept {
15623 m_writer->endElement();
15625 m_writer = other.m_writer;
15626 other.m_writer =
nullptr;
15627 m_fmt = other.m_fmt;
15628 other.m_fmt = XmlFormatting::None;
15632 XmlWriter::ScopedElement::~ScopedElement() {
15634 m_writer->endElement(m_fmt);
15638 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string
const& text, XmlFormatting fmt ) {
15639 m_writer->writeText( text, fmt );
15643 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15645 writeDeclaration();
15648 XmlWriter::~XmlWriter() {
15649 while (!m_tags.empty()) {
15652 newlineIfNecessary();
15655 XmlWriter& XmlWriter::startElement( std::string
const& name, XmlFormatting fmt ) {
15657 newlineIfNecessary();
15658 if (shouldIndent(fmt)) {
15662 m_os <<
'<' << name;
15663 m_tags.push_back( name );
15664 m_tagIsOpen =
true;
15665 applyFormatting(fmt);
15669 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string
const& name, XmlFormatting fmt ) {
15670 ScopedElement scoped(
this, fmt );
15671 startElement( name, fmt );
15675 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15676 m_indent = m_indent.substr(0, m_indent.size() - 2);
15678 if( m_tagIsOpen ) {
15680 m_tagIsOpen =
false;
15682 newlineIfNecessary();
15683 if (shouldIndent(fmt)) {
15686 m_os <<
"</" << m_tags.back() <<
">";
15688 m_os << std::flush;
15689 applyFormatting(fmt);
15694 XmlWriter& XmlWriter::writeAttribute( std::string
const& name, std::string
const& attribute ) {
15695 if( !name.empty() && !attribute.empty() )
15696 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
15700 XmlWriter& XmlWriter::writeAttribute( std::string
const& name,
bool attribute ) {
15701 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
15705 XmlWriter& XmlWriter::writeText( std::string
const& text, XmlFormatting fmt) {
15706 if( !text.empty() ){
15707 bool tagWasOpen = m_tagIsOpen;
15709 if (tagWasOpen && shouldIndent(fmt)) {
15712 m_os << XmlEncode( text );
15713 applyFormatting(fmt);
15718 XmlWriter& XmlWriter::writeComment( std::string
const& text, XmlFormatting fmt) {
15720 if (shouldIndent(fmt)) {
15723 m_os <<
"<!--" << text <<
"-->";
15724 applyFormatting(fmt);
15728 void XmlWriter::writeStylesheetRef( std::string
const& url ) {
15729 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15732 XmlWriter& XmlWriter::writeBlankLine() {
15738 void XmlWriter::ensureTagClosed() {
15739 if( m_tagIsOpen ) {
15740 m_os <<
'>' << std::flush;
15741 newlineIfNecessary();
15742 m_tagIsOpen =
false;
15746 void XmlWriter::applyFormatting(XmlFormatting fmt) {
15747 m_needsNewline = shouldNewline(fmt);
15750 void XmlWriter::writeDeclaration() {
15751 m_os <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15754 void XmlWriter::newlineIfNecessary() {
15755 if( m_needsNewline ) {
15757 m_needsNewline =
false;
15771 void prepareExpandedExpression(AssertionResult& result) {
15772 result.getExpandedExpression();
15777 std::string getFormattedDuration(
double duration ) {
15782 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15783 char buffer[maxDoubleSize];
15788 sprintf_s(buffer,
"%.3f", duration);
15790 std::sprintf(buffer,
"%.3f", duration);
15792 return std::string(buffer);
15795 bool shouldShowDuration( IConfig
const& config,
double duration ) {
15796 if ( config.showDurations() == ShowDurations::Always ) {
15799 if ( config.showDurations() == ShowDurations::Never ) {
15802 const double min = config.minDuration();
15803 return min >= 0 && duration >= min;
15806 std::string serializeFilters( std::vector<std::string>
const& container ) {
15807 ReusableStringStream oss;
15809 for (
auto&& filter : container)
15821 TestEventListenerBase::TestEventListenerBase(ReporterConfig
const & _config)
15822 :StreamingReporterBase(_config) {}
15824 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15825 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15828 void TestEventListenerBase::assertionStarting(AssertionInfo
const &) {}
15830 bool TestEventListenerBase::assertionEnded(AssertionStats
const &) {
15840#ifdef CATCH_PLATFORM_MAC
15841 const char* failedString() {
return "FAILED"; }
15842 const char* passedString() {
return "PASSED"; }
15844 const char* failedString() {
return "failed"; }
15845 const char* passedString() {
return "passed"; }
15849 Catch::Colour::Code dimColour() {
return Catch::Colour::FileName; }
15851 std::string bothOrAll( std::size_t count ) {
15852 return count == 1 ? std::string() :
15853 count == 2 ?
"both " :
"all " ;
15866void printTotals(std::ostream& out,
const Totals& totals) {
15867 if (totals.testCases.total() == 0) {
15868 out <<
"No tests ran.";
15869 }
else if (totals.testCases.failed == totals.testCases.total()) {
15870 Colour colour(Colour::ResultError);
15871 const std::string qualify_assertions_failed =
15872 totals.assertions.failed == totals.assertions.total() ?
15873 bothOrAll(totals.assertions.failed) : std::
string();
15875 "Failed " << bothOrAll(totals.testCases.failed)
15876 << pluralise(totals.testCases.failed,
"test case") <<
", "
15877 "failed " << qualify_assertions_failed <<
15878 pluralise(totals.assertions.failed,
"assertion") <<
'.';
15879 }
else if (totals.assertions.total() == 0) {
15881 "Passed " << bothOrAll(totals.testCases.total())
15882 << pluralise(totals.testCases.total(),
"test case")
15883 <<
" (no assertions).";
15884 }
else if (totals.assertions.failed) {
15885 Colour colour(Colour::ResultError);
15887 "Failed " << pluralise(totals.testCases.failed,
"test case") <<
", "
15888 "failed " << pluralise(totals.assertions.failed,
"assertion") <<
'.';
15890 Colour colour(Colour::ResultSuccess);
15892 "Passed " << bothOrAll(totals.testCases.passed)
15893 << pluralise(totals.testCases.passed,
"test case") <<
15894 " with " << pluralise(totals.assertions.passed,
"assertion") <<
'.';
15899class AssertionPrinter {
15901 AssertionPrinter& operator= (AssertionPrinter
const&) =
delete;
15902 AssertionPrinter(AssertionPrinter
const&) =
delete;
15903 AssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
15905 , result(_stats.assertionResult)
15906 , messages(_stats.infoMessages)
15907 , itMessage(_stats.infoMessages.begin())
15908 , printInfoMessages(_printInfoMessages) {}
15913 itMessage = messages.begin();
15915 switch (result.getResultType()) {
15916 case ResultWas::Ok:
15917 printResultType(Colour::ResultSuccess, passedString());
15918 printOriginalExpression();
15919 printReconstructedExpression();
15920 if (!result.hasExpression())
15921 printRemainingMessages(Colour::None);
15923 printRemainingMessages();
15925 case ResultWas::ExpressionFailed:
15927 printResultType(Colour::ResultSuccess, failedString() + std::string(
" - but was ok"));
15929 printResultType(Colour::Error, failedString());
15930 printOriginalExpression();
15931 printReconstructedExpression();
15932 printRemainingMessages();
15934 case ResultWas::ThrewException:
15935 printResultType(Colour::Error, failedString());
15936 printIssue(
"unexpected exception with message:");
15938 printExpressionWas();
15939 printRemainingMessages();
15941 case ResultWas::FatalErrorCondition:
15942 printResultType(Colour::Error, failedString());
15943 printIssue(
"fatal error condition with message:");
15945 printExpressionWas();
15946 printRemainingMessages();
15948 case ResultWas::DidntThrowException:
15949 printResultType(Colour::Error, failedString());
15950 printIssue(
"expected exception, got none");
15951 printExpressionWas();
15952 printRemainingMessages();
15954 case ResultWas::Info:
15955 printResultType(Colour::None,
"info");
15957 printRemainingMessages();
15959 case ResultWas::Warning:
15960 printResultType(Colour::None,
"warning");
15962 printRemainingMessages();
15964 case ResultWas::ExplicitFailure:
15965 printResultType(Colour::Error, failedString());
15966 printIssue(
"explicitly");
15967 printRemainingMessages(Colour::None);
15970 case ResultWas::Unknown:
15971 case ResultWas::FailureBit:
15972 case ResultWas::Exception:
15973 printResultType(Colour::Error,
"** internal error **");
15979 void printSourceInfo()
const {
15980 Colour colourGuard(Colour::FileName);
15981 stream << result.getSourceInfo() <<
':';
15984 void printResultType(Colour::Code colour, std::string
const& passOrFail)
const {
15985 if (!passOrFail.empty()) {
15987 Colour colourGuard(colour);
15988 stream <<
' ' << passOrFail;
15994 void printIssue(std::string
const& issue)
const {
15995 stream <<
' ' << issue;
15998 void printExpressionWas() {
15999 if (result.hasExpression()) {
16002 Colour colour(dimColour());
16003 stream <<
" expression was:";
16005 printOriginalExpression();
16009 void printOriginalExpression()
const {
16010 if (result.hasExpression()) {
16011 stream <<
' ' << result.getExpression();
16015 void printReconstructedExpression()
const {
16016 if (result.hasExpandedExpression()) {
16018 Colour colour(dimColour());
16019 stream <<
" for: ";
16021 stream << result.getExpandedExpression();
16025 void printMessage() {
16026 if (itMessage != messages.end()) {
16027 stream <<
" '" << itMessage->message <<
'\'';
16032 void printRemainingMessages(Colour::Code colour = dimColour()) {
16033 if (itMessage == messages.end())
16036 const auto itEnd = messages.cend();
16037 const auto N =
static_cast<std::size_t
>(std::distance(itMessage, itEnd));
16040 Colour colourGuard(colour);
16041 stream <<
" with " << pluralise(N,
"message") <<
':';
16044 while (itMessage != itEnd) {
16046 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16048 if (itMessage != itEnd) {
16049 Colour colourGuard(dimColour());
16059 std::ostream& stream;
16060 AssertionResult
const& result;
16061 std::vector<MessageInfo> messages;
16062 std::vector<MessageInfo>::const_iterator itMessage;
16063 bool printInfoMessages;
16068 std::string CompactReporter::getDescription() {
16069 return "Reports test results on a single line, suitable for IDEs";
16072 void CompactReporter::noMatchingTestCases( std::string
const& spec ) {
16073 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16076 void CompactReporter::assertionStarting( AssertionInfo
const& ) {}
16078 bool CompactReporter::assertionEnded( AssertionStats
const& _assertionStats ) {
16079 AssertionResult
const& result = _assertionStats.assertionResult;
16081 bool printInfoMessages =
true;
16084 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16085 if( result.getResultType() != ResultWas::Warning )
16087 printInfoMessages =
false;
16090 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16093 stream << std::endl;
16097 void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
16098 double dur = _sectionStats.durationInSeconds;
16099 if ( shouldShowDuration( *m_config, dur ) ) {
16100 stream << getFormattedDuration( dur ) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16104 void CompactReporter::testRunEnded( TestRunStats
const& _testRunStats ) {
16105 printTotals( stream, _testRunStats.totals );
16106 stream <<
'\n' << std::endl;
16107 StreamingReporterBase::testRunEnded( _testRunStats );
16110 CompactReporter::~CompactReporter() {}
16112 CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
16121#if defined(_MSC_VER)
16122#pragma warning(push)
16123#pragma warning(disable:4061)
16127#if defined(__clang__)
16128# pragma clang diagnostic push
16130# pragma clang diagnostic ignored "-Wunused-function"
16138class ConsoleAssertionPrinter {
16140 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter
const&) =
delete;
16141 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
16142 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
16145 result(_stats.assertionResult),
16146 colour(Colour::None),
16147 message(result.getMessage()),
16148 messages(_stats.infoMessages),
16149 printInfoMessages(_printInfoMessages) {
16150 switch (result.getResultType()) {
16151 case ResultWas::Ok:
16152 colour = Colour::Success;
16153 passOrFail =
"PASSED";
16155 if (_stats.infoMessages.size() == 1)
16156 messageLabel =
"with message";
16157 if (_stats.infoMessages.size() > 1)
16158 messageLabel =
"with messages";
16160 case ResultWas::ExpressionFailed:
16161 if (result.isOk()) {
16162 colour = Colour::Success;
16163 passOrFail =
"FAILED - but was ok";
16165 colour = Colour::Error;
16166 passOrFail =
"FAILED";
16168 if (_stats.infoMessages.size() == 1)
16169 messageLabel =
"with message";
16170 if (_stats.infoMessages.size() > 1)
16171 messageLabel =
"with messages";
16173 case ResultWas::ThrewException:
16174 colour = Colour::Error;
16175 passOrFail =
"FAILED";
16176 messageLabel =
"due to unexpected exception with ";
16177 if (_stats.infoMessages.size() == 1)
16178 messageLabel += "message";
16179 if (_stats.infoMessages.size() > 1)
16180 messageLabel += "messages";
16182 case ResultWas::FatalErrorCondition:
16183 colour = Colour::Error;
16184 passOrFail =
"FAILED";
16185 messageLabel =
"due to a fatal error condition";
16187 case ResultWas::DidntThrowException:
16188 colour = Colour::Error;
16189 passOrFail =
"FAILED";
16190 messageLabel =
"because no exception was thrown where one was expected";
16192 case ResultWas::Info:
16193 messageLabel =
"info";
16195 case ResultWas::Warning:
16196 messageLabel =
"warning";
16198 case ResultWas::ExplicitFailure:
16199 passOrFail =
"FAILED";
16200 colour = Colour::Error;
16201 if (_stats.infoMessages.size() == 1)
16202 messageLabel =
"explicitly with message";
16203 if (_stats.infoMessages.size() > 1)
16204 messageLabel =
"explicitly with messages";
16207 case ResultWas::Unknown:
16208 case ResultWas::FailureBit:
16209 case ResultWas::Exception:
16210 passOrFail =
"** internal error **";
16211 colour = Colour::Error;
16216 void print()
const {
16218 if (stats.totals.assertions.total() > 0) {
16220 printOriginalExpression();
16221 printReconstructedExpression();
16229 void printResultType()
const {
16230 if (!passOrFail.empty()) {
16231 Colour colourGuard(colour);
16232 stream << passOrFail <<
":\n";
16235 void printOriginalExpression()
const {
16236 if (result.hasExpression()) {
16237 Colour colourGuard(Colour::OriginalExpression);
16239 stream << result.getExpressionInMacro();
16243 void printReconstructedExpression()
const {
16244 if (result.hasExpandedExpression()) {
16245 stream <<
"with expansion:\n";
16246 Colour colourGuard(Colour::ReconstructedExpression);
16247 stream << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16250 void printMessage()
const {
16251 if (!messageLabel.empty())
16252 stream << messageLabel <<
':' <<
'\n';
16253 for (
auto const& msg : messages) {
16255 if (printInfoMessages || msg.type != ResultWas::Info)
16256 stream << Column(msg.message).indent(2) <<
'\n';
16259 void printSourceInfo()
const {
16260 Colour colourGuard(Colour::FileName);
16261 stream << result.getSourceInfo() <<
": ";
16264 std::ostream& stream;
16265 AssertionStats
const& stats;
16266 AssertionResult
const& result;
16267 Colour::Code colour;
16268 std::string passOrFail;
16269 std::string messageLabel;
16270 std::string message;
16271 std::vector<MessageInfo> messages;
16272 bool printInfoMessages;
16275std::size_t makeRatio(std::size_t number, std::size_t total) {
16276 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16277 return (ratio == 0 && number > 0) ? 1 : ratio;
16280std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16281 if (i > j && i > k)
16290 enum Justification { Left, Right };
16293 Justification justification;
16295struct ColumnBreak {};
16307 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16308 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16309 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16310 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16312 double m_inNanoseconds;
16316 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16317 : m_inNanoseconds(inNanoseconds),
16319 if (m_units == Unit::Auto) {
16320 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16321 m_units = Unit::Nanoseconds;
16322 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16323 m_units = Unit::Microseconds;
16324 else if (m_inNanoseconds < s_nanosecondsInASecond)
16325 m_units = Unit::Milliseconds;
16326 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16327 m_units = Unit::Seconds;
16329 m_units = Unit::Minutes;
16334 auto value() const ->
double {
16336 case Unit::Microseconds:
16337 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16338 case Unit::Milliseconds:
16339 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16340 case Unit::Seconds:
16341 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16342 case Unit::Minutes:
16343 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16345 return m_inNanoseconds;
16348 auto unitsAsString() const -> std::
string {
16350 case Unit::Nanoseconds:
16352 case Unit::Microseconds:
16354 case Unit::Milliseconds:
16356 case Unit::Seconds:
16358 case Unit::Minutes:
16361 return "** internal error **";
16365 friend auto operator << (std::ostream& os, Duration
const& duration) -> std::ostream& {
16366 return os << duration.value() <<
' ' << duration.unitsAsString();
16371class TablePrinter {
16372 std::ostream& m_os;
16373 std::vector<ColumnInfo> m_columnInfos;
16374 std::ostringstream m_oss;
16375 int m_currentColumn = -1;
16376 bool m_isOpen =
false;
16379 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16381 m_columnInfos( std::move( columnInfos ) ) {}
16383 auto columnInfos() const -> std::vector<ColumnInfo> const& {
16384 return m_columnInfos;
16390 *
this << RowBreak();
16392 Columns headerCols;
16394 for (
auto const& info : m_columnInfos) {
16395 headerCols += Column(
info.name).width(static_cast<std::size_t>(
info.width - 2));
16396 headerCols += spacer;
16398 m_os << headerCols <<
'\n';
16400 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16405 *
this << RowBreak();
16411 template<
typename T>
16412 friend TablePrinter&
operator << (TablePrinter& tp, T
const& value) {
16417 friend TablePrinter&
operator << (TablePrinter& tp, ColumnBreak) {
16418 auto colStr = tp.m_oss.str();
16419 const auto strSize = colStr.size();
16422 if (tp.m_currentColumn ==
static_cast<int>(tp.m_columnInfos.size() - 1)) {
16423 tp.m_currentColumn = -1;
16426 tp.m_currentColumn++;
16428 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16429 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16430 ? std::string(colInfo.width - (strSize + 1), ' ')
16432 if (colInfo.justification == ColumnInfo::Left)
16433 tp.m_os << colStr << padding <<
' ';
16435 tp.m_os << padding << colStr <<
' ';
16439 friend TablePrinter&
operator << (TablePrinter& tp, RowBreak) {
16440 if (tp.m_currentColumn > 0) {
16442 tp.m_currentColumn = -1;
16448ConsoleReporter::ConsoleReporter(ReporterConfig
const& config)
16449 : StreamingReporterBase(config),
16450 m_tablePrinter(new TablePrinter(config.stream(),
16451 [&config]() -> std::vector<ColumnInfo> {
16452 if (config.fullConfig()->benchmarkNoAnalysis())
16455 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16456 {
" samples", 14, ColumnInfo::Right },
16457 {
" iterations", 14, ColumnInfo::Right },
16458 {
" mean", 14, ColumnInfo::Right }
16464 {
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16465 {
"samples mean std dev", 14, ColumnInfo::Right },
16466 {
"iterations low mean low std dev", 14, ColumnInfo::Right },
16467 {
"estimated high mean high std dev", 14, ColumnInfo::Right }
16471ConsoleReporter::~ConsoleReporter() =
default;
16473std::string ConsoleReporter::getDescription() {
16474 return "Reports test results as plain lines of text";
16477void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16478 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16481void ConsoleReporter::reportInvalidArguments(std::string
const&arg){
16482 stream <<
"Invalid Filter: " << arg << std::endl;
16485void ConsoleReporter::assertionStarting(AssertionInfo
const&) {}
16487bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16488 AssertionResult
const& result = _assertionStats.assertionResult;
16490 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16493 if (!includeResults && result.getResultType() != ResultWas::Warning)
16498 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16500 stream << std::endl;
16504void ConsoleReporter::sectionStarting(SectionInfo
const& _sectionInfo) {
16505 m_tablePrinter->close();
16506 m_headerPrinted =
false;
16507 StreamingReporterBase::sectionStarting(_sectionInfo);
16509void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16510 m_tablePrinter->close();
16511 if (_sectionStats.missingAssertions) {
16513 Colour colour(Colour::ResultError);
16514 if (m_sectionStack.size() > 1)
16515 stream <<
"\nNo assertions in section";
16517 stream <<
"\nNo assertions in test case";
16518 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16520 double dur = _sectionStats.durationInSeconds;
16521 if (shouldShowDuration(*m_config, dur)) {
16522 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
16524 if (m_headerPrinted) {
16525 m_headerPrinted =
false;
16527 StreamingReporterBase::sectionEnded(_sectionStats);
16530#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16531void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16532 lazyPrintWithoutClosingBenchmarkTable();
16534 auto nameCol = Column(name).width(
static_cast<std::size_t
>(m_tablePrinter->columnInfos()[0].width - 2));
16536 bool firstLine =
true;
16537 for (
auto line : nameCol) {
16539 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16543 (*m_tablePrinter) << line << ColumnBreak();
16547void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16548 (*m_tablePrinter) <<
info.samples << ColumnBreak()
16549 <<
info.iterations << ColumnBreak();
16550 if (!m_config->benchmarkNoAnalysis())
16551 (*m_tablePrinter) << Duration(
info.estimatedDuration) << ColumnBreak();
16553void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16554 if (m_config->benchmarkNoAnalysis())
16556 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16560 (*m_tablePrinter) << ColumnBreak()
16561 << Duration(stats.mean.point.count()) << ColumnBreak()
16562 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16563 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16564 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16565 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16566 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16570void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16571 Colour colour(Colour::Red);
16573 <<
"Benchmark failed (" << error <<
')'
16574 << ColumnBreak() << RowBreak();
16578void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16579 m_tablePrinter->close();
16580 StreamingReporterBase::testCaseEnded(_testCaseStats);
16581 m_headerPrinted =
false;
16583void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16584 if (currentGroupInfo.used) {
16585 printSummaryDivider();
16586 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16587 printTotals(_testGroupStats.totals);
16588 stream <<
'\n' << std::endl;
16590 StreamingReporterBase::testGroupEnded(_testGroupStats);
16592void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16593 printTotalsDivider(_testRunStats.totals);
16594 printTotals(_testRunStats.totals);
16595 stream << std::endl;
16596 StreamingReporterBase::testRunEnded(_testRunStats);
16598void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16599 StreamingReporterBase::testRunStarting(_testInfo);
16600 printTestFilters();
16603void ConsoleReporter::lazyPrint() {
16605 m_tablePrinter->close();
16606 lazyPrintWithoutClosingBenchmarkTable();
16609void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16611 if (!currentTestRunInfo.used)
16612 lazyPrintRunInfo();
16613 if (!currentGroupInfo.used)
16614 lazyPrintGroupInfo();
16616 if (!m_headerPrinted) {
16617 printTestCaseAndSectionHeader();
16618 m_headerPrinted =
true;
16621void ConsoleReporter::lazyPrintRunInfo() {
16622 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16623 Colour colour(Colour::SecondaryText);
16624 stream << currentTestRunInfo->name
16625 <<
" is a Catch v" << libraryVersion() <<
" host application.\n"
16626 <<
"Run with -? for options\n\n";
16628 if (m_config->rngSeed() != 0)
16629 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16631 currentTestRunInfo.used =
true;
16633void ConsoleReporter::lazyPrintGroupInfo() {
16634 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16635 printClosedHeader(
"Group: " + currentGroupInfo->name);
16636 currentGroupInfo.used =
true;
16639void ConsoleReporter::printTestCaseAndSectionHeader() {
16640 assert(!m_sectionStack.empty());
16641 printOpenHeader(currentTestCaseInfo->name);
16643 if (m_sectionStack.size() > 1) {
16644 Colour colourGuard(Colour::Headers);
16647 it = m_sectionStack.begin() + 1,
16648 itEnd = m_sectionStack.end();
16649 for (; it != itEnd; ++it)
16650 printHeaderString(it->name, 2);
16653 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16655 stream << getLineOfChars<
'-'>() <<
'\n';
16656 Colour colourGuard(Colour::FileName);
16657 stream << lineInfo <<
'\n';
16658 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16661void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16662 printOpenHeader(_name);
16663 stream << getLineOfChars<
'.'>() <<
'\n';
16665void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16666 stream << getLineOfChars<
'-'>() <<
'\n';
16668 Colour colourGuard(Colour::Headers);
16669 printHeaderString(_name);
16675void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16676 std::size_t i = _string.find(
": ");
16677 if (i != std::string::npos)
16681 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16684struct SummaryColumn {
16686 SummaryColumn( std::string _label, Colour::Code _colour )
16687 : label( std::move( _label ) ),
16688 colour( _colour ) {}
16689 SummaryColumn addRow( std::size_t count ) {
16690 ReusableStringStream rss;
16692 std::string row = rss.str();
16693 for (
auto& oldRow : rows) {
16694 while (oldRow.size() < row.size())
16695 oldRow =
' ' + oldRow;
16696 while (oldRow.size() > row.size())
16699 rows.push_back(row);
16704 Colour::Code colour;
16705 std::vector<std::string> rows;
16709void ConsoleReporter::printTotals( Totals
const& totals ) {
16710 if (totals.testCases.total() == 0) {
16711 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16712 }
else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16713 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16715 << pluralise(totals.assertions.passed,
"assertion") <<
" in "
16716 << pluralise(totals.testCases.passed,
"test case") <<
')'
16720 std::vector<SummaryColumn> columns;
16721 columns.push_back(SummaryColumn(
"", Colour::None)
16722 .addRow(totals.testCases.total())
16723 .addRow(totals.assertions.total()));
16724 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16725 .addRow(totals.testCases.passed)
16726 .addRow(totals.assertions.passed));
16727 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16728 .addRow(totals.testCases.failed)
16729 .addRow(totals.assertions.failed));
16730 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16731 .addRow(totals.testCases.failedButOk)
16732 .addRow(totals.assertions.failedButOk));
16734 printSummaryRow(
"test cases", columns, 0);
16735 printSummaryRow(
"assertions", columns, 1);
16738void ConsoleReporter::printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row) {
16739 for (
auto col : cols) {
16740 std::string value = col.rows[row];
16741 if (col.label.empty()) {
16742 stream << label <<
": ";
16746 stream << Colour(Colour::Warning) <<
"- none -";
16747 }
else if (value !=
"0") {
16748 stream << Colour(Colour::LightGrey) <<
" | ";
16749 stream << Colour(col.colour)
16750 << value <<
' ' << col.label;
16756void ConsoleReporter::printTotalsDivider(Totals
const& totals) {
16757 if (totals.testCases.total() > 0) {
16758 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16759 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16760 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16761 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16762 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16763 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16764 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16766 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16767 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16768 if (totals.testCases.allPassed())
16769 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16771 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16773 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16777void ConsoleReporter::printSummaryDivider() {
16778 stream << getLineOfChars<
'-'>() <<
'\n';
16781void ConsoleReporter::printTestFilters() {
16782 if (m_config->testSpec().hasFilters()) {
16783 Colour guard(Colour::BrightYellow);
16784 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16788CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16792#if defined(_MSC_VER)
16793#pragma warning(pop)
16796#if defined(__clang__)
16797# pragma clang diagnostic pop
16805#include <algorithm>
16811 std::string getCurrentTimestamp() {
16815 std::time(&rawtime);
16816 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16819 std::tm timeInfo = {};
16820 gmtime_s(&timeInfo, &rawtime);
16823 timeInfo = std::gmtime(&rawtime);
16826 char timeStamp[timeStampSize];
16827 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16830 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16832 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16834 return std::string(timeStamp, timeStampSize-1);
16837 std::string fileNameTag(
const std::vector<std::string> &tags) {
16838 auto it = std::find_if(begin(tags),
16840 [] (std::string
const& tag) {
return tag.front() ==
'#'; });
16841 if (it != tags.end())
16842 return it->substr(1);
16843 return std::string();
16850 std::string formatDuration(
double seconds ) {
16851 ReusableStringStream rss;
16852 rss << std::fixed << std::setprecision( 3 ) << seconds;
16858 JunitReporter::JunitReporter( ReporterConfig
const& _config )
16859 : CumulativeReporterBase( _config ),
16860 xml( _config.stream() )
16862 m_reporterPrefs.shouldRedirectStdOut =
true;
16863 m_reporterPrefs.shouldReportAllAssertions =
true;
16866 JunitReporter::~JunitReporter() {}
16868 std::string JunitReporter::getDescription() {
16869 return "Reports test results in an XML format that looks like Ant's junitreport target";
16872 void JunitReporter::noMatchingTestCases( std::string
const& ) {}
16874 void JunitReporter::testRunStarting( TestRunInfo
const& runInfo ) {
16875 CumulativeReporterBase::testRunStarting( runInfo );
16876 xml.startElement(
"testsuites" );
16879 void JunitReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
16880 suiteTimer.start();
16881 stdOutForSuite.clear();
16882 stdErrForSuite.clear();
16883 unexpectedExceptions = 0;
16884 CumulativeReporterBase::testGroupStarting( groupInfo );
16887 void JunitReporter::testCaseStarting( TestCaseInfo
const& testCaseInfo ) {
16888 m_okToFail = testCaseInfo.okToFail();
16891 bool JunitReporter::assertionEnded( AssertionStats
const& assertionStats ) {
16892 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16893 unexpectedExceptions++;
16894 return CumulativeReporterBase::assertionEnded( assertionStats );
16897 void JunitReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
16898 stdOutForSuite += testCaseStats.stdOut;
16899 stdErrForSuite += testCaseStats.stdErr;
16900 CumulativeReporterBase::testCaseEnded( testCaseStats );
16903 void JunitReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
16904 double suiteTime = suiteTimer.getElapsedSeconds();
16905 CumulativeReporterBase::testGroupEnded( testGroupStats );
16906 writeGroup( *m_testGroups.back(), suiteTime );
16909 void JunitReporter::testRunEndedCumulative() {
16913 void JunitReporter::writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
16914 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
16916 TestGroupStats
const& stats = groupNode.value;
16917 xml.writeAttribute(
"name", stats.groupInfo.name );
16918 xml.writeAttribute(
"errors", unexpectedExceptions );
16919 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
16920 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
16921 xml.writeAttribute(
"hostname",
"tbd" );
16922 if( m_config->showDurations() == ShowDurations::Never )
16923 xml.writeAttribute(
"time",
"" );
16925 xml.writeAttribute(
"time", formatDuration( suiteTime ) );
16926 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
16929 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16930 auto properties = xml.scopedElement(
"properties");
16931 if (m_config->hasTestFilters()) {
16932 xml.scopedElement(
"property")
16933 .writeAttribute(
"name",
"filters")
16934 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16936 if (m_config->rngSeed() != 0) {
16937 xml.scopedElement(
"property")
16938 .writeAttribute(
"name",
"random-seed")
16939 .writeAttribute(
"value", m_config->rngSeed());
16944 for(
auto const& child : groupNode.children )
16945 writeTestCase( *child );
16947 xml.scopedElement(
"system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16948 xml.scopedElement(
"system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16951 void JunitReporter::writeTestCase( TestCaseNode
const& testCaseNode ) {
16952 TestCaseStats
const& stats = testCaseNode.value;
16956 assert( testCaseNode.children.size() == 1 );
16957 SectionNode
const& rootSection = *testCaseNode.children.front();
16959 std::string className = stats.testInfo.className;
16961 if( className.empty() ) {
16962 className = fileNameTag(stats.testInfo.tags);
16963 if ( className.empty() )
16964 className =
"global";
16967 if ( !m_config->name().empty() )
16968 className = m_config->name() + "." + className;
16970 writeSection( className,
"", rootSection, stats.testInfo.okToFail() );
16973 void JunitReporter::writeSection( std::string
const& className,
16974 std::string
const& rootName,
16975 SectionNode
const& sectionNode,
16976 bool testOkToFail) {
16977 std::string name = trim( sectionNode.stats.sectionInfo.name );
16978 if( !rootName.empty() )
16979 name = rootName + '/' + name;
16981 if( !sectionNode.assertions.empty() ||
16982 !sectionNode.stdOut.empty() ||
16983 !sectionNode.stdErr.empty() ) {
16984 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
16985 if( className.empty() ) {
16986 xml.writeAttribute(
"classname", name );
16987 xml.writeAttribute(
"name",
"root" );
16990 xml.writeAttribute(
"classname", className );
16991 xml.writeAttribute(
"name", name );
16993 xml.writeAttribute(
"time", formatDuration( sectionNode.stats.durationInSeconds ) );
16998 xml.writeAttribute(
"status",
"run" );
17000 if (sectionNode.stats.assertions.failedButOk) {
17001 xml.scopedElement(
"skipped")
17002 .writeAttribute(
"message",
"TEST_CASE tagged with !mayfail");
17005 writeAssertions( sectionNode );
17007 if( !sectionNode.stdOut.empty() )
17008 xml.scopedElement(
"system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
17009 if( !sectionNode.stdErr.empty() )
17010 xml.scopedElement(
"system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
17012 for(
auto const& childNode : sectionNode.childSections )
17013 if( className.empty() )
17014 writeSection( name,
"", *childNode, testOkToFail );
17016 writeSection( className, name, *childNode, testOkToFail );
17019 void JunitReporter::writeAssertions( SectionNode
const& sectionNode ) {
17020 for(
auto const& assertion : sectionNode.assertions )
17021 writeAssertion( assertion );
17024 void JunitReporter::writeAssertion( AssertionStats
const& stats ) {
17025 AssertionResult
const& result = stats.assertionResult;
17026 if( !result.isOk() ) {
17027 std::string elementName;
17028 switch( result.getResultType() ) {
17029 case ResultWas::ThrewException:
17030 case ResultWas::FatalErrorCondition:
17031 elementName =
"error";
17033 case ResultWas::ExplicitFailure:
17034 case ResultWas::ExpressionFailed:
17035 case ResultWas::DidntThrowException:
17036 elementName =
"failure";
17040 case ResultWas::Info:
17041 case ResultWas::Warning:
17042 case ResultWas::Ok:
17043 case ResultWas::Unknown:
17044 case ResultWas::FailureBit:
17045 case ResultWas::Exception:
17046 elementName =
"internalError";
17050 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17052 xml.writeAttribute(
"message", result.getExpression() );
17053 xml.writeAttribute(
"type", result.getTestMacroName() );
17055 ReusableStringStream rss;
17056 if (stats.totals.assertions.total() > 0) {
17057 rss <<
"FAILED" <<
":\n";
17058 if (result.hasExpression()) {
17060 rss << result.getExpressionInMacro();
17063 if (result.hasExpandedExpression()) {
17064 rss <<
"with expansion:\n";
17065 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
17071 if( !result.getMessage().empty() )
17072 rss << result.getMessage() <<
'\n';
17073 for(
auto const& msg : stats.infoMessages )
17074 if( msg.type == ResultWas::Info )
17075 rss << msg.message <<
'\n';
17077 rss <<
"at " << result.getSourceInfo();
17078 xml.writeText( rss.str(), XmlFormatting::Newline );
17082 CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
17092 ListeningReporter::ListeningReporter() {
17094 m_preferences.shouldReportAllAssertions =
true;
17097 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17098 m_listeners.push_back( std::move( listener ) );
17101 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17102 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
17103 m_reporter = std::move( reporter );
17104 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17107 ReporterPreferences ListeningReporter::getPreferences()
const {
17108 return m_preferences;
17111 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17112 return std::set<Verbosity>{ };
17115 void ListeningReporter::noMatchingTestCases( std::string
const& spec ) {
17116 for (
auto const& listener : m_listeners ) {
17117 listener->noMatchingTestCases( spec );
17119 m_reporter->noMatchingTestCases( spec );
17122 void ListeningReporter::reportInvalidArguments(std::string
const&arg){
17123 for (
auto const& listener : m_listeners ) {
17124 listener->reportInvalidArguments( arg );
17126 m_reporter->reportInvalidArguments( arg );
17129#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17130 void ListeningReporter::benchmarkPreparing( std::string
const& name ) {
17131 for (
auto const& listener : m_listeners) {
17132 listener->benchmarkPreparing(name);
17134 m_reporter->benchmarkPreparing(name);
17136 void ListeningReporter::benchmarkStarting( BenchmarkInfo
const& benchmarkInfo ) {
17137 for (
auto const& listener : m_listeners ) {
17138 listener->benchmarkStarting( benchmarkInfo );
17140 m_reporter->benchmarkStarting( benchmarkInfo );
17142 void ListeningReporter::benchmarkEnded( BenchmarkStats<>
const& benchmarkStats ) {
17143 for (
auto const& listener : m_listeners ) {
17144 listener->benchmarkEnded( benchmarkStats );
17146 m_reporter->benchmarkEnded( benchmarkStats );
17149 void ListeningReporter::benchmarkFailed( std::string
const& error ) {
17150 for (
auto const& listener : m_listeners) {
17151 listener->benchmarkFailed(error);
17153 m_reporter->benchmarkFailed(error);
17157 void ListeningReporter::testRunStarting( TestRunInfo
const& testRunInfo ) {
17158 for (
auto const& listener : m_listeners ) {
17159 listener->testRunStarting( testRunInfo );
17161 m_reporter->testRunStarting( testRunInfo );
17164 void ListeningReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17165 for (
auto const& listener : m_listeners ) {
17166 listener->testGroupStarting( groupInfo );
17168 m_reporter->testGroupStarting( groupInfo );
17171 void ListeningReporter::testCaseStarting( TestCaseInfo
const& testInfo ) {
17172 for (
auto const& listener : m_listeners ) {
17173 listener->testCaseStarting( testInfo );
17175 m_reporter->testCaseStarting( testInfo );
17178 void ListeningReporter::sectionStarting( SectionInfo
const& sectionInfo ) {
17179 for (
auto const& listener : m_listeners ) {
17180 listener->sectionStarting( sectionInfo );
17182 m_reporter->sectionStarting( sectionInfo );
17185 void ListeningReporter::assertionStarting( AssertionInfo
const& assertionInfo ) {
17186 for (
auto const& listener : m_listeners ) {
17187 listener->assertionStarting( assertionInfo );
17189 m_reporter->assertionStarting( assertionInfo );
17193 bool ListeningReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17194 for(
auto const& listener : m_listeners ) {
17195 static_cast<void>( listener->assertionEnded( assertionStats ) );
17197 return m_reporter->assertionEnded( assertionStats );
17200 void ListeningReporter::sectionEnded( SectionStats
const& sectionStats ) {
17201 for (
auto const& listener : m_listeners ) {
17202 listener->sectionEnded( sectionStats );
17204 m_reporter->sectionEnded( sectionStats );
17207 void ListeningReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17208 for (
auto const& listener : m_listeners ) {
17209 listener->testCaseEnded( testCaseStats );
17211 m_reporter->testCaseEnded( testCaseStats );
17214 void ListeningReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17215 for (
auto const& listener : m_listeners ) {
17216 listener->testGroupEnded( testGroupStats );
17218 m_reporter->testGroupEnded( testGroupStats );
17221 void ListeningReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17222 for (
auto const& listener : m_listeners ) {
17223 listener->testRunEnded( testRunStats );
17225 m_reporter->testRunEnded( testRunStats );
17228 void ListeningReporter::skipTest( TestCaseInfo
const& testInfo ) {
17229 for (
auto const& listener : m_listeners ) {
17230 listener->skipTest( testInfo );
17232 m_reporter->skipTest( testInfo );
17235 bool ListeningReporter::isMulti()
const {
17243#if defined(_MSC_VER)
17244#pragma warning(push)
17245#pragma warning(disable:4061)
17251 XmlReporter::XmlReporter( ReporterConfig
const& _config )
17252 : StreamingReporterBase( _config ),
17253 m_xml(_config.stream())
17255 m_reporterPrefs.shouldRedirectStdOut =
true;
17256 m_reporterPrefs.shouldReportAllAssertions =
true;
17259 XmlReporter::~XmlReporter() =
default;
17261 std::string XmlReporter::getDescription() {
17262 return "Reports test results as an XML document";
17265 std::string XmlReporter::getStylesheetRef()
const {
17266 return std::string();
17269 void XmlReporter::writeSourceInfo( SourceLineInfo
const& sourceInfo ) {
17271 .writeAttribute(
"filename", sourceInfo.file )
17272 .writeAttribute(
"line", sourceInfo.line );
17275 void XmlReporter::noMatchingTestCases( std::string
const& s ) {
17276 StreamingReporterBase::noMatchingTestCases( s );
17279 void XmlReporter::testRunStarting( TestRunInfo
const& testInfo ) {
17280 StreamingReporterBase::testRunStarting( testInfo );
17281 std::string stylesheetRef = getStylesheetRef();
17282 if( !stylesheetRef.empty() )
17283 m_xml.writeStylesheetRef( stylesheetRef );
17284 m_xml.startElement(
"Catch" );
17285 if( !m_config->name().empty() )
17286 m_xml.writeAttribute(
"name", m_config->name() );
17287 if (m_config->testSpec().hasFilters())
17288 m_xml.writeAttribute(
"filters", serializeFilters( m_config->getTestsOrTags() ) );
17289 if( m_config->rngSeed() != 0 )
17290 m_xml.scopedElement(
"Randomness" )
17291 .writeAttribute(
"seed", m_config->rngSeed() );
17294 void XmlReporter::testGroupStarting( GroupInfo
const& groupInfo ) {
17295 StreamingReporterBase::testGroupStarting( groupInfo );
17296 m_xml.startElement(
"Group" )
17297 .writeAttribute(
"name", groupInfo.name );
17300 void XmlReporter::testCaseStarting( TestCaseInfo
const& testInfo ) {
17301 StreamingReporterBase::testCaseStarting(testInfo);
17302 m_xml.startElement(
"TestCase" )
17303 .writeAttribute(
"name", trim( testInfo.name ) )
17304 .writeAttribute(
"description", testInfo.description )
17305 .writeAttribute(
"tags", testInfo.tagsAsString() );
17307 writeSourceInfo( testInfo.lineInfo );
17309 if ( m_config->showDurations() == ShowDurations::Always )
17310 m_testCaseTimer.start();
17311 m_xml.ensureTagClosed();
17314 void XmlReporter::sectionStarting( SectionInfo
const& sectionInfo ) {
17315 StreamingReporterBase::sectionStarting( sectionInfo );
17316 if( m_sectionDepth++ > 0 ) {
17317 m_xml.startElement(
"Section" )
17318 .writeAttribute(
"name", trim( sectionInfo.name ) );
17319 writeSourceInfo( sectionInfo.lineInfo );
17320 m_xml.ensureTagClosed();
17324 void XmlReporter::assertionStarting( AssertionInfo
const& ) { }
17326 bool XmlReporter::assertionEnded( AssertionStats
const& assertionStats ) {
17328 AssertionResult
const& result = assertionStats.assertionResult;
17330 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17332 if( includeResults || result.getResultType() == ResultWas::Warning ) {
17334 for(
auto const& msg : assertionStats.infoMessages ) {
17335 if( msg.type == ResultWas::Info && includeResults ) {
17336 m_xml.scopedElement(
"Info" )
17337 .writeText( msg.message );
17338 }
else if ( msg.type == ResultWas::Warning ) {
17339 m_xml.scopedElement(
"Warning" )
17340 .writeText( msg.message );
17346 if( !includeResults && result.getResultType() != ResultWas::Warning )
17350 if( result.hasExpression() ) {
17351 m_xml.startElement(
"Expression" )
17352 .writeAttribute(
"success", result.succeeded() )
17353 .writeAttribute(
"type", result.getTestMacroName() );
17355 writeSourceInfo( result.getSourceInfo() );
17357 m_xml.scopedElement(
"Original" )
17358 .writeText( result.getExpression() );
17359 m_xml.scopedElement(
"Expanded" )
17360 .writeText( result.getExpandedExpression() );
17364 switch( result.getResultType() ) {
17365 case ResultWas::ThrewException:
17366 m_xml.startElement(
"Exception" );
17367 writeSourceInfo( result.getSourceInfo() );
17368 m_xml.writeText( result.getMessage() );
17369 m_xml.endElement();
17371 case ResultWas::FatalErrorCondition:
17372 m_xml.startElement(
"FatalErrorCondition" );
17373 writeSourceInfo( result.getSourceInfo() );
17374 m_xml.writeText( result.getMessage() );
17375 m_xml.endElement();
17377 case ResultWas::Info:
17378 m_xml.scopedElement(
"Info" )
17379 .writeText( result.getMessage() );
17381 case ResultWas::Warning:
17384 case ResultWas::ExplicitFailure:
17385 m_xml.startElement(
"Failure" );
17386 writeSourceInfo( result.getSourceInfo() );
17387 m_xml.writeText( result.getMessage() );
17388 m_xml.endElement();
17394 if( result.hasExpression() )
17395 m_xml.endElement();
17400 void XmlReporter::sectionEnded( SectionStats
const& sectionStats ) {
17401 StreamingReporterBase::sectionEnded( sectionStats );
17402 if( --m_sectionDepth > 0 ) {
17403 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
17404 e.writeAttribute(
"successes", sectionStats.assertions.passed );
17405 e.writeAttribute(
"failures", sectionStats.assertions.failed );
17406 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
17408 if ( m_config->showDurations() == ShowDurations::Always )
17409 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
17411 m_xml.endElement();
17415 void XmlReporter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
17416 StreamingReporterBase::testCaseEnded( testCaseStats );
17417 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
17418 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
17420 if ( m_config->showDurations() == ShowDurations::Always )
17421 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17423 if( !testCaseStats.stdOut.empty() )
17424 m_xml.scopedElement(
"StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17425 if( !testCaseStats.stdErr.empty() )
17426 m_xml.scopedElement(
"StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17428 m_xml.endElement();
17431 void XmlReporter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
17432 StreamingReporterBase::testGroupEnded( testGroupStats );
17434 m_xml.scopedElement(
"OverallResults" )
17435 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
17436 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
17437 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
17438 m_xml.scopedElement(
"OverallResultsCases")
17439 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed )
17440 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed )
17441 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk );
17442 m_xml.endElement();
17445 void XmlReporter::testRunEnded( TestRunStats
const& testRunStats ) {
17446 StreamingReporterBase::testRunEnded( testRunStats );
17447 m_xml.scopedElement(
"OverallResults" )
17448 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
17449 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
17450 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
17451 m_xml.scopedElement(
"OverallResultsCases")
17452 .writeAttribute(
"successes", testRunStats.totals.testCases.passed )
17453 .writeAttribute(
"failures", testRunStats.totals.testCases.failed )
17454 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk );
17455 m_xml.endElement();
17458#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17459 void XmlReporter::benchmarkPreparing(std::string
const& name) {
17460 m_xml.startElement(
"BenchmarkResults")
17461 .writeAttribute(
"name", name);
17464 void XmlReporter::benchmarkStarting(BenchmarkInfo
const &info) {
17465 m_xml.writeAttribute(
"samples",
info.samples)
17466 .writeAttribute(
"resamples",
info.resamples)
17467 .writeAttribute(
"iterations",
info.iterations)
17468 .writeAttribute(
"clockResolution",
info.clockResolution)
17469 .writeAttribute(
"estimatedDuration",
info.estimatedDuration)
17470 .writeComment(
"All values in nano seconds");
17473 void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17474 m_xml.startElement(
"mean")
17475 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17476 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17477 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17478 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17479 m_xml.endElement();
17480 m_xml.startElement(
"standardDeviation")
17481 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17482 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17483 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17484 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17485 m_xml.endElement();
17486 m_xml.startElement(
"outliers")
17487 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17488 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17489 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17490 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17491 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17492 m_xml.endElement();
17493 m_xml.endElement();
17496 void XmlReporter::benchmarkFailed(std::string
const &error) {
17497 m_xml.scopedElement(
"failed").
17498 writeAttribute(
"message", error);
17499 m_xml.endElement();
17503 CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
17507#if defined(_MSC_VER)
17508#pragma warning(pop)
17513 LeakDetector leakDetector;
17517#pragma clang diagnostic pop
17523#ifdef CATCH_CONFIG_MAIN
17528#ifndef CATCH_INTERNAL_CDECL
17530#define CATCH_INTERNAL_CDECL __cdecl
17532#define CATCH_INTERNAL_CDECL
17536#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17538extern "C" int CATCH_INTERNAL_CDECL wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
17541int CATCH_INTERNAL_CDECL main (
int argc,
char * argv[]) {
17544 return Catch::Session().run( argc, argv );
17550int main (
int argc,
char *
const argv[]) {
17551#if !CATCH_ARC_ENABLED
17552 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17555 Catch::registerTestMethods();
17556 int result = Catch::Session().run( argc, (
char**)argv );
17558#if !CATCH_ARC_ENABLED
17570#if !defined(CATCH_CONFIG_IMPL_ONLY)
17572#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17573# undef CLARA_CONFIG_MAIN
17576#if !defined(CATCH_CONFIG_DISABLE)
17579#ifdef CATCH_CONFIG_PREFIX_ALL
17581#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17582#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17584#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17585#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17586#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17587#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17588#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17590#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17592#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17593#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17594#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17595#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17596#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17598#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17599#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17600#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17601#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17602#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17604#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17606#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17607#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17609#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17612#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17613#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17614#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17615#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17617#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17618#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17619#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17620#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17621#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17622#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17623#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17624#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17625#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17627#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17629#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17630#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17631#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17632#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17633#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17634#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17635#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17636#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17637#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17639#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17640#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17641#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17642#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17643#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17644#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17645#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17646#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17649#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17650#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
17651#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17653#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
17654#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17658#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17659#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17660#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17661#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17662#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17663#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17664#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17665#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17667#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17668#define CATCH_BENCHMARK(...) \
17669 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__,,))
17670#define CATCH_BENCHMARK_ADVANCED(name) \
17671 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17677#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17678#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17680#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17681#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17682#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17683#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17684#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17686#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17688#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17689#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17690#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17691#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17692#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17694#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17695#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17696#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17697#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17698#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17700#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17702#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17703#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17705#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17708#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17709#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17710#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17711#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17713#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17714#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17715#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17716#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17717#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17718#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17719#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17720#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17721#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17722#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17724#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17725#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17726#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17727#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17728#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17729#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17730#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17731#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17732#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17733#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17734#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17736#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17737#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17738#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17739#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17740#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17741#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17742#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17743#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17744#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17745#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17748#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17749#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17750#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17752#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
17753#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17758#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17761#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17762#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17764#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17765#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17766#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17767#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17768#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17769#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17771#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17772#define BENCHMARK(...) \
17773 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__,,))
17774#define BENCHMARK_ADVANCED(name) \
17775 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17784#ifdef CATCH_CONFIG_PREFIX_ALL
17786#define CATCH_REQUIRE( ... ) (void)(0)
17787#define CATCH_REQUIRE_FALSE( ... ) (void)(0)
17789#define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17790#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17791#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17792#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17793#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17795#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17797#define CATCH_CHECK( ... ) (void)(0)
17798#define CATCH_CHECK_FALSE( ... ) (void)(0)
17799#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
17800#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17801#define CATCH_CHECK_NOFAIL( ... ) (void)(0)
17803#define CATCH_CHECK_THROWS( ... ) (void)(0)
17804#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17805#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17806#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17807#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17809#define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17811#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17812#define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
17814#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17817#define CATCH_INFO( msg ) (void)(0)
17818#define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17819#define CATCH_WARN( msg ) (void)(0)
17820#define CATCH_CAPTURE( msg ) (void)(0)
17822#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17823#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17824#define CATCH_METHOD_AS_TEST_CASE( method, ... )
17825#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17826#define CATCH_SECTION( ... )
17827#define CATCH_DYNAMIC_SECTION( ... )
17828#define CATCH_FAIL( ... ) (void)(0)
17829#define CATCH_FAIL_CHECK( ... ) (void)(0)
17830#define CATCH_SUCCEED( ... ) (void)(0)
17832#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17834#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17835#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17836#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17837#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17838#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17839#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17840#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17841#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17842#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17844#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17845#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17846#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17847#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17848#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17849#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17850#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17851#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17855#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17856#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 )
17857#define CATCH_GIVEN( desc )
17858#define CATCH_AND_GIVEN( desc )
17859#define CATCH_WHEN( desc )
17860#define CATCH_AND_WHEN( desc )
17861#define CATCH_THEN( desc )
17862#define CATCH_AND_THEN( desc )
17864#define CATCH_STATIC_REQUIRE( ... ) (void)(0)
17865#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17870#define REQUIRE( ... ) (void)(0)
17871#define REQUIRE_FALSE( ... ) (void)(0)
17873#define REQUIRE_THROWS( ... ) (void)(0)
17874#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17875#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17876#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17877#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17879#define REQUIRE_NOTHROW( ... ) (void)(0)
17881#define CHECK( ... ) (void)(0)
17882#define CHECK_FALSE( ... ) (void)(0)
17883#define CHECKED_IF( ... ) if (__VA_ARGS__)
17884#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17885#define CHECK_NOFAIL( ... ) (void)(0)
17887#define CHECK_THROWS( ... ) (void)(0)
17888#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17889#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17890#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17891#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17893#define CHECK_NOTHROW( ... ) (void)(0)
17895#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17896#define CHECK_THAT( arg, matcher ) (void)(0)
17898#define REQUIRE_THAT( arg, matcher ) (void)(0)
17901#define INFO( msg ) (void)(0)
17902#define UNSCOPED_INFO( msg ) (void)(0)
17903#define WARN( msg ) (void)(0)
17904#define CAPTURE( ... ) (void)(0)
17906#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17907#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17908#define METHOD_AS_TEST_CASE( method, ... )
17909#define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17910#define SECTION( ... )
17911#define DYNAMIC_SECTION( ... )
17912#define FAIL( ... ) (void)(0)
17913#define FAIL_CHECK( ... ) (void)(0)
17914#define SUCCEED( ... ) (void)(0)
17915#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17917#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17918#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17919#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17920#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17921#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17922#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17923#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17924#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17925#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17927#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17928#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17929#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17930#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17931#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17932#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17933#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17934#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17937#define STATIC_REQUIRE( ... ) (void)(0)
17938#define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17942#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17945#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ) )
17946#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className )
17948#define GIVEN( desc )
17949#define AND_GIVEN( desc )
17950#define WHEN( desc )
17951#define AND_WHEN( desc )
17952#define THEN( desc )
17953#define AND_THEN( desc )
17966# pragma warning(pop)
17968# pragma clang diagnostic pop
17970#elif defined __GNUC__
17971# pragma GCC diagnostic pop
std::ostream & operator<<(std::ostream &out, const CellType celltype)
Allow Standard c++ streams to print out our enum values as text.
Definition: Cell.cpp:2038
std::vector< Item > Children(const Item &item)
The parts of an item, in reading order; empty if it has none.
Definition: OutputNavigation.cpp:254
@ count
Not a check: the number of checks.
@ warning
Works, but not fully: some feature won't.
@ info
Not a problem, but worth knowing (e.g.
Definition: diagrams_c.h:5
Definition: catch.hpp:2549
Definition: catch.hpp:2225
Definition: catch.hpp:2653
Definition: catch.hpp:3079
Definition: catch.hpp:1565
Definition: catch.hpp:3022
Definition: catch.hpp:2339
Definition: catch.hpp:3920
Definition: catch.hpp:4298
Definition: catch.hpp:4157
Definition: catch.hpp:3968
Definition: catch.hpp:3846
Definition: catch.hpp:3987
Definition: catch.hpp:4011
Definition: catch.hpp:4713
Definition: catch.hpp:4257
Definition: catch.hpp:4604
Definition: catch.hpp:4626
Definition: catch.hpp:4668
Definition: catch.hpp:4201
Definition: catch.hpp:3954
Definition: catch.hpp:4121
Definition: catch.hpp:2527
Definition: catch.hpp:3771
Definition: catch.hpp:3400
Definition: catch.hpp:3496
Definition: catch.hpp:3244
Definition: catch.hpp:491
Definition: catch.hpp:4410
Definition: catch.hpp:1441
Definition: catch.hpp:2642
Definition: catch.hpp:2912
Definition: catch.hpp:4559
A non-owning string class (similar to the forthcoming std::string_view) Note that,...
Definition: catch.hpp:606
Definition: catch.hpp:4808
Definition: catch.hpp:963
Definition: catch.hpp:2895
Definition: catch.hpp:2301
Definition: diagrams_e.h:4
A class that is inherited from the external class Test.
Definition: tag.cpp:5
void func()
function in group 1
Definition: group.cpp:13
detail namespace with internal helper functions
Definition: json.hpp:249
@ object
object (unordered set of name/value pairs)
std::size_t hash(const BasicJsonType &j)
hash a JSON value
Definition: json.hpp:6022
StringType escape(StringType s)
string escaping as described in RFC 6901 (Sect.
Definition: json.hpp:2990
Coord add(Coord c1, Coord c2)
This function returns the addition of c1 and c2, i.e: (c1.x+c2.x,c1.y+c2.y)
Definition: restypedef.cpp:23
Definition: catch.hpp:1398
Definition: catch.hpp:2544
Definition: catch.hpp:987
Definition: catch.hpp:486
Definition: catch.hpp:2830
Definition: catch.hpp:2415
Definition: catch.hpp:1467
Definition: catch.hpp:3942
Definition: catch.hpp:4061
Definition: catch.hpp:4513
Definition: catch.hpp:4360
Definition: catch.hpp:3016
Definition: catch.hpp:3011
Definition: catch.hpp:3860
Definition: catch.hpp:4369
Definition: catch.hpp:1477
Definition: catch.hpp:2977
Definition: catch.hpp:2966
Definition: catch.hpp:2459
Definition: catch.hpp:4841
Definition: catch.hpp:1434
Definition: catch.hpp:580
Definition: catch.hpp:572
Definition: catch.hpp:2203
Definition: catch.hpp:3430
Definition: catch.hpp:3455
Definition: catch.hpp:3439
Definition: catch.hpp:3289
Definition: catch.hpp:3322
Definition: catch.hpp:3357
Definition: catch.hpp:3281
Definition: catch.hpp:3263
Definition: catch.hpp:3540
Definition: catch.hpp:3561
Definition: catch.hpp:3569
Definition: catch.hpp:3557
Definition: catch.hpp:3574
Definition: catch.hpp:3565
Definition: catch.hpp:3549
Definition: catch.hpp:3682
Definition: catch.hpp:3608
Definition: catch.hpp:3629
Definition: catch.hpp:3659
Definition: catch.hpp:3718
Definition: catch.hpp:2628
Definition: catch.hpp:2600
Definition: catch.hpp:2617
Definition: catch.hpp:549
Definition: catch.hpp:1378
Definition: catch.hpp:1354
Definition: catch.hpp:4494
Definition: catch.hpp:2877
Definition: catch.hpp:2861
Definition: catch.hpp:4489
Definition: catch.hpp:502
Definition: catch.hpp:534
Definition: catch.hpp:1616
Definition: catch.hpp:4773
Definition: catch.hpp:2522
Definition: catch.hpp:2843
Definition: catch.hpp:4499
Definition: catch.hpp:4504
Definition: catch.hpp:4483
Definition: catch.hpp:926
Definition: catch.hpp:1999
Definition: catch.hpp:1994
Definition: catch.hpp:929
Definition: catch.hpp:937
Definition: catch.hpp:2008
Definition: catch.hpp:3217
Definition: catch.hpp:928
Definition: catch.hpp:481
int open(const char *, int)
Opens a file descriptor.
int errno
Contains the last error code.
Definition: structcmd.h:53
int close(int)
Closes the file descriptor fd.
size_t write(int, const char *, size_t)
Writes count bytes from buf to the filedescriptor fd.